@namzu/sdk 69.0.0 → 69.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (303) hide show
  1. package/CHANGELOG.md +61 -0
  2. package/dist/agents/QueryAgent.d.ts.map +1 -1
  3. package/dist/agents/QueryAgent.js +2 -0
  4. package/dist/agents/QueryAgent.js.map +1 -1
  5. package/dist/authorization/skill-grant.d.ts.map +1 -1
  6. package/dist/authorization/skill-grant.js +1 -0
  7. package/dist/authorization/skill-grant.js.map +1 -1
  8. package/dist/bridge/acp/permission.d.ts +10 -0
  9. package/dist/bridge/acp/permission.d.ts.map +1 -1
  10. package/dist/bridge/acp/permission.js.map +1 -1
  11. package/dist/bridge/acp/server.d.ts.map +1 -1
  12. package/dist/bridge/acp/server.js +1 -0
  13. package/dist/bridge/acp/server.js.map +1 -1
  14. package/dist/connector/index.d.ts +2 -2
  15. package/dist/connector/index.d.ts.map +1 -1
  16. package/dist/connector/index.js +1 -1
  17. package/dist/connector/index.js.map +1 -1
  18. package/dist/connector/mcp/client.d.ts +29 -0
  19. package/dist/connector/mcp/client.d.ts.map +1 -1
  20. package/dist/connector/mcp/client.js +59 -2
  21. package/dist/connector/mcp/client.js.map +1 -1
  22. package/dist/connector/mcp/errors.d.ts +7 -0
  23. package/dist/connector/mcp/errors.d.ts.map +1 -1
  24. package/dist/connector/mcp/errors.js +14 -0
  25. package/dist/connector/mcp/errors.js.map +1 -1
  26. package/dist/connector/mcp/index.d.ts +5 -1
  27. package/dist/connector/mcp/index.d.ts.map +1 -1
  28. package/dist/connector/mcp/index.js +3 -1
  29. package/dist/connector/mcp/index.js.map +1 -1
  30. package/dist/connector/mcp/skill-source.d.ts +144 -0
  31. package/dist/connector/mcp/skill-source.d.ts.map +1 -0
  32. package/dist/connector/mcp/skill-source.js +375 -0
  33. package/dist/connector/mcp/skill-source.js.map +1 -0
  34. package/dist/connector/mcp/skills.d.ts +137 -0
  35. package/dist/connector/mcp/skills.d.ts.map +1 -0
  36. package/dist/connector/mcp/skills.js +303 -0
  37. package/dist/connector/mcp/skills.js.map +1 -0
  38. package/dist/network/audit.d.ts +1 -1
  39. package/dist/network/audit.d.ts.map +1 -1
  40. package/dist/network/audit.js +2 -0
  41. package/dist/network/audit.js.map +1 -1
  42. package/dist/network/computer.d.ts +107 -0
  43. package/dist/network/computer.d.ts.map +1 -0
  44. package/dist/network/computer.js +250 -0
  45. package/dist/network/computer.js.map +1 -0
  46. package/dist/network/index.d.ts +2 -0
  47. package/dist/network/index.d.ts.map +1 -1
  48. package/dist/network/index.js +1 -0
  49. package/dist/network/index.js.map +1 -1
  50. package/dist/network/join.d.ts +3 -1
  51. package/dist/network/join.d.ts.map +1 -1
  52. package/dist/network/join.js +6 -3
  53. package/dist/network/join.js.map +1 -1
  54. package/dist/network/roster.d.ts +5 -0
  55. package/dist/network/roster.d.ts.map +1 -1
  56. package/dist/network/roster.js.map +1 -1
  57. package/dist/network/service.d.ts +12 -2
  58. package/dist/network/service.d.ts.map +1 -1
  59. package/dist/network/service.js +377 -52
  60. package/dist/network/service.js.map +1 -1
  61. package/dist/network/store.d.ts +10 -0
  62. package/dist/network/store.d.ts.map +1 -1
  63. package/dist/network/store.js +25 -3
  64. package/dist/network/store.js.map +1 -1
  65. package/dist/network/wire.d.ts +2 -0
  66. package/dist/network/wire.d.ts.map +1 -1
  67. package/dist/network/wire.js +5 -0
  68. package/dist/network/wire.js.map +1 -1
  69. package/dist/plugin/shell-hook-tool-names.d.ts.map +1 -1
  70. package/dist/plugin/shell-hook-tool-names.js +1 -0
  71. package/dist/plugin/shell-hook-tool-names.js.map +1 -1
  72. package/dist/plugin/shell-hook.d.ts +8 -3
  73. package/dist/plugin/shell-hook.d.ts.map +1 -1
  74. package/dist/plugin/shell-hook.js +132 -7
  75. package/dist/plugin/shell-hook.js.map +1 -1
  76. package/dist/provider/fallback.d.ts.map +1 -1
  77. package/dist/provider/fallback.js +4 -0
  78. package/dist/provider/fallback.js.map +1 -1
  79. package/dist/provider/idle-timeout.d.ts.map +1 -1
  80. package/dist/provider/idle-timeout.js +3 -0
  81. package/dist/provider/idle-timeout.js.map +1 -1
  82. package/dist/provider/model-window-suffix.d.ts.map +1 -1
  83. package/dist/provider/model-window-suffix.js +1 -0
  84. package/dist/provider/model-window-suffix.js.map +1 -1
  85. package/dist/provider/retry.d.ts.map +1 -1
  86. package/dist/provider/retry.js +3 -0
  87. package/dist/provider/retry.js.map +1 -1
  88. package/dist/public-runtime.d.ts +9 -6
  89. package/dist/public-runtime.d.ts.map +1 -1
  90. package/dist/public-runtime.js +11 -4
  91. package/dist/public-runtime.js.map +1 -1
  92. package/dist/public-tools.d.ts +5 -4
  93. package/dist/public-tools.d.ts.map +1 -1
  94. package/dist/public-tools.js +5 -3
  95. package/dist/public-tools.js.map +1 -1
  96. package/dist/public-types.d.ts +3 -1
  97. package/dist/public-types.d.ts.map +1 -1
  98. package/dist/runtime/query/executor/tool-call-admission.d.ts.map +1 -1
  99. package/dist/runtime/query/executor/tool-call-admission.js +10 -1
  100. package/dist/runtime/query/executor/tool-call-admission.js.map +1 -1
  101. package/dist/runtime/query/executor.d.ts +12 -0
  102. package/dist/runtime/query/executor.d.ts.map +1 -1
  103. package/dist/runtime/query/executor.js +43 -9
  104. package/dist/runtime/query/executor.js.map +1 -1
  105. package/dist/runtime/query/index.d.ts +4 -0
  106. package/dist/runtime/query/index.d.ts.map +1 -1
  107. package/dist/runtime/query/index.js +32 -0
  108. package/dist/runtime/query/index.js.map +1 -1
  109. package/dist/runtime/query/review-policy.d.ts +2 -2
  110. package/dist/runtime/query/review-policy.d.ts.map +1 -1
  111. package/dist/runtime/query/review-policy.js +2 -2
  112. package/dist/runtime/query/review-policy.js.map +1 -1
  113. package/dist/runtime/query/shell-line-escalation.d.ts +24 -0
  114. package/dist/runtime/query/shell-line-escalation.d.ts.map +1 -0
  115. package/dist/runtime/query/shell-line-escalation.js +38 -0
  116. package/dist/runtime/query/shell-line-escalation.js.map +1 -0
  117. package/dist/runtime/query/tooling.d.ts +7 -0
  118. package/dist/runtime/query/tooling.d.ts.map +1 -1
  119. package/dist/runtime/query/tooling.js +2 -0
  120. package/dist/runtime/query/tooling.js.map +1 -1
  121. package/dist/runtime/query/turn/outcome-ledger.d.ts.map +1 -1
  122. package/dist/runtime/query/turn/outcome-ledger.js +11 -0
  123. package/dist/runtime/query/turn/outcome-ledger.js.map +1 -1
  124. package/dist/scheduler/local.d.ts.map +1 -1
  125. package/dist/scheduler/local.js +3 -1
  126. package/dist/scheduler/local.js.map +1 -1
  127. package/dist/skills/index.d.ts +4 -0
  128. package/dist/skills/index.d.ts.map +1 -1
  129. package/dist/skills/index.js +2 -0
  130. package/dist/skills/index.js.map +1 -1
  131. package/dist/skills/inline-shell-host.d.ts +103 -0
  132. package/dist/skills/inline-shell-host.d.ts.map +1 -0
  133. package/dist/skills/inline-shell-host.js +238 -0
  134. package/dist/skills/inline-shell-host.js.map +1 -0
  135. package/dist/skills/inline-shell.d.ts +176 -0
  136. package/dist/skills/inline-shell.d.ts.map +1 -0
  137. package/dist/skills/inline-shell.js +646 -0
  138. package/dist/skills/inline-shell.js.map +1 -0
  139. package/dist/store/index.d.ts +2 -0
  140. package/dist/store/index.d.ts.map +1 -1
  141. package/dist/store/index.js +1 -0
  142. package/dist/store/index.js.map +1 -1
  143. package/dist/store/task/file.d.ts +124 -0
  144. package/dist/store/task/file.d.ts.map +1 -0
  145. package/dist/store/task/file.js +498 -0
  146. package/dist/store/task/file.js.map +1 -0
  147. package/dist/teams/backend.d.ts +28 -0
  148. package/dist/teams/backend.d.ts.map +1 -0
  149. package/dist/teams/backend.js +2 -0
  150. package/dist/teams/backend.js.map +1 -0
  151. package/dist/teams/fs-sync.d.ts +19 -0
  152. package/dist/teams/fs-sync.d.ts.map +1 -0
  153. package/dist/teams/fs-sync.js +81 -0
  154. package/dist/teams/fs-sync.js.map +1 -0
  155. package/dist/teams/index.d.ts +14 -0
  156. package/dist/teams/index.d.ts.map +1 -0
  157. package/dist/teams/index.js +11 -0
  158. package/dist/teams/index.js.map +1 -0
  159. package/dist/teams/names.d.ts +15 -0
  160. package/dist/teams/names.d.ts.map +1 -0
  161. package/dist/teams/names.js +43 -0
  162. package/dist/teams/names.js.map +1 -0
  163. package/dist/teams/store.d.ts +133 -0
  164. package/dist/teams/store.d.ts.map +1 -0
  165. package/dist/teams/store.js +536 -0
  166. package/dist/teams/store.js.map +1 -0
  167. package/dist/teams/types.d.ts +97 -0
  168. package/dist/teams/types.d.ts.map +1 -0
  169. package/dist/teams/types.js +70 -0
  170. package/dist/teams/types.js.map +1 -0
  171. package/dist/tools/admit-facts.d.ts.map +1 -1
  172. package/dist/tools/admit-facts.js +9 -1
  173. package/dist/tools/admit-facts.js.map +1 -1
  174. package/dist/tools/builtins/computer-use.d.ts +56 -2
  175. package/dist/tools/builtins/computer-use.d.ts.map +1 -1
  176. package/dist/tools/builtins/computer-use.js +604 -90
  177. package/dist/tools/builtins/computer-use.js.map +1 -1
  178. package/dist/tools/builtins/index.d.ts +1 -1
  179. package/dist/tools/builtins/index.d.ts.map +1 -1
  180. package/dist/tools/builtins/index.js.map +1 -1
  181. package/dist/tools/builtins/skill.d.ts +31 -0
  182. package/dist/tools/builtins/skill.d.ts.map +1 -1
  183. package/dist/tools/builtins/skill.js +232 -88
  184. package/dist/tools/builtins/skill.js.map +1 -1
  185. package/dist/tools/task/create.d.ts.map +1 -1
  186. package/dist/tools/task/create.js +11 -2
  187. package/dist/tools/task/create.js.map +1 -1
  188. package/dist/tools/task/get.d.ts +8 -0
  189. package/dist/tools/task/get.d.ts.map +1 -0
  190. package/dist/tools/task/get.js +51 -0
  191. package/dist/tools/task/get.js.map +1 -0
  192. package/dist/tools/task/index.d.ts +7 -0
  193. package/dist/tools/task/index.d.ts.map +1 -1
  194. package/dist/tools/task/index.js +10 -2
  195. package/dist/tools/task/index.js.map +1 -1
  196. package/dist/tools/task/list.d.ts.map +1 -1
  197. package/dist/tools/task/list.js +10 -2
  198. package/dist/tools/task/list.js.map +1 -1
  199. package/dist/tools/task/number.d.ts +13 -0
  200. package/dist/tools/task/number.d.ts.map +1 -0
  201. package/dist/tools/task/number.js +30 -0
  202. package/dist/tools/task/number.js.map +1 -0
  203. package/dist/tools/task/present.d.ts.map +1 -1
  204. package/dist/tools/task/present.js +17 -3
  205. package/dist/tools/task/present.js.map +1 -1
  206. package/dist/tools/task/update.d.ts +2 -1
  207. package/dist/tools/task/update.d.ts.map +1 -1
  208. package/dist/tools/task/update.js +86 -19
  209. package/dist/tools/task/update.js.map +1 -1
  210. package/dist/types/acp/index.d.ts +10 -0
  211. package/dist/types/acp/index.d.ts.map +1 -1
  212. package/dist/types/agent/base.d.ts +4 -0
  213. package/dist/types/agent/base.d.ts.map +1 -1
  214. package/dist/types/agent/scheduler.d.ts +9 -0
  215. package/dist/types/agent/scheduler.d.ts.map +1 -1
  216. package/dist/types/computer-use/index.d.ts +7 -0
  217. package/dist/types/computer-use/index.d.ts.map +1 -1
  218. package/dist/types/computer-use/index.js.map +1 -1
  219. package/dist/types/connector/mcp.d.ts +10 -0
  220. package/dist/types/connector/mcp.d.ts.map +1 -1
  221. package/dist/types/permission/index.d.ts +20 -0
  222. package/dist/types/permission/index.d.ts.map +1 -1
  223. package/dist/types/permission/index.js +25 -0
  224. package/dist/types/permission/index.js.map +1 -1
  225. package/dist/types/plugin/index.d.ts +47 -3
  226. package/dist/types/plugin/index.d.ts.map +1 -1
  227. package/dist/types/plugin/index.js +4 -0
  228. package/dist/types/plugin/index.js.map +1 -1
  229. package/dist/types/provider/interface.d.ts +6 -0
  230. package/dist/types/provider/interface.d.ts.map +1 -1
  231. package/dist/types/tool/index.d.ts +28 -2
  232. package/dist/types/tool/index.d.ts.map +1 -1
  233. package/dist/types/tool/index.js.map +1 -1
  234. package/dist/types/tool/presentation.d.ts +4 -0
  235. package/dist/types/tool/presentation.d.ts.map +1 -1
  236. package/package.json +1 -1
  237. package/src/agents/QueryAgent.ts +2 -0
  238. package/src/authorization/skill-grant.ts +1 -0
  239. package/src/bridge/acp/permission.ts +11 -1
  240. package/src/bridge/acp/server.ts +1 -0
  241. package/src/connector/index.ts +27 -0
  242. package/src/connector/mcp/client.ts +71 -2
  243. package/src/connector/mcp/errors.ts +14 -0
  244. package/src/connector/mcp/index.ts +36 -0
  245. package/src/connector/mcp/skill-source.ts +499 -0
  246. package/src/connector/mcp/skills.ts +367 -0
  247. package/src/network/audit.ts +2 -0
  248. package/src/network/computer.ts +347 -0
  249. package/src/network/index.ts +20 -0
  250. package/src/network/join.ts +4 -2
  251. package/src/network/roster.ts +5 -0
  252. package/src/network/service.ts +492 -75
  253. package/src/network/store.ts +29 -3
  254. package/src/network/wire.ts +5 -0
  255. package/src/plugin/shell-hook-tool-names.ts +1 -0
  256. package/src/plugin/shell-hook.ts +144 -7
  257. package/src/provider/fallback.ts +4 -0
  258. package/src/provider/idle-timeout.ts +3 -0
  259. package/src/provider/model-window-suffix.ts +1 -0
  260. package/src/provider/retry.ts +3 -0
  261. package/src/public-runtime.ts +99 -0
  262. package/src/public-tools.ts +9 -0
  263. package/src/public-types.ts +28 -0
  264. package/src/runtime/query/executor/tool-call-admission.ts +10 -1
  265. package/src/runtime/query/executor.ts +57 -8
  266. package/src/runtime/query/index.ts +43 -0
  267. package/src/runtime/query/review-policy.ts +7 -1
  268. package/src/runtime/query/shell-line-escalation.ts +49 -0
  269. package/src/runtime/query/tooling.ts +6 -0
  270. package/src/runtime/query/turn/outcome-ledger.ts +11 -0
  271. package/src/scheduler/local.ts +3 -1
  272. package/src/skills/index.ts +43 -0
  273. package/src/skills/inline-shell-host.ts +303 -0
  274. package/src/skills/inline-shell.ts +765 -0
  275. package/src/store/index.ts +8 -0
  276. package/src/store/task/file.ts +641 -0
  277. package/src/teams/backend.ts +29 -0
  278. package/src/teams/fs-sync.ts +91 -0
  279. package/src/teams/index.ts +47 -0
  280. package/src/teams/names.ts +49 -0
  281. package/src/teams/store.ts +607 -0
  282. package/src/teams/types.ts +102 -0
  283. package/src/tools/admit-facts.ts +9 -1
  284. package/src/tools/builtins/computer-use.ts +689 -95
  285. package/src/tools/builtins/index.ts +1 -0
  286. package/src/tools/builtins/skill.ts +291 -95
  287. package/src/tools/task/create.ts +11 -2
  288. package/src/tools/task/get.ts +53 -0
  289. package/src/tools/task/index.ts +14 -2
  290. package/src/tools/task/list.ts +10 -2
  291. package/src/tools/task/number.ts +32 -0
  292. package/src/tools/task/present.ts +18 -3
  293. package/src/tools/task/update.ts +93 -19
  294. package/src/types/acp/index.ts +11 -1
  295. package/src/types/agent/base.ts +6 -0
  296. package/src/types/agent/scheduler.ts +9 -0
  297. package/src/types/computer-use/index.ts +7 -0
  298. package/src/types/connector/mcp.ts +10 -0
  299. package/src/types/permission/index.ts +29 -0
  300. package/src/types/plugin/index.ts +95 -39
  301. package/src/types/provider/interface.ts +7 -0
  302. package/src/types/tool/index.ts +23 -2
  303. package/src/types/tool/presentation.ts +2 -0
@@ -1,12 +1,34 @@
1
+ import { createHash } from 'node:crypto';
1
2
  import { z } from 'zod';
2
3
  import { modelReadsImages, resolveProviderCapabilities } from '../../provider/capabilities.js';
3
4
  import { sleep } from '../../utils/backoff.js';
4
5
  import { defineTool } from '../defineTool.js';
5
6
  import { neutralizeEnvelopeDelimiter, wrapUntrusted } from '../untrusted-envelope.js';
6
7
  import { ScreenshotFrames, assumedDisplay, desktopRectOnImage, pointOnImage, toDisplayPoint, toDisplayRect, toImagePoint, toWindowPoint, } from './computer-use-coordinates.js';
7
- import { STANDARD_SCREENSHOT_LIMITS, cropAndFitPng, fitPng, pngSize, } from './computer-use-image.js';
8
+ import { HIGH_RES_SCREENSHOT_LIMITS, STANDARD_SCREENSHOT_LIMITS, cropAndFitPng, fitPng, pngSize, } from './computer-use-image.js';
8
9
  import { coerceWindowId, windowKey } from './computer-use-window-id.js';
9
10
  export { HIGH_RES_SCREENSHOT_LIMITS, STANDARD_SCREENSHOT_LIMITS, screenshotTargetSize, } from './computer-use-image.js';
11
+ /**
12
+ * The limits to fit a screenshot to for `model`: the high-resolution tier for
13
+ * a model known to read it (the 4.7 and later models of the vendor behind that
14
+ * tier, with or without a vendor prefix or a dated suffix), the standard tier for every
15
+ * other model, including one the table does not know. A wrong "high" costs a
16
+ * rejected tool result; a wrong "standard" only costs detail, so an unknown
17
+ * model gets the standard tier.
18
+ */
19
+ export function screenshotLimitsForModel(model) {
20
+ if (model === undefined)
21
+ return STANDARD_SCREENSHOT_LIMITS;
22
+ const match = /claude-(?:opus|sonnet|haiku|fable)-(\d+)(?:[-.](\d{1,2})(?!\d))?/i.exec(model);
23
+ if (!match)
24
+ return STANDARD_SCREENSHOT_LIMITS;
25
+ const major = Number(match[1]);
26
+ const minor = match[2] === undefined ? 0 : Number(match[2]);
27
+ // A dated id such as `claude-sonnet-4-20250514` has no minor: the date is not one.
28
+ return major > 4 || (major === 4 && minor >= 7)
29
+ ? HIGH_RES_SCREENSHOT_LIMITS
30
+ : STANDARD_SCREENSHOT_LIMITS;
31
+ }
10
32
  export const COMPUTER_USE_TOOL_NAME = 'computer_use';
11
33
  const DEFAULT_SETTLE_MS = 500;
12
34
  const DEFAULT_MAX_BATCH_ACTIONS = 20;
@@ -33,8 +55,12 @@ async function settleAfterActions(host, windowId, settleMs, signal) {
33
55
  await sleep(settleMs, signal);
34
56
  }
35
57
  const MAX_LISTED_WINDOWS = 50;
36
- /** The most of a ui_snapshot the model is shown, in characters (about 4 000 tokens). */
37
- const MAX_UI_SNAPSHOT_CHARS = 14_000;
58
+ /** Steps after which a batch may end with the window's controls instead of a picture. */
59
+ const TREE_ENDING_STEPS = new Set(['ui_act', 'ui_do', 'type_text', 'key']);
60
+ /** Steps that aim at a pixel of a screenshot. */
61
+ const PIXEL_STEPS = new Set(['mouse_click', 'mouse_drag', 'scroll']);
62
+ /** The most of a ui_snapshot the model is shown, in characters (about 7 000 tokens). */
63
+ const MAX_UI_SNAPSHOT_CHARS = 24_000;
38
64
  /** The refs of earlier snapshots the tool still resolves for the host. */
39
65
  const MAX_HELD_UI_REFS = 4_000;
40
66
  /** The least confidence in the best control for the tool to act on it. */
@@ -43,6 +69,30 @@ const ADVICE_MIN_CONFIDENCE = 0.85;
43
69
  const ADVICE_MIN_MARGIN = 0.4;
44
70
  /** The most controls an advisor is asked about at once. */
45
71
  const MAX_ADVISED_CANDIDATES = 255;
72
+ /** How a browser is told apart in a grant: trimmed, lower case, spaces joined, without `.exe`. */
73
+ function browserKey(app) {
74
+ return deniedAppKey(app).replace(/\s+/g, '-');
75
+ }
76
+ /**
77
+ * The three ways forward after a browser window was not acted in, in the words the model offers
78
+ * the person. `own` names the first: the setting to change when it is `look`, the question when
79
+ * it is `ask`.
80
+ */
81
+ function browserWaysForward(name, setting) {
82
+ const first = setting === 'look'
83
+ ? `change Browser windows in Settings (computerUse.browserWindows) to Ask, so Namzu may click and type in ${name} once they allow it`
84
+ : `allow Namzu to click and type in ${name} for this conversation`;
85
+ return `Ways forward to offer the person, in plain words: ${first}; or continue in Namzu's own browser (the browser tool), where they sign in once; or they click in ${name} themselves while you guide them from screenshots.`;
86
+ }
87
+ /** What the tool says about browser windows, one paragraph, for its description. */
88
+ export function browserWindowsGuidance(setting) {
89
+ const care = 'Even where it is allowed, stop and ask the person before you type into a password field, submit payment or personal data, send or post something, delete, accept terms, or change organisation-wide admin settings.';
90
+ if (setting === 'act')
91
+ return `Browser windows are worked like any other application. The browser tool is Namzu's own browser, where the person signs in once; the person's own open browser is here. ${care}`;
92
+ if (setting === 'ask')
93
+ return `A browser window is only looked at until the person allows more: the first action aimed at one asks them whether Namzu may click and type in that browser for this conversation, and only their answer allows it. If it is refused or not asked yet, offer the person the ways forward in plain words: allow it for this conversation; continue in Namzu's own browser (the browser tool), where they sign in once; or they click while you guide them from screenshots. ${care}`;
94
+ return "A browser window is only looked at: act on a page with the browser tool, which is Namzu's own browser, where the person signs in once. To work in the browser window the person already has open, they can allow it in Settings (Browser windows), or click there themselves while you guide them from screenshots.";
95
+ }
46
96
  /** How an application name is compared: trimmed, lower case, without a trailing `.exe`. */
47
97
  function deniedAppKey(app) {
48
98
  return app
@@ -162,6 +212,10 @@ const uiSnapshotSchema = z.object({
162
212
  offset: z.number().int().min(0).max(1_000_000).optional(),
163
213
  /** Only controls whose text contains this, with the elements above them. */
164
214
  query: z.string().min(1).max(200).optional(),
215
+ /** Only controls of this role (comma-separated for several), with the elements above them. */
216
+ role: z.string().min(1).max(120).optional(),
217
+ /** Show the whole tree even where the window was read before (the default shows what changed). */
218
+ full: z.boolean().optional(),
165
219
  });
166
220
  const WAIT_FOR_CONDITIONS = [
167
221
  'element_appears',
@@ -315,24 +369,36 @@ const TERMINAL_APPS = /^(WindowsTerminal|OpenConsole|conhost|cmd|powershell|pwsh
315
369
  * Windows without `.exe`). The tool only looks at these: a page is worked
316
370
  * through the browser tool.
317
371
  */
318
- const BROWSER_APPS = /^(chrome|google-chrome(-stable|-beta|-unstable)?|chromium(-browser)?|msedge|microsoft-edge(-stable|-beta|-dev)?|firefox(-esr|-bin)?|brave(-browser)?|opera|vivaldi(-stable)?|arc-browser|safari|librewolf|waterfox|zen-browser|navigator|tor browser|iexplore|duckduckgo|yandex-?browser|thorium)$/i;
372
+ const BROWSER_APPS = /^(chrome|google-chrome(-stable|-beta|-unstable|-canary|-dev)?|chromium(-browser)?|msedge|microsoft-edge(-stable|-beta|-dev)?|firefox(-esr|-bin)?|brave(-browser)?|opera|vivaldi(-stable)?|arc-browser|safari|librewolf|waterfox|zen-browser|navigator|tor browser|iexplore|duckduckgo|yandex-?browser|thorium)$/i;
319
373
  /**
320
374
  * Editors and development environments, by process name. Like a terminal,
321
375
  * the tool may click in these but does not type or press keys in them: the
322
376
  * shell and the edit tools do that work without a screen.
323
377
  */
324
- const IDE_APPS = /^(code(-insiders|-oss)?|cursor|windsurf|zed|devenv|idea(64)?|pycharm(64)?|webstorm(64)?|goland(64)?|clion(64)?|rider(64)?|phpstorm(64)?|rubymine(64)?|datagrip(64)?|studio64|android-studio|jetbrains-[a-z-]+|sublime_text|subl|atom-editor|eclipse|netbeans(64)?|xcode|nova-editor|vscodium|codium|kate|gedit|vim|gvim|nvim-qt|emacs|lapce|jetbrains-fleet)$/i;
378
+ const IDE_APPS = /^(code(-insiders|-oss)?|visual-studio-code(-insiders)?|intellij-idea(-ce)?|cursor|windsurf|zed|devenv|idea(64)?|pycharm(64)?|webstorm(64)?|goland(64)?|clion(64)?|rider(64)?|phpstorm(64)?|rubymine(64)?|datagrip(64)?|studio64|android-studio|jetbrains-[a-z-]+|sublime_text|subl|atom-editor|eclipse|netbeans(64)?|xcode|nova-editor|vscodium|codium|kate|gedit|vim|gvim|nvim-qt|emacs|lapce|jetbrains-fleet)$/i;
325
379
  /** The tier of an application by the name a host reports for its window. */
326
380
  export function appTier(app) {
381
+ // Arc's macOS display name is the bare word; as a lower-case process name it is too generic.
382
+ if (appIs(BROWSER_APPS, app) || app.trim() === 'Arc')
383
+ return 'view';
384
+ if (appIs(TERMINAL_APPS, app) || appIs(IDE_APPS, app))
385
+ return 'click';
386
+ return 'full';
387
+ }
388
+ /**
389
+ * Whether an application name matches a family pattern. Hosts name a window's
390
+ * application differently: a process name on Windows and Linux (`msedge`,
391
+ * `sublime_text`), the display name on macOS (`Microsoft Edge`, `Sublime Text`).
392
+ * The name is tried as given and with its spaces joined by `-` and by `_`.
393
+ */
394
+ function appIs(pattern, app) {
327
395
  const name = app
328
396
  .trim()
329
397
  .replace(/\.exe$/i, '')
330
398
  .replace(/^.*[\\/]/, '');
331
- if (BROWSER_APPS.test(name))
332
- return 'view';
333
- if (TERMINAL_APPS.test(name) || IDE_APPS.test(name))
334
- return 'click';
335
- return 'full';
399
+ return (pattern.test(name) ||
400
+ pattern.test(name.replace(/\s+/g, '-')) ||
401
+ pattern.test(name.replace(/\s+/g, '_')));
336
402
  }
337
403
  /** Keys that only move a page: allowed in a view-only application. */
338
404
  const SCROLL_KEYS = /^(page_?up|page_?down|home|end|arrow_?(up|down|left|right)|up|down|space)$/i;
@@ -483,7 +549,7 @@ function unavailableHostActions(host, caps) {
483
549
  // ---------------------------------------------------------------------------
484
550
  // Model-facing description and schema
485
551
  // ---------------------------------------------------------------------------
486
- function buildDescription(host, caps, settings, advisor) {
552
+ function buildDescription(host, caps, settings, advisor, browser = 'look') {
487
553
  const available = availableActions(host, caps, advisor);
488
554
  const unavailable = unavailableHostActions(host, caps);
489
555
  const intro = hostActionAvailable(caps, 'screenshot')
@@ -505,12 +571,12 @@ function buildDescription(host, caps, settings, advisor) {
505
571
  return finish(lines, caps, available);
506
572
  if (available.includes('ui_snapshot'))
507
573
  lines.push("Work from the window's controls first: list_windows, then ui_snapshot {window_id}, then ui_act on a ref. This reaches a window that is behind others, does not move the user's pointer or take their screen, and does not depend on coordinates. Confirm an action by the result it reports (a control read back), by wait_for, or by a window screenshot. Click coordinates only in a window whose tree has no usable controls; a first coordinate click in a window that has a tree comes with a reminder.");
508
- lines.push('Coordinates: every x/y you send is a pixel of the most recent screenshot this tool returned — origin at its top-left, x to the right, y down — never a screen pixel. Each screenshot states its id and size (for example "s3: 1456x819"); stay inside it. Display screenshots map onto the display. To aim at an earlier display screenshot, pass its id as screenshot_id.', 'Take a screenshot before your first click on pixels.', "Look at the screen before you say what state an application is in. Never click links with computer use: a page is the browser tool's. Prefer a connected tool or a command line to the screen when one does the job.");
574
+ lines.push('Coordinates: every x/y you send is a pixel of the most recent screenshot this tool returned — origin at its top-left, x to the right, y down — never a screen pixel. Each screenshot states its id and size (for example "s3: 1456x819"); stay inside it. Display screenshots map onto the display. To aim at an earlier display screenshot, pass its id as screenshot_id.', 'Click coordinates need a screenshot to refer to; any action that changes something already returns one, so take one yourself only when none has been shown yet.', `Look at the screen before you say what state an application is in. ${browser === 'look' ? "Never click links with computer use: a page is the browser tool's." : 'Prefer the browser tool for a page; click in a browser window with computer use only where the browser rule allows it.'} Prefer a connected tool or a command line to the screen when one does the job.`);
509
575
  if (settings.screenshotAfterActions)
510
- lines.push(`After any action that changes something, the tool waits ${settings.settleMs} ms and returns a new screenshot — do not call screenshot again after acting.`);
511
- lines.push('zoom returns a closer, sharper view of region {x, y, width, height} of the screenshot; your coordinates still refer to the screenshot, not to the zoomed image.', `wait pauses for ms milliseconds (at most ${settings.maxWaitMs} per call, a batch's waits together) and then shows the screen.${available.includes('wait_for') ? ' Prefer wait_for to a fixed wait whenever you know what you are waiting for.' : ''}`);
576
+ lines.push(`After any action that changes something, the tool itself waits for the window to stop changing (at most ${settings.settleMs} ms) and then returns the result — do not add a wait or call screenshot after acting.`);
577
+ lines.push(`zoom returns a closer, sharper view of region {x, y, width, height} of the screenshot; your coordinates still refer to the screenshot, not to the zoomed image. It is for reading small text that ${available.includes('ui_snapshot') ? "the window's controls do not name" : 'the screenshot shows too small'}, not a step to take before acting: act on what you can already see.`, `wait pauses for ms milliseconds (at most ${settings.maxWaitMs} per call, a batch's waits together) and then shows the screen.${available.includes('wait_for') ? ' Prefer wait_for to a fixed wait whenever you know what you are waiting for.' : ''}`);
512
578
  if (available.includes('batch'))
513
- lines.push(`batch: {"type":"batch","actions":[...]} runs up to ${settings.maxBatchActions} actions in order, stops at the first one that fails, and returns one screenshot at the end. Every call costs a model round trip of several seconds, so put the steps you can already predict into one batch (click a field, type, press ENTER) rather than one call each — but end the batch at any step that should bring up a new window, and look before typing into it. A batch cannot contain screenshot${available.includes('ui_snapshot') ? ', zoom or ui_snapshot' : ' or zoom'}.`);
579
+ lines.push(`batch: {"type":"batch","actions":[...]} runs up to ${settings.maxBatchActions} actions in order, stops at the first one that fails (a ref that cannot be found or is ambiguous included, so nothing after it runs), and ends with what changed in the window's controls when you have read that window, or else one screenshot. The tool settles after each action, so a batch needs no wait between steps. Every call costs a model round trip of several seconds, so put the steps you can already predict into one batch (click a field, type, press ENTER) rather than one call each — but end the batch at any step that should bring up a new window, and look before typing into it. A batch cannot contain screenshot${available.includes('ui_snapshot') ? ', zoom or ui_snapshot' : ' or zoom'}.`);
514
580
  if (caps.displayServer === 'win32' &&
515
581
  available.includes('key') &&
516
582
  available.includes('type_text'))
@@ -520,9 +586,9 @@ function buildDescription(host, caps, settings, advisor) {
520
586
  if (available.includes('list_windows'))
521
587
  lines.push('list_windows names the open windows with their ids; focus_window brings one to the front.');
522
588
  if (windowCaptureAvailable(host, caps))
523
- lines.push(`When the user names an application or window, ${available.includes('list_windows') ? 'use list_windows then screenshot {window_id}' : 'use screenshot {window_id} with a host-provided window id'} to capture pixels for that window. Its x/y are pixels of that window image; clicks, drags, typing and keys target that window. Window pointer input is sent in the background first. If a click or drag is refused, inspect a fresh image before any other action; where the host can use the screen it may repeat a refused click once on the screen, and the result says so. ${caps.windowScroll === false ? `Window pixel scrolling is unavailable on this host; ${hostActionAvailable(caps, 'screenshot') ? 'deliberately take a display screenshot for display scrolling' : 'scroll by another means'}. ` : ''}Foreground text may briefly bring the verified window to the front: the host waits until the user has been still for a moment, puts their window back afterwards, and reports it as not delivered (safe to try again later) when the screen stays busy. ${host.beginTurn ? 'A result that says the user pressed Escape means stop: end your turn and say what is left undone. ' : ''}A browser window is only looked at: act on a page with the browser tool. A stale or moved window is refused; take a fresh window screenshot. ${hostActionAvailable(caps, 'screenshot') ? 'Plain screenshot still shows the display. ' : 'screenshot requires window_id on this host. '}Browser permission bubbles outside the window may be absent. If the window image is blank or shows another window, do not click it; focus the target and capture it again.`);
589
+ lines.push(`When the user names an application or window, ${available.includes('list_windows') ? 'use list_windows then screenshot {window_id}' : 'use screenshot {window_id} with a host-provided window id'} to capture pixels for that window. Its x/y are pixels of that window image; clicks, drags, typing and keys target that window. Window pointer input is sent in the background first. If a click or drag is refused, inspect a fresh image before any other action; where the host can use the screen it may repeat a refused click once on the screen, and the result says so. ${caps.windowScroll === false ? `Window pixel scrolling is unavailable on this host; ${hostActionAvailable(caps, 'screenshot') ? 'deliberately take a display screenshot for display scrolling' : 'scroll by another means'}. ` : ''}Foreground text may briefly bring the verified window to the front: the host waits until the user has been still for a moment, puts their window back afterwards, and reports it as not delivered (safe to try again later) when the screen stays busy. ${host.beginTurn ? 'A result that says the user pressed Escape means stop: end your turn and say what is left undone. ' : ''}${browserWindowsGuidance(browser)} A stale or moved window is refused; take a fresh window screenshot. ${hostActionAvailable(caps, 'screenshot') ? 'Plain screenshot still shows the display. ' : 'screenshot requires window_id on this host. '}Browser permission bubbles outside the window may be absent. If the window image is blank or shows another window, do not click it; focus the target and capture it again.`);
524
590
  if (available.includes('ui_snapshot'))
525
- lines.push(`ui_snapshot {window_id} reads a window's controls (its accessibility tree) as text, each control you can act on with a ref such as e12; without window_id it reads the window in front. A large window comes back as an outline: a region ends with "(+N more inside)" and has a ref; ui_snapshot {root: <that ref>} reads that region alone (a long one in pages: offset) and keeps every other ref usable, and ui_snapshot {query: <text>} lists only the controls whose text matches. ui_act {ref, action, value} acts on one control: invoke (press a button, open a menu item), set_value (replace a field's text with value), toggle, select, expand, collapse. A batch of ui_act steps (for example pressing several buttons) runs in one call. A ref names its control and stays usable after later snapshots and after you act: the control is found again by its id, its place and its name before anything is sent. If it cannot be found the step fails with STALE_REF, and if several controls fit it fails with AMBIGUOUS_TARGET; in both nothing was sent, so take a ui_snapshot and choose again.`, 'Each ui_act says what is known. "done, verified" means the control was read back and matches. "sent, not confirmed" means the input went out and nothing could check it: look (ui_snapshot, or a window screenshot) before repeating it, because repeating can act twice. A failure that says "not delivered" means nothing reached the control, so trying again, or another way, is safe. set_value on a control that does not take the value fails with that reason instead of being typed in; select on a list row selects it without opening it (invoke opens it).', ...(available.includes('wait_for')
591
+ lines.push(`ui_snapshot {window_id} reads a window's controls (its accessibility tree) as text, each control you can act on with a ref such as e12; without window_id it reads the window in front. A large window comes back as an outline: a region ends with "(+N more inside)" and has a ref; ui_snapshot {root: <that ref>} reads that region alone (a long one in pages: offset) and keeps every other ref usable, and ui_snapshot {query: <text>} lists only the controls whose text matches, and ui_snapshot {role: "Button"} only those of that type (both keep the elements above them). A window you have read before comes back as what changed since (+ added, ~ changed, - gone, or "no change"), with every earlier ref still usable; ui_snapshot {full: true} lists the whole tree. The result ends with the focused control and any selected text. A window screenshot of a window not yet read comes with its controls. ui_act {ref, action, value} acts on one control: invoke (press a button, open a menu item), set_value (replace a field's text with value), toggle, select, expand, collapse. A batch of ui_act steps (for example pressing several buttons) runs in one call. A ref names its control and stays usable after later snapshots and after you act: the control is found again by its id, its place and its name before anything is sent. If it cannot be found the step fails with STALE_REF, and if several controls fit it fails with AMBIGUOUS_TARGET; in both nothing was sent, so take a ui_snapshot and choose again.`, 'Each ui_act says what is known. "done, verified" means the control was read back and matches. "sent, not confirmed" means the input went out and nothing could check it: look (ui_snapshot, or a window screenshot) before repeating it, because repeating can act twice. A failure that says "not delivered" means nothing reached the control, so trying again, or another way, is safe. set_value on a control that does not take the value fails with that reason instead of being typed in; select on a list row selects it without opening it (invoke opens it).', ...(available.includes('wait_for')
526
592
  ? [
527
593
  `wait_for {until, match, window_id, timeout_ms} looks for an element (element_appears, element_gone; role narrows it), a text (text_appears, text_gone) or a window (window_appears, window_closed) and returns the window's controls as soon as it holds (at most ${settings.maxWaitMs} ms). Use it after an action that opens a dialog or loads a page, instead of a fixed wait. It is its own call, not part of a batch.`,
528
594
  ]
@@ -588,7 +654,7 @@ const ACTION_REQUIREMENTS = {
588
654
  wait: 'wait needs ms',
589
655
  list_windows: 'list_windows needs no other fields',
590
656
  focus_window: 'focus_window needs window_id',
591
- ui_snapshot: 'ui_snapshot takes an optional window_id, root (a ref to open) and query (text to find)',
657
+ ui_snapshot: 'ui_snapshot takes an optional window_id, root (a ref to open), query (text to find), role (a control type to list) and full (the whole tree instead of what changed)',
592
658
  wait_for: 'wait_for needs until and match; role, window_id and timeout_ms are optional',
593
659
  ui_act: 'ui_act needs ref and action, and value for set_value',
594
660
  ui_do: 'ui_do needs target (the control, in words) and action, and value for set_value',
@@ -684,6 +750,14 @@ function hostModelSchema(host, caps, settings, advisor) {
684
750
  type: 'string',
685
751
  description: 'For ui_snapshot: list only the controls whose text contains this (case-insensitive), with the elements above them.',
686
752
  };
753
+ fields.role = {
754
+ type: 'string',
755
+ description: 'For ui_snapshot: list only controls of this role, such as Button or Edit (comma-separated for several), with the elements above them. Combines with query.',
756
+ };
757
+ fields.full = {
758
+ type: 'boolean',
759
+ description: 'For ui_snapshot: true shows the whole tree. By default a window read before shows only what changed since that read.',
760
+ };
687
761
  }
688
762
  if (!forItems && present.includes('wait_for')) {
689
763
  fields.until = {
@@ -928,14 +1002,18 @@ function resolveSettings(options) {
928
1002
  throw new RangeError(`createComputerUseTool: ${name} must be an integer ≥ ${min}`);
929
1003
  return value;
930
1004
  };
931
- const limits = options.screenshotLimits ?? STANDARD_SCREENSHOT_LIMITS;
932
- if (!Number.isSafeInteger(limits.maxLongEdge) ||
933
- !Number.isSafeInteger(limits.maxTiles) ||
934
- limits.maxLongEdge < 28 ||
935
- limits.maxTiles < 1)
936
- throw new RangeError('createComputerUseTool: screenshotLimits needs an integer maxLongEdge ≥ 28 and maxTiles ≥ 1');
1005
+ const source = options.screenshotLimits ?? STANDARD_SCREENSHOT_LIMITS;
1006
+ const check = (limits) => {
1007
+ if (!Number.isSafeInteger(limits.maxLongEdge) ||
1008
+ !Number.isSafeInteger(limits.maxTiles) ||
1009
+ limits.maxLongEdge < 28 ||
1010
+ limits.maxTiles < 1)
1011
+ throw new RangeError('createComputerUseTool: screenshotLimits needs an integer maxLongEdge ≥ 28 and maxTiles ≥ 1');
1012
+ return limits;
1013
+ };
1014
+ check(typeof source === 'function' ? source() : source);
937
1015
  return {
938
- limits,
1016
+ limits: () => check(typeof source === 'function' ? source() : source),
939
1017
  settleMs: count(options.settleMs, DEFAULT_SETTLE_MS, 0, 'settleMs'),
940
1018
  screenshotAfterActions: options.screenshotAfterActions ?? true,
941
1019
  maxBatchActions: count(options.maxBatchActions, DEFAULT_MAX_BATCH_ACTIONS, 1, 'maxBatchActions'),
@@ -1031,14 +1109,34 @@ function hostOutcome(verdict) {
1031
1109
  return deliveryOutcome(verdict);
1032
1110
  }
1033
1111
  const CONSEQUENTIAL_KEYS = /(^|\+)(alt\+f4|ctrl\+q|cmd\+q|super\+q|ctrl\+w|ctrl\+shift\+delete|shift\+delete|ctrl\+enter|cmd\+enter|delete)$/i;
1034
- const CONSEQUENTIAL_WORDS = /(?<!\p{L})(delete|remove|erase|discard|don'?t save|do not save|close|quit|exit|send|submit|pay|purchase|buy|order|sign out|log ?out|empty|format|uninstall|kaydetme|sil|gönder|kapat|çık|çıkış|satın al|öde)(?!\p{L})/iu;
1112
+ const CONSEQUENTIAL_WORDS = /(?<!\p{L})(delete|remove|erase|discard|don'?t save|do not save|close|quit|exit|send|submit|pay|purchase|buy|order|sign out|log ?out|empty|format|uninstall|accept|agree|post|publish|confirm|password|passcode|card number|cvv|iban|kaydetme|sil|gönder|kapat|çık|çıkış|satın al|öde)(?!\p{L})/iu;
1113
+ /** Browsers whose process name is not how a person says it. */
1114
+ const KNOWN_BROWSER_NAMES = {
1115
+ 'brave-browser': 'Brave',
1116
+ brave: 'Brave',
1117
+ 'google-chrome': 'Chrome',
1118
+ chrome: 'Chrome',
1119
+ msedge: 'Microsoft Edge',
1120
+ 'microsoft-edge': 'Microsoft Edge',
1121
+ firefox: 'Firefox',
1122
+ };
1035
1123
  /** An application as a person reads it: no `.exe`, and a lowercase process name starts with a capital. */
1036
1124
  function applicationName(name) {
1037
1125
  const bare = name.trim().replace(/\.exe$/i, '');
1126
+ const known = KNOWN_BROWSER_NAMES[bare.toLowerCase()];
1127
+ if (known)
1128
+ return known;
1038
1129
  return bare && bare === bare.toLowerCase()
1039
1130
  ? `${bare.charAt(0).toUpperCase()}${bare.slice(1)}`
1040
1131
  : bare;
1041
1132
  }
1133
+ /** A control that takes a secret: a password field, by its state, role or name. */
1134
+ function isSecretElement(element) {
1135
+ const states = (element.states ?? []).map((state) => state.toLowerCase());
1136
+ if (states.some((state) => state === 'password' || state === 'protected' || state === 'secure'))
1137
+ return true;
1138
+ return /password|passcode|passwort|parola|şifre|sifre/i.test(`${element.role} ${element.name}`);
1139
+ }
1042
1140
  /** Words that make a control's name or an intent one a person should answer for. */
1043
1141
  function consequentialWords(text) {
1044
1142
  return text !== undefined && CONSEQUENTIAL_WORDS.test(text);
@@ -1139,6 +1237,22 @@ export function createComputerUseTool(host, options = {}) {
1139
1237
  const frames = new ScreenshotFrames();
1140
1238
  const available = new Set(availableActions(host, caps, options.advisor));
1141
1239
  const advisor = options.advisor;
1240
+ // Browser windows: the setting, and the browsers a person allowed in this conversation. Only the
1241
+ // person's answer to `askBrowserWindow` adds one; `ask` with nobody to ask is `look`.
1242
+ const readBrowserSetting = () => typeof options.browserWindows === 'function'
1243
+ ? options.browserWindows()
1244
+ : (options.browserWindows ?? 'look');
1245
+ const browserSetting = readBrowserSetting();
1246
+ const browserGranted = new Map();
1247
+ const browserDeclined = new Map();
1248
+ const browserActionsAllowed = (app) => {
1249
+ const setting = readBrowserSetting();
1250
+ if (setting === 'look')
1251
+ browserGranted.clear();
1252
+ return setting === 'act' || (setting === 'ask' && browserGranted.has(browserKey(app)));
1253
+ };
1254
+ // Whether the control in focus in the latest ui_snapshot is a secret field (a password).
1255
+ let focusedSecret = false;
1142
1256
  // The controls of the latest ui_snapshot, by the ref the model was shown.
1143
1257
  // A ref names a control, not one reading of it: the same host ref keeps the
1144
1258
  // same number in every snapshot, and a number is never reused for another
@@ -1147,6 +1261,8 @@ export function createComputerUseTool(host, options = {}) {
1147
1261
  const uiRefByHost = new Map();
1148
1262
  // The refs the latest reading of each window showed, so an advisor is asked about what is there now.
1149
1263
  const shownRefs = new Map();
1264
+ // The last whole-window read of each window, for showing only what changed next time.
1265
+ const uiSnapshotMemory = new Map();
1150
1266
  let uiSnapshots = 0;
1151
1267
  let uiRefCount = 0;
1152
1268
  let uiSnapshotWindowId;
@@ -1208,10 +1324,12 @@ export function createComputerUseTool(host, options = {}) {
1208
1324
  if (!windowCaptureAvailable(host, caps))
1209
1325
  throw new StepFailure('this host cannot capture a named window; no desktop screenshot was taken');
1210
1326
  const shot = await host.captureWindow(windowId, callSignal);
1211
- const image = await fitPng(shot.data, settings.limits);
1327
+ const image = await fitPng(shot.data, settings.limits());
1212
1328
  if (image.sourceWidth !== shot.width || image.sourceHeight !== shot.height)
1213
1329
  throw new StepFailure('the window PNG dimensions changed during capture; take a new screenshot');
1214
- return { frame: frames.recordWindow(image, shot), image };
1330
+ const frame = frames.recordWindow(image, shot);
1331
+ noteDigest(frame, image);
1332
+ return { frame, image };
1215
1333
  }
1216
1334
  if (!hostActionAvailable(caps, 'screenshot'))
1217
1335
  throw new StepFailure('this host requires window_id for screenshots; no display screenshot was taken');
@@ -1219,9 +1337,58 @@ export function createComputerUseTool(host, options = {}) {
1219
1337
  if (result.type !== 'screenshot')
1220
1338
  throw new Error(`computer_use: the host answered a screenshot with "${result.type}"`);
1221
1339
  const shot = result.result;
1222
- const image = await fitPng(shot.data, settings.limits);
1340
+ const image = await fitPng(shot.data, settings.limits());
1223
1341
  const display = shot.display ?? assumedDisplay(image.sourceWidth, image.sourceHeight);
1224
- return { frame: frames.record(image, display), image };
1342
+ const frame = frames.record(image, display);
1343
+ noteDigest(frame, image);
1344
+ return { frame, image };
1345
+ };
1346
+ /**
1347
+ * Before a click, drag or scroll on a window screenshot: the window must still be where that
1348
+ * picture was taken. A moved or resized window turns every coordinate into a different control,
1349
+ * and a closed one has nothing left to click. Nothing is sent. A host that cannot list windows
1350
+ * leaves the check to its own.
1351
+ */
1352
+ const refuseMovedWindow = async (frame) => {
1353
+ const shown = frame.window?.window;
1354
+ if (!shown || typeof host.listWindows !== 'function')
1355
+ return;
1356
+ let windows;
1357
+ try {
1358
+ windows = rememberWindows(await host.listWindows(callSignal));
1359
+ }
1360
+ catch {
1361
+ if (callSignal?.aborted)
1362
+ throw new StepFailure('cancelled');
1363
+ return;
1364
+ }
1365
+ const now = windows.find((window) => window.id === shown.id);
1366
+ const where = `window ${visibleWindowId(shown.id)}`;
1367
+ let why;
1368
+ if (!now)
1369
+ why = `${where} is no longer open`;
1370
+ else if (now.minimized)
1371
+ why = `${where} is minimized now`;
1372
+ else if (now.bounds.x !== shown.bounds.x ||
1373
+ now.bounds.y !== shown.bounds.y ||
1374
+ now.bounds.width !== shown.bounds.width ||
1375
+ now.bounds.height !== shown.bounds.height)
1376
+ why = `${where} moved or was resized since ${frame.id} was taken (${shown.bounds.width}x${shown.bounds.height} at ${shown.bounds.x},${shown.bounds.y}, now ${now.bounds.width}x${now.bounds.height} at ${now.bounds.x},${now.bounds.y})`;
1377
+ if (why)
1378
+ throw deliveryFailure({
1379
+ delivery: 'not_delivered',
1380
+ retrySafety: 'safe',
1381
+ detail: `${why}, so nothing was clicked: the coordinates of ${frame.id} no longer point at what they did. Take a new window screenshot (or read its controls with ui_snapshot) and choose the target again.`,
1382
+ });
1383
+ };
1384
+ /** A fingerprint of each frame's picture, to tell a click that changed nothing from one that did. */
1385
+ const frameDigest = new Map();
1386
+ const noteDigest = (frame, image) => {
1387
+ frameDigest.set(frame.id, createHash('sha1').update(image.data).digest('hex'));
1388
+ // Only the few newest are ever compared.
1389
+ if (frameDigest.size > 16)
1390
+ for (const key of [...frameDigest.keys()].slice(0, frameDigest.size - 16))
1391
+ frameDigest.delete(key);
1225
1392
  };
1226
1393
  const frameFor = (id) => {
1227
1394
  if (id !== undefined) {
@@ -1321,6 +1488,7 @@ export function createComputerUseTool(host, options = {}) {
1321
1488
  const frame = frameFor(frameId);
1322
1489
  const at = mapPoint(frame, item.at, 'at');
1323
1490
  return step(async () => {
1491
+ await refuseMovedWindow(frame);
1324
1492
  const outcome = await runHost({
1325
1493
  type: 'mouse_click',
1326
1494
  at,
@@ -1344,7 +1512,10 @@ export function createComputerUseTool(host, options = {}) {
1344
1512
  const frame = frameFor(frameId);
1345
1513
  const from = mapPoint(frame, item.from, 'from');
1346
1514
  const to = mapPoint(frame, item.to, 'to');
1347
- return step(() => runHost({ type: 'mouse_drag', from, to, button: item.button }, frame));
1515
+ return step(async () => {
1516
+ await refuseMovedWindow(frame);
1517
+ return runHost({ type: 'mouse_drag', from, to, button: item.button }, frame);
1518
+ });
1348
1519
  }
1349
1520
  case 'scroll': {
1350
1521
  const frame = frameFor(frameId);
@@ -1353,12 +1524,15 @@ export function createComputerUseTool(host, options = {}) {
1353
1524
  if (frame.window && caps.windowScroll === false)
1354
1525
  throw new StepFailure('window pixel scrolling is unavailable on this host; take a deliberate display screenshot before display scrolling, or use the browser tool for a page');
1355
1526
  const at = mapPoint(frame, item.at, 'at');
1356
- return step(() => runHost({
1357
- type: 'scroll',
1358
- at,
1359
- direction: item.direction,
1360
- amount: item.amount,
1361
- }, frame));
1527
+ return step(async () => {
1528
+ await refuseMovedWindow(frame);
1529
+ return runHost({
1530
+ type: 'scroll',
1531
+ at,
1532
+ direction: item.direction,
1533
+ amount: item.amount,
1534
+ }, frame);
1535
+ });
1362
1536
  }
1363
1537
  case 'type_text': {
1364
1538
  if (item.at)
@@ -1367,7 +1541,7 @@ export function createComputerUseTool(host, options = {}) {
1367
1541
  const frame = frameFor(frameId);
1368
1542
  if (item.delivery_mode && !frame.window)
1369
1543
  throw new StepFailure('type_text delivery_mode requires a window screenshot');
1370
- if (frame.window && TERMINAL_APPS.test(frame.window.window.app))
1544
+ if (frame.window && appIs(TERMINAL_APPS, frame.window.window.app))
1371
1545
  throw new StepFailure('computer_use never types into a terminal window; use the shell tool for a command');
1372
1546
  return step(() => runHost({
1373
1547
  type: 'type_text',
@@ -1382,7 +1556,7 @@ export function createComputerUseTool(host, options = {}) {
1382
1556
  const frame = frameFor(frameId);
1383
1557
  if (item.delivery_mode && !frame.window)
1384
1558
  throw new StepFailure('key delivery_mode requires a window screenshot; take one with screenshot {window_id}');
1385
- if (frame.window && TERMINAL_APPS.test(frame.window.window.app))
1559
+ if (frame.window && appIs(TERMINAL_APPS, frame.window.window.app))
1386
1560
  throw new StepFailure('computer_use never sends keys to a terminal window; use the shell tool for a command');
1387
1561
  return step(() => runHost({
1388
1562
  type: 'key',
@@ -1526,6 +1700,7 @@ export function createComputerUseTool(host, options = {}) {
1526
1700
  ...(rootRef ? { root: rootRef.hostRef } : {}),
1527
1701
  ...(rootRef && input.offset !== undefined ? { offset: input.offset } : {}),
1528
1702
  ...(input.query !== undefined ? { query: input.query } : {}),
1703
+ ...(input.role !== undefined ? { role: input.role } : {}),
1529
1704
  };
1530
1705
  try {
1531
1706
  snapshot = await host.uiSnapshot(windowId, options, callSignal);
@@ -1533,10 +1708,20 @@ export function createComputerUseTool(host, options = {}) {
1533
1708
  catch (error) {
1534
1709
  throw new StepFailure(errorText(error));
1535
1710
  }
1536
- return showUiSnapshot(snapshot, windowId, [], input.root);
1711
+ return showUiSnapshot(snapshot, windowId, [], input.root, {
1712
+ ...(input.full === true ? { full: true } : {}),
1713
+ ...(input.query !== undefined || input.role !== undefined
1714
+ ? {
1715
+ filter: [
1716
+ ...(input.role !== undefined ? [`role ${quotedText(input.role)}`] : []),
1717
+ ...(input.query !== undefined ? [`text ${quotedText(input.query)}`] : []),
1718
+ ].join(' and '),
1719
+ }
1720
+ : {}),
1721
+ });
1537
1722
  };
1538
1723
  /** Number a read tree's controls and show it; this snapshot's refs replace the last one's. */
1539
- const showUiSnapshot = (snapshot, requestedWindowId, preface = [], openedRef) => {
1724
+ const showUiSnapshot = (snapshot, requestedWindowId, preface = [], openedRef, mode = {}) => {
1540
1725
  uiSnapshots += 1;
1541
1726
  const id = `u${uiSnapshots}`;
1542
1727
  const refs = new Map();
@@ -1548,6 +1733,10 @@ export function createComputerUseTool(host, options = {}) {
1548
1733
  let shown = 0;
1549
1734
  let total = 0;
1550
1735
  let cut = false;
1736
+ // What was listed, for the diff against the next read of this window.
1737
+ const entries = [];
1738
+ let focusedLine;
1739
+ let focusedSecretNow = false;
1551
1740
  const visit = (element, depth) => {
1552
1741
  total += 1;
1553
1742
  const actionable = element.ref.length > 0;
@@ -1566,6 +1755,14 @@ export function createComputerUseTool(host, options = {}) {
1566
1755
  }
1567
1756
  else {
1568
1757
  lines.push(line);
1758
+ entries.push({
1759
+ hostRef: actionable ? element.ref : undefined,
1760
+ text: line.trim(),
1761
+ });
1762
+ if (focusedLine === undefined && element.states?.includes('focused') === true) {
1763
+ focusedLine = line.trim();
1764
+ focusedSecretNow = isSecretElement(element);
1765
+ }
1569
1766
  chars += line.length + 1;
1570
1767
  shown += 1;
1571
1768
  if (ref) {
@@ -1585,6 +1782,7 @@ export function createComputerUseTool(host, options = {}) {
1585
1782
  // region opened by itself leaves the refs outside it usable.
1586
1783
  for (const [ref, entry] of refs)
1587
1784
  uiRefs.set(ref, entry);
1785
+ focusedSecret = focusedSecretNow;
1588
1786
  if (uiRefs.size > MAX_HELD_UI_REFS) {
1589
1787
  for (const ref of [...uiRefs.keys()].slice(0, uiRefs.size - MAX_HELD_UI_REFS)) {
1590
1788
  const gone = uiRefs.get(ref);
@@ -1604,16 +1802,6 @@ export function createComputerUseTool(host, options = {}) {
1604
1802
  uiSnapshotFrame = frames.latest();
1605
1803
  const window = snapshot.windowId && /^[\w.:-]{1,64}$/.test(snapshot.windowId) ? snapshot.windowId : undefined;
1606
1804
  const opened = openedRef !== undefined && /^e\d{1,6}$/.test(openedRef) ? openedRef : undefined;
1607
- const summaryLine = `UI snapshot ${id}${window ? ` of window ${window}` : ''}${snapshot.region ? `${opened ? `, region ${opened}` : ', one region'}` : ''}: ${shown} controls shown${snapshot.total !== undefined && snapshot.total > shown ? ` of ${snapshot.total}` : ''}, ${refs.size} with a ref you can pass to ui_act. A ref names its control and stays usable after later snapshots; if the control has gone or several fit, ui_act says so (STALE_REF, AMBIGUOUS_TARGET) and nothing is sent.`;
1608
- const header = [
1609
- ...preface,
1610
- summaryLine,
1611
- ...(frame && !frame.window
1612
- ? [
1613
- `@(x, y) is a control's centre on screenshot ${frame.id}, for a click when ui_act cannot reach it.`,
1614
- ]
1615
- : []),
1616
- ];
1617
1805
  // The window's title and application, when the tree's own root does not
1618
1806
  // already say them; inside the frame, since an application sets both.
1619
1807
  const about = [
@@ -1622,37 +1810,126 @@ export function createComputerUseTool(host, options = {}) {
1622
1810
  ? [`Window title ${quotedText(snapshot.title)}`]
1623
1811
  : []),
1624
1812
  ];
1625
- const body = [...about, ...lines].join('\n');
1626
- const drill = 'Open a region with ui_snapshot {root: <its ref>}, or find a control by its text with ui_snapshot {query}.';
1627
- const footer = [
1628
- ...(snapshot.next !== undefined && opened
1629
- ? [
1630
- `This is one page of a long region. Next page: ui_snapshot {root: "${opened}", offset: ${snapshot.next}}.`,
1631
- ]
1632
- : []),
1633
- ...(snapshot.outline
1634
- ? [
1635
- `This is an outline: regions marked "(+N more inside)" hold controls that are not listed. ${drill}`,
1636
- ]
1637
- : []),
1638
- ...(cut
1813
+ // A window read before shows what changed since, unless the whole tree is
1814
+ // asked for, the read is a region or a filtered one, or either read was cut.
1815
+ const whole = !snapshot.region && mode.filter === undefined;
1816
+ const key = windowKey(uiSnapshotWindowId);
1817
+ const before = whole ? uiSnapshotMemory.get(key) : undefined;
1818
+ if (whole)
1819
+ uiSnapshotMemory.set(key, { id, entries: cut ? undefined : entries });
1820
+ let changes;
1821
+ if (before?.entries && !cut && mode.full !== true) {
1822
+ const prevByRef = new Map();
1823
+ const prevCounts = new Map();
1824
+ for (const entry of before.entries) {
1825
+ if (entry.hostRef)
1826
+ prevByRef.set(entry.hostRef, entry.text);
1827
+ else
1828
+ prevCounts.set(entry.text, (prevCounts.get(entry.text) ?? 0) + 1);
1829
+ }
1830
+ const added = [];
1831
+ const changed = [];
1832
+ const seenRefs = new Set();
1833
+ const left = new Map(prevCounts);
1834
+ for (const entry of entries) {
1835
+ if (entry.hostRef) {
1836
+ seenRefs.add(entry.hostRef);
1837
+ const was = prevByRef.get(entry.hostRef);
1838
+ if (was === undefined)
1839
+ added.push(entry.text);
1840
+ else if (was !== entry.text)
1841
+ changed.push(entry.text);
1842
+ }
1843
+ else {
1844
+ const count = left.get(entry.text) ?? 0;
1845
+ if (count > 0)
1846
+ left.set(entry.text, count - 1);
1847
+ else
1848
+ added.push(entry.text);
1849
+ }
1850
+ }
1851
+ const removed = [];
1852
+ for (const [hostRef, text] of prevByRef)
1853
+ if (!seenRefs.has(hostRef))
1854
+ removed.push(text);
1855
+ for (const [text, count] of left)
1856
+ for (let i = 0; i < count; i++)
1857
+ removed.push(text);
1858
+ // A window that mostly changed is shorter, and clearer, read whole.
1859
+ if (added.length + changed.length + removed.length < entries.length)
1860
+ changes = { added, changed, removed };
1861
+ }
1862
+ const trailer = [
1863
+ ...(focusedLine !== undefined ? [`Focused: ${focusedLine}`] : []),
1864
+ ...(snapshot.selectedText !== undefined
1639
1865
  ? [
1640
- `The listing was cut at ${MAX_UI_SNAPSHOT_CHARS} characters after ${shown} of ${total} controls. Drill into the region you need: ${drill}`,
1866
+ `Selected text: ${neutralizeEnvelopeDelimiter(JSON.stringify(snapshot.selectedText.slice(0, 500)))}`,
1641
1867
  ]
1642
1868
  : []),
1643
- ...(snapshot.truncated
1869
+ ];
1870
+ const body = changes
1871
+ ? [
1872
+ ...about,
1873
+ ...changes.added.map((line) => `+ ${line}`),
1874
+ ...changes.changed.map((line) => `~ ${line}`),
1875
+ ...changes.removed.map((line) => `- ${line}`),
1876
+ ...trailer,
1877
+ ].join('\n')
1878
+ : [...about, ...lines, ...trailer].join('\n');
1879
+ const noChange = changes !== undefined &&
1880
+ changes.added.length + changes.changed.length + changes.removed.length === 0;
1881
+ const where = `${window ? ` of window ${window}` : ''}${snapshot.region ? `${opened ? `, region ${opened}` : ', one region'}` : ''}${mode.filter ? `, only ${mode.filter}` : ''}`;
1882
+ const counts = `${shown} controls shown${snapshot.total !== undefined ? ` of the ${snapshot.total} the window holds` : ''}, ${refs.size} with a ref you can pass to ui_act`;
1883
+ const summaryLine = changes
1884
+ ? noChange
1885
+ ? `UI snapshot ${id}${where}: no change since ${before ? before.id : 'the last read'} (${counts}). Refs from that read are used while the host still has them.`
1886
+ : `UI snapshot ${id}${where}: ${changes.added.length} added (+), ${changes.changed.length} changed (~), ${changes.removed.length} gone (-) since ${before ? before.id : 'the last read'}; ${counts}. Refs from that read are used while the host still has them. ui_snapshot {full: true} lists the whole tree.`
1887
+ : `UI snapshot ${id}${where}: ${counts}. A ref names its control and stays usable after later snapshots; if the control has gone or several fit, ui_act says so (STALE_REF, AMBIGUOUS_TARGET) and nothing is sent.${mode.filter && shown <= 1 ? ' Nothing matched the filter.' : ''}`;
1888
+ const header = [
1889
+ ...preface,
1890
+ summaryLine,
1891
+ ...(frame && !frame.window
1644
1892
  ? [
1645
- `The host stopped reading the tree before it ended, so some controls are missing. Drill into the region you need: ${drill} A window screenshot shows the rest.`,
1893
+ `@(x, y) is a control's centre on screenshot ${frame.id}, for a click when ui_act cannot reach it.`,
1646
1894
  ]
1647
1895
  : []),
1648
1896
  ];
1897
+ const drill = 'Open a region with ui_snapshot {root: <its ref>}, or find a control by its text with ui_snapshot {query}.';
1898
+ const footer = changes
1899
+ ? []
1900
+ : [
1901
+ ...(snapshot.next !== undefined && opened
1902
+ ? [
1903
+ `This is one page of a long region. Next page: ui_snapshot {root: "${opened}", offset: ${snapshot.next}}.`,
1904
+ ]
1905
+ : []),
1906
+ ...(snapshot.outline
1907
+ ? [
1908
+ `This is an outline: regions marked "(+N more inside)" hold controls that are not listed. ${drill}`,
1909
+ ]
1910
+ : []),
1911
+ ...(cut
1912
+ ? [
1913
+ `The listing was cut at ${MAX_UI_SNAPSHOT_CHARS} characters after ${shown} of ${total} controls. Drill into the region you need: ${drill}`,
1914
+ ]
1915
+ : []),
1916
+ ...(snapshot.truncated
1917
+ ? [
1918
+ `The host stopped reading the tree before it ended, so some controls are missing. Drill into the region you need: ${drill} A window screenshot shows the rest.`,
1919
+ ]
1920
+ : []),
1921
+ ];
1649
1922
  const text = [
1650
1923
  ...header,
1651
- wrapUntrusted({
1652
- kind: 'desktop-ui',
1653
- ...(window ? { attributes: { window } } : {}),
1654
- provenance: "The accessibility tree of a window on the user's desktop, as the host read it. Names and values are whatever the application shows, which can include text anyone wrote.",
1655
- }, body),
1924
+ ...(noChange && body.length === 0
1925
+ ? []
1926
+ : [
1927
+ wrapUntrusted({
1928
+ kind: 'desktop-ui',
1929
+ ...(window ? { attributes: { window } } : {}),
1930
+ provenance: "The accessibility tree of a window on the user's desktop, as the host read it. Names and values are whatever the application shows, which can include text anyone wrote.",
1931
+ }, body),
1932
+ ]),
1656
1933
  ...footer,
1657
1934
  ].join('\n');
1658
1935
  return {
@@ -1667,6 +1944,7 @@ export function createComputerUseTool(host, options = {}) {
1667
1944
  refs: refs.size,
1668
1945
  truncated: cut || snapshot.truncated === true,
1669
1946
  ...(snapshot.outline ? { outline: true } : {}),
1947
+ ...(changes ? { diff: noChange ? 'none' : 'changes' } : {}),
1670
1948
  ...(snapshot.total !== undefined ? { total: snapshot.total } : {}),
1671
1949
  },
1672
1950
  },
@@ -1810,11 +2088,11 @@ export function createComputerUseTool(host, options = {}) {
1810
2088
  throw new StepFailure(`the window in front could not be read, so nothing was typed: ${errorText(error)}`);
1811
2089
  }
1812
2090
  const front = windows.find((window) => window.focused);
1813
- if (front && appTier(front.app) === 'view')
1814
- throw new StepFailure(`a browser is in front (${front.app}, window ${front.id}), so nothing was typed: computer_use only looks at a browser. Use the browser tool to act on a page, or bring the window you mean to the front (focus_window, or click it) and try again`);
1815
- if (front && IDE_APPS.test(front.app.trim().replace(/\.exe$/i, '')))
2091
+ if (front && appTier(front.app) === 'view' && !browserActionsAllowed(front.app))
2092
+ throw new StepFailure(`a browser is in front (${front.app}, window ${front.id}), so nothing was typed: computer_use does not type in a browser unless the person allowed it. Use the browser tool to act on a page, or bring the window you mean to the front (focus_window, or click it) and try again. ${browserWaysForward(applicationName(front.app), readBrowserSetting())}`);
2093
+ if (front && appIs(IDE_APPS, front.app))
1816
2094
  throw new StepFailure(`an editor is in front (${front.app}, window ${front.id}), so nothing was typed: computer_use clicks in an editor but does not type there. Use the edit tools for a file and the shell tool for a command, or bring the window you mean to the front (focus_window, or click it) and try again`);
1817
- if (front && TERMINAL_APPS.test(front.app))
2095
+ if (front && appIs(TERMINAL_APPS, front.app))
1818
2096
  throw new StepFailure(`a terminal is in front (${front.app}, window ${front.id}), so nothing was typed: computer_use never sends keys or text to a terminal. Bring the window you mean to the front (focus_window, or click it) and try again; for a command, use a shell tool instead`);
1819
2097
  };
1820
2098
  const listWindows = async () => {
@@ -1877,7 +2155,9 @@ export function createComputerUseTool(host, options = {}) {
1877
2155
  // what to do, rather than let the model guess at blurred pixels.
1878
2156
  const shrink = display.width / frame.imageWidth;
1879
2157
  const shrunkNote = shrink >= 2
1880
- ? ` The display is ${Math.round(shrink * 10) / 10} times larger than this image, so small text is hard to read here: use zoom on the area to read it at full detail.`
2158
+ ? ` The display is ${Math.round(shrink * 10) / 10} times larger than this image, so small text is hard to read here.${windowCaptureAvailable(host, caps)
2159
+ ? ' For the application you are working in, take a window screenshot (list_windows, then screenshot with its window_id): it is close to full size.'
2160
+ : ''}`
1881
2161
  : '';
1882
2162
  return scaled
1883
2163
  ? `Screenshot ${frame.id}: ${frame.imageWidth}x${frame.imageHeight} pixels, showing the ${display.width}x${display.height} display. Send coordinates in this image's pixels (x 0–${frame.imageWidth - 1}, y 0–${frame.imageHeight - 1}); the tool maps them onto the display.${shrunkNote}`
@@ -1934,6 +2214,46 @@ export function createComputerUseTool(host, options = {}) {
1934
2214
  data: { screenshot: frameData(shot.frame) },
1935
2215
  workingState: pin(shot.frame),
1936
2216
  });
2217
+ /**
2218
+ * The first look at a window carries its controls with the picture, so the
2219
+ * model starts from names, not pixels. Later looks are the picture alone
2220
+ * (ui_snapshot shows what changed). A host that cannot read the tree, or a
2221
+ * read that fails, leaves the screenshot as it was.
2222
+ */
2223
+ const firstLookWithTree = async (shot, windowId) => {
2224
+ const result = screenshotResult(shot);
2225
+ if (!shot.frame.window ||
2226
+ windowId === undefined ||
2227
+ !available.has('ui_snapshot') ||
2228
+ uiSnapshotMemory.has(windowKey(windowId)))
2229
+ return result;
2230
+ try {
2231
+ const snapshot = await host.uiSnapshot(windowId, undefined, callSignal);
2232
+ const tree = showUiSnapshot(snapshot, windowId);
2233
+ const treeBlocks = Array.isArray(tree.content) ? tree.content : [];
2234
+ const treeText = treeBlocks.find((block) => block.type === 'text');
2235
+ if (!treeText || treeText.type !== 'text')
2236
+ return result;
2237
+ const [head, ...rest] = Array.isArray(result.content) ? result.content : [];
2238
+ return {
2239
+ ...result,
2240
+ content: [
2241
+ ...(head ? [head] : []),
2242
+ {
2243
+ type: 'text',
2244
+ text: `The window's controls, read with this screenshot (ui_act on a ref; pixels only for what the controls do not name):\n${treeText.text}`,
2245
+ },
2246
+ ...rest,
2247
+ ],
2248
+ data: { ...result.data, ...tree.data },
2249
+ };
2250
+ }
2251
+ catch (error) {
2252
+ if (callSignal?.aborted)
2253
+ throw error;
2254
+ return result;
2255
+ }
2256
+ };
1937
2257
  const zoom = async (input) => {
1938
2258
  const frame = frameFor(input.screenshot_id);
1939
2259
  const { region } = input;
@@ -1950,11 +2270,11 @@ export function createComputerUseTool(host, options = {}) {
1950
2270
  if (frame.window) {
1951
2271
  if (!frame.window.data)
1952
2272
  throw new StepFailure(`window screenshot ${frame.id} is stale; capture the window again`);
1953
- fitted = await cropAndFitPng(frame.window.data, rect, settings.limits);
2273
+ fitted = await cropAndFitPng(frame.window.data, rect, settings.limits());
1954
2274
  }
1955
2275
  else if (caps.regionCapture === true && typeof host.captureRegion === 'function') {
1956
2276
  const piece = await host.captureRegion(rect, callSignal);
1957
- fitted = await fitPng(piece.data, settings.limits);
2277
+ fitted = await fitPng(piece.data, settings.limits());
1958
2278
  }
1959
2279
  else {
1960
2280
  const result = await host.execute({ type: 'screenshot' }, callSignal);
@@ -1975,7 +2295,7 @@ export function createComputerUseTool(host, options = {}) {
1975
2295
  y: top,
1976
2296
  width: Math.max(1, Math.min(size.width, Math.ceil((rect.x + rect.width) * sx)) - left),
1977
2297
  height: Math.max(1, Math.min(size.height, Math.ceil((rect.y + rect.height) * sy)) - top),
1978
- }, settings.limits);
2298
+ }, settings.limits());
1979
2299
  }
1980
2300
  const detail = fitted.width / onImage.width;
1981
2301
  const text = `Zoom of ${onImage.width}x${onImage.height} at ${pointLabel(onImage)} in ${frame.id}, shown at ${fitted.width}x${fitted.height} (${detail.toFixed(1)}x the detail of ${frame.id}). Coordinates for actions still refer to ${frame.id} (${frame.imageWidth}x${frame.imageHeight}), not to this image.`;
@@ -2028,6 +2348,24 @@ export function createComputerUseTool(host, options = {}) {
2028
2348
  const unsent = blockedAt >= 0 ? items.slice(blockedAt) : [];
2029
2349
  const toPlan = blockedAt >= 0 ? items.slice(0, blockedAt) : items;
2030
2350
  const actionFrame = frameId ? frames.get(frameId) : frames.latest();
2351
+ // What the model last saw, to tell afterwards whether a pixel action changed it.
2352
+ const frameBefore = frames.latest();
2353
+ // The baseline for "a new window opened" is the host's list right now, never the last list the
2354
+ // model asked for, which may be old. A list that fails leaves no baseline, so no note.
2355
+ let windowsBefore = [];
2356
+ if (typeof host.listWindows === 'function' &&
2357
+ typeof host.uiSnapshot === 'function' &&
2358
+ toPlan.length > 0 &&
2359
+ toPlan.every((item) => TREE_ENDING_STEPS.has(item.type)) &&
2360
+ [...treeUsable.values()].includes(true)) {
2361
+ try {
2362
+ windowsBefore = rememberWindows(await host.listWindows(callSignal));
2363
+ }
2364
+ catch {
2365
+ if (callSignal?.aborted)
2366
+ throw new Error('cancelled');
2367
+ }
2368
+ }
2031
2369
  const explicitDisplayFrame = frameId !== undefined && actionFrame !== undefined && !actionFrame.window;
2032
2370
  if (actionFrame?.window &&
2033
2371
  items.some((item, index) => item.type === 'focus_window' &&
@@ -2167,15 +2505,108 @@ export function createComputerUseTool(host, options = {}) {
2167
2505
  !signal?.aborted;
2168
2506
  let shot = frameShot;
2169
2507
  let shotError;
2170
- if (looks) {
2508
+ // A batch of element and keyboard steps on a window whose controls were read ends with what
2509
+ // changed there, not a picture: the model acts on the next refs, and the text is far cheaper.
2510
+ const executed = planned.filter((_, index) => records[index]?.status === 'done');
2511
+ let treeText;
2512
+ let treeData;
2513
+ let windowClosed;
2514
+ let newWindows = [];
2515
+ const treeEnding = looks &&
2516
+ !failure &&
2517
+ frameShot === undefined &&
2518
+ frameId === undefined &&
2519
+ postWindowId !== undefined &&
2520
+ available.has('ui_snapshot') &&
2521
+ typeof host.uiSnapshot === 'function' &&
2522
+ treeUsable.get(windowKey(postWindowId)) === true &&
2523
+ executed.length > 0 &&
2524
+ executed.every((step) => TREE_ENDING_STEPS.has(step.item.type));
2525
+ /** Whether a window is gone from the host's list: the action closed it. */
2526
+ const isGone = async (id) => {
2527
+ if (typeof host.listWindows !== 'function')
2528
+ return false;
2529
+ try {
2530
+ const listed = rememberWindows(await host.listWindows(callSignal));
2531
+ return !listed.some((window) => window.id === id);
2532
+ }
2533
+ catch {
2534
+ return false;
2535
+ }
2536
+ };
2537
+ if (treeEnding && postWindowId !== undefined) {
2538
+ try {
2539
+ await settleAfterActions(host, postWindowId, settings.settleMs, signal);
2540
+ const read = await uiSnapshot({
2541
+ type: 'ui_snapshot',
2542
+ window_id: postWindowId,
2543
+ });
2544
+ const block = Array.isArray(read.content)
2545
+ ? read.content.find((entry) => entry.type === 'text')
2546
+ : undefined;
2547
+ treeText = block?.type === 'text' ? block.text : read.output;
2548
+ treeData = read.data;
2549
+ if (windowsBefore.length > 0 && typeof host.listWindows === 'function') {
2550
+ try {
2551
+ const listed = rememberWindows(await host.listWindows(callSignal));
2552
+ newWindows = listed.filter((window) => !windowsBefore.some((old) => old.id === window.id) &&
2553
+ !deniedKeys.has(deniedAppKey(window.app)));
2554
+ }
2555
+ catch {
2556
+ // A list that fails says nothing; the tree above stands.
2557
+ }
2558
+ }
2559
+ }
2560
+ catch {
2561
+ // Fall back to the picture below; a cancelled call stops there too.
2562
+ if (signal?.aborted)
2563
+ shotError = 'cancelled';
2564
+ else if (await isGone(postWindowId))
2565
+ windowClosed = postWindowId;
2566
+ }
2567
+ }
2568
+ if (looks && treeText === undefined && windowClosed === undefined) {
2171
2569
  try {
2172
2570
  await settleAfterActions(host, postWindowId, settings.settleMs, signal);
2173
2571
  shot = await capture(postWindowId);
2174
2572
  }
2175
2573
  catch (error) {
2176
2574
  shotError = signal?.aborted ? 'cancelled' : errorText(error);
2575
+ if (!signal?.aborted && postWindowId !== undefined && (await isGone(postWindowId)))
2576
+ windowClosed = postWindowId;
2177
2577
  }
2178
2578
  }
2579
+ // The window is gone: show what is left of the screen, when the host can.
2580
+ if (windowClosed !== undefined &&
2581
+ shot === undefined &&
2582
+ !signal?.aborted &&
2583
+ hostActionAvailable(caps, 'screenshot')) {
2584
+ try {
2585
+ shot = await capture();
2586
+ shotError = undefined;
2587
+ }
2588
+ catch (error) {
2589
+ shotError = errorText(error);
2590
+ }
2591
+ }
2592
+ const closedLine = windowClosed !== undefined
2593
+ ? `Window ${visibleWindowId(windowClosed)} is no longer open: the action closed it (or the application did). This is a result, not a failure of the tool; list_windows shows what is open now.${shot ? ' The display screenshot follows.' : ''}`
2594
+ : undefined;
2595
+ // A pixel action after which the picture is identical to the one before it did nothing visible.
2596
+ const pixelActed = executed.some((step) => PIXEL_STEPS.has(step.item.type));
2597
+ const noVisibleChange = pixelActed &&
2598
+ shot !== undefined &&
2599
+ frameShot === undefined &&
2600
+ frameBefore !== undefined &&
2601
+ shot.frame !== frameBefore &&
2602
+ (frameBefore.window?.window.id ?? null) === (shot.frame.window?.window.id ?? null) &&
2603
+ frameBefore.imageWidth === shot.frame.imageWidth &&
2604
+ frameBefore.imageHeight === shot.frame.imageHeight &&
2605
+ frameDigest.get(frameBefore.id) !== undefined &&
2606
+ frameDigest.get(frameBefore.id) === frameDigest.get(shot.frame.id);
2607
+ const noChangeLine = noVisibleChange
2608
+ ? `No visible change: the screen looks the same after the settle wait as in ${frameBefore?.id}. The click may have landed without showing it, or it may have missed; check with a fresh look or a control by ref.`
2609
+ : undefined;
2179
2610
  const summary = (record, index) => {
2180
2611
  const n = single ? '' : `${index + 1}. `;
2181
2612
  switch (record.status) {
@@ -2206,10 +2637,29 @@ export function createComputerUseTool(host, options = {}) {
2206
2637
  ? [`The screenshot after acting failed: ${shotError}. Take one before acting again.`]
2207
2638
  : [];
2208
2639
  const unknownLines = failure?.unknown ? [failure.unknown.message] : [];
2209
- const text = [...header, ...stepLines, ...unknownLines, ...shotLines].join('\n');
2640
+ const afterLines = [
2641
+ ...(closedLine ? [closedLine] : []),
2642
+ ...(noChangeLine ? [noChangeLine] : []),
2643
+ ...(treeText !== undefined ? [treeText] : []),
2644
+ ...(newWindows.length > 0
2645
+ ? [
2646
+ `A new window opened during the batch; read it with ui_snapshot {window_id}:\n${wrapUntrusted({
2647
+ kind: 'desktop-windows',
2648
+ provenance: "Windows that opened on the user's desktop during the batch, as the host listed them. Titles are whatever each application shows, which can include text anyone wrote.",
2649
+ }, newWindows
2650
+ .slice(0, 5)
2651
+ .map((window) => `- ${window.id} · ${JSON.stringify(window.title)} · ${window.app}`)
2652
+ .join('\n'))}`,
2653
+ ]
2654
+ : []),
2655
+ ];
2656
+ const text = [...header, ...stepLines, ...unknownLines, ...afterLines, ...shotLines].join('\n');
2210
2657
  const output = [
2211
2658
  ...header,
2212
2659
  ...stepLines,
2660
+ ...(closedLine ? [closedLine] : []),
2661
+ ...(noChangeLine ? [noChangeLine] : []),
2662
+ ...(treeText !== undefined ? ['Window controls after the batch follow.'] : []),
2213
2663
  ...(shot
2214
2664
  ? [`Screenshot ${shot.frame.id} (${shot.frame.imageWidth}x${shot.frame.imageHeight}).`]
2215
2665
  : []),
@@ -2233,6 +2683,9 @@ export function createComputerUseTool(host, options = {}) {
2233
2683
  }
2234
2684
  : { label: record.label, status: record.status }),
2235
2685
  ...(shot ? { screenshot: frameData(shot.frame) } : {}),
2686
+ ...(treeData && typeof treeData === 'object' ? treeData : {}),
2687
+ ...(windowClosed !== undefined ? { windowClosed } : {}),
2688
+ ...(noVisibleChange ? { noVisibleChange: true } : {}),
2236
2689
  ...(failure?.unknown
2237
2690
  ? {
2238
2691
  code: failure.unknown.code,
@@ -2471,6 +2924,41 @@ export function createComputerUseTool(host, options = {}) {
2471
2924
  return undefined;
2472
2925
  return `computer_use does not act in ${applicationName(app)}: the person put it off limits. Nothing was done. Use another application, or tell the person you need it and let them change the list.`;
2473
2926
  };
2927
+ /**
2928
+ * Why an action aimed at a browser window may not run, or undefined when it may. `act` allows
2929
+ * it; `ask` allows it once a person has said yes for this browser in this conversation, asking
2930
+ * them the first time. Nobody to ask, or a no, leaves the window look-only and says what the
2931
+ * person can do instead. A no holds for the rest of the turn so one turn does not ask twice.
2932
+ */
2933
+ const browserWindowRefusal = async (app, name, context) => {
2934
+ if (browserActionsAllowed(app))
2935
+ return undefined;
2936
+ const key = browserKey(app);
2937
+ const ways = (setting) => browserWaysForward(name, setting);
2938
+ if (readBrowserSetting() === 'look')
2939
+ return `computer_use only looks at ${name}, a browser: it does not click, type or press keys there. Use the browser tool to act on a page; take a screenshot to see what the window shows. Nothing was done. ${ways('look')}`;
2940
+ if (!options.askBrowserWindow)
2941
+ return `computer_use only looks at ${name}, a browser, in this session: acting there needs a person's yes and nobody can be asked here. Nothing was done. Use the browser tool, or tell the person what is left for them. ${ways('ask')}`;
2942
+ if (browserDeclined.get(key) === String(context.turnId))
2943
+ return `The person said not now to clicking and typing in ${name} in this turn. Nothing was done. Do not ask again this turn. ${ways('ask')}`;
2944
+ let answer;
2945
+ try {
2946
+ answer = await options.askBrowserWindow({ app, name }, context.abortSignal);
2947
+ }
2948
+ catch {
2949
+ answer = 'unavailable';
2950
+ }
2951
+ if (answer === 'allow') {
2952
+ browserGranted.set(key, name);
2953
+ browserDeclined.delete(key);
2954
+ return undefined;
2955
+ }
2956
+ if (answer === 'deny') {
2957
+ browserDeclined.set(key, String(context.turnId));
2958
+ return `The person said not now to clicking and typing in ${name}. Nothing was done. ${ways('ask')}`;
2959
+ }
2960
+ return `computer_use only looks at ${name}, a browser: the question whether Namzu may act there was not answered. Nothing was done. ${ways('ask')}`;
2961
+ };
2474
2962
  /**
2475
2963
  * Why this call may not run because of the kind of application it would act in, or undefined:
2476
2964
  * a browser window is only looked at, a terminal or an editor is clicked but not typed into.
@@ -2521,9 +3009,19 @@ export function createComputerUseTool(host, options = {}) {
2521
3009
  const name = applicationName(app);
2522
3010
  if (tier === 'view' && type === 'key' && onlyScrollKeys(item.keys))
2523
3011
  continue;
2524
- if (tier === 'view')
2525
- return `computer_use only looks at ${name}, a browser: it does not click, type or press keys there. Use the browser tool to act on a page; take a screenshot to see what the window shows. Nothing was done.`;
2526
- if (tier === 'click' && !TERMINAL_APPS.test(app) && (TYPING_ACTIONS.has(type) || setsValue))
3012
+ if (tier === 'view') {
3013
+ const refused = await browserWindowRefusal(app, name, context);
3014
+ if (refused)
3015
+ return refused;
3016
+ // A granted browser still never gets a secret typed by the tool: the person types it.
3017
+ const ref = typeof item.ref === 'string' ? uiRefs.get(item.ref) : undefined;
3018
+ if ((type === 'type_text' && focusedSecret) ||
3019
+ (setsValue && ref !== undefined && isSecretElement(ref.element)))
3020
+ return `computer_use does not type into a password field in ${name}. Nothing was done. Ask the person to type it themselves, then continue.`;
3021
+ }
3022
+ if (tier === 'click' &&
3023
+ !appIs(TERMINAL_APPS, app) &&
3024
+ (TYPING_ACTIONS.has(type) || setsValue))
2527
3025
  return `computer_use clicks in ${name} but does not type or press keys there. Use the shell tool for a command and the edit tools for a file. Nothing was done.`;
2528
3026
  }
2529
3027
  }
@@ -2549,7 +3047,7 @@ export function createComputerUseTool(host, options = {}) {
2549
3047
  try {
2550
3048
  switch (input.type) {
2551
3049
  case 'screenshot':
2552
- return screenshotResult(await capture(input.window_id));
3050
+ return await firstLookWithTree(await capture(input.window_id), input.window_id);
2553
3051
  case 'zoom':
2554
3052
  return await zoom(input);
2555
3053
  case 'ui_snapshot':
@@ -2579,7 +3077,7 @@ export function createComputerUseTool(host, options = {}) {
2579
3077
  };
2580
3078
  const tool = defineTool({
2581
3079
  name: COMPUTER_USE_TOOL_NAME,
2582
- description: buildDescription(host, caps, settings, options.advisor),
3080
+ description: buildDescription(host, caps, settings, options.advisor, browserSetting),
2583
3081
  inputSchema: actionSchema,
2584
3082
  modelInputSchema: hostModelSchema(host, caps, settings, options.advisor),
2585
3083
  validationErrorHint: `Action requirements: ${ALL_ACTIONS.map((action) => actionRequirement(action, host, caps)).join('; ')}. A batch is {"type":"batch","actions":[...]} with at most ${settings.maxBatchActions} actions and no screenshot, zoom, ui_snapshot or batch inside.`,
@@ -2626,12 +3124,28 @@ export function createComputerUseTool(host, options = {}) {
2626
3124
  const result = await runAction(input, context);
2627
3125
  if (app && result.success !== false && !appsUsed.has(app) && !isReadOnlyInput(input)) {
2628
3126
  appsUsed.add(app);
2629
- result.data = { ...(isRecord(result.data) ? result.data : {}), firstUseOf: app };
3127
+ result.data = {
3128
+ ...(isRecord(result.data) ? result.data : {}),
3129
+ firstUseOf: app,
3130
+ };
2630
3131
  }
2631
3132
  await observe(input, before, result, context.toolUseId, app);
2632
3133
  return result;
2633
3134
  },
2634
3135
  });
2635
- return Object.assign(tool, { describeUiRef, appOf, appsOf, consequence });
3136
+ const browserQuestionPending = (app) => appTier(app) === 'view' &&
3137
+ readBrowserSetting() === 'ask' &&
3138
+ options.askBrowserWindow !== undefined &&
3139
+ !browserGranted.has(browserKey(app));
3140
+ return Object.assign(tool, {
3141
+ describeUiRef,
3142
+ appOf,
3143
+ appsOf,
3144
+ consequence,
3145
+ browserGrants: () => [...browserGranted.values()],
3146
+ revokeBrowserGrant: (app) => browserGranted.delete(browserKey(app)),
3147
+ browserQuestionPending,
3148
+ browserAsk: (input, apps) => isReadOnlyInput(input) ? [] : apps.filter((app) => browserQuestionPending(app)),
3149
+ });
2636
3150
  }
2637
3151
  //# sourceMappingURL=computer-use.js.map