@namzu/sdk 45.1.0 → 48.0.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 (767) hide show
  1. package/CHANGELOG.md +436 -8
  2. package/README.md +7 -8
  3. package/dist/advisory/history.d.ts.map +1 -1
  4. package/dist/advisory/history.js +21 -1
  5. package/dist/advisory/history.js.map +1 -1
  6. package/dist/advisory/index.d.ts +1 -1
  7. package/dist/advisory/index.d.ts.map +1 -1
  8. package/dist/advisory/index.js +1 -1
  9. package/dist/advisory/index.js.map +1 -1
  10. package/dist/advisory/registry.d.ts +17 -0
  11. package/dist/advisory/registry.d.ts.map +1 -1
  12. package/dist/advisory/registry.js +26 -0
  13. package/dist/advisory/registry.js.map +1 -1
  14. package/dist/agents/PipelineAgent.d.ts +2 -46
  15. package/dist/agents/PipelineAgent.d.ts.map +1 -1
  16. package/dist/agents/PipelineAgent.js +2 -242
  17. package/dist/agents/PipelineAgent.js.map +1 -1
  18. package/dist/agents/QueryAgent.d.ts +21 -0
  19. package/dist/agents/QueryAgent.d.ts.map +1 -0
  20. package/dist/agents/QueryAgent.js +214 -0
  21. package/dist/agents/QueryAgent.js.map +1 -0
  22. package/dist/agents/ReactiveAgent.d.ts +4 -16
  23. package/dist/agents/ReactiveAgent.d.ts.map +1 -1
  24. package/dist/agents/ReactiveAgent.js +4 -183
  25. package/dist/agents/ReactiveAgent.js.map +1 -1
  26. package/dist/agents/RouterAgent.d.ts +2 -20
  27. package/dist/agents/RouterAgent.d.ts.map +1 -1
  28. package/dist/agents/RouterAgent.js +2 -266
  29. package/dist/agents/RouterAgent.js.map +1 -1
  30. package/dist/agents/SupervisorAgent.d.ts +3 -43
  31. package/dist/agents/SupervisorAgent.d.ts.map +1 -1
  32. package/dist/agents/SupervisorAgent.js +3 -418
  33. package/dist/agents/SupervisorAgent.js.map +1 -1
  34. package/dist/agents/defineAgent.d.ts +2 -1
  35. package/dist/agents/defineAgent.d.ts.map +1 -1
  36. package/dist/agents/defineAgent.js +6 -1
  37. package/dist/agents/defineAgent.js.map +1 -1
  38. package/dist/agents/examples/PipelineAgent.d.ts +46 -0
  39. package/dist/agents/examples/PipelineAgent.d.ts.map +1 -0
  40. package/dist/agents/examples/PipelineAgent.js +242 -0
  41. package/dist/agents/examples/PipelineAgent.js.map +1 -0
  42. package/dist/agents/examples/RouterAgent.d.ts +22 -0
  43. package/dist/agents/examples/RouterAgent.d.ts.map +1 -0
  44. package/dist/agents/examples/RouterAgent.js +268 -0
  45. package/dist/agents/examples/RouterAgent.js.map +1 -0
  46. package/dist/agents/examples/SupervisorAgent.d.ts +45 -0
  47. package/dist/agents/examples/SupervisorAgent.d.ts.map +1 -0
  48. package/dist/agents/examples/SupervisorAgent.js +406 -0
  49. package/dist/agents/examples/SupervisorAgent.js.map +1 -0
  50. package/dist/agents/explore.d.ts +6 -3
  51. package/dist/agents/explore.d.ts.map +1 -1
  52. package/dist/agents/explore.js +6 -3
  53. package/dist/agents/explore.js.map +1 -1
  54. package/dist/agents/forward-options.d.ts +11 -0
  55. package/dist/agents/forward-options.d.ts.map +1 -0
  56. package/dist/agents/forward-options.js +15 -0
  57. package/dist/agents/forward-options.js.map +1 -0
  58. package/dist/agents/index.d.ts +1 -0
  59. package/dist/agents/index.d.ts.map +1 -1
  60. package/dist/agents/index.js +2 -0
  61. package/dist/agents/index.js.map +1 -1
  62. package/dist/agents/runAgent.d.ts +19 -8
  63. package/dist/agents/runAgent.d.ts.map +1 -1
  64. package/dist/agents/runAgent.js +99 -29
  65. package/dist/agents/runAgent.js.map +1 -1
  66. package/dist/authorization/command-line.d.ts +2 -0
  67. package/dist/authorization/command-line.d.ts.map +1 -1
  68. package/dist/authorization/command-line.js +2 -2
  69. package/dist/authorization/command-line.js.map +1 -1
  70. package/dist/authorization/gate.d.ts +13 -2
  71. package/dist/authorization/gate.d.ts.map +1 -1
  72. package/dist/authorization/gate.js +37 -5
  73. package/dist/authorization/gate.js.map +1 -1
  74. package/dist/authorization/program.d.ts +151 -0
  75. package/dist/authorization/program.d.ts.map +1 -0
  76. package/dist/authorization/program.js +713 -0
  77. package/dist/authorization/program.js.map +1 -0
  78. package/dist/authorization/reexec-wrapper.d.ts +106 -0
  79. package/dist/authorization/reexec-wrapper.d.ts.map +1 -0
  80. package/dist/authorization/reexec-wrapper.js +532 -0
  81. package/dist/authorization/reexec-wrapper.js.map +1 -0
  82. package/dist/authorization/rules.d.ts +9 -0
  83. package/dist/authorization/rules.d.ts.map +1 -1
  84. package/dist/authorization/rules.js +27 -1
  85. package/dist/authorization/rules.js.map +1 -1
  86. package/dist/authorization/shell-lexer.d.ts +39 -0
  87. package/dist/authorization/shell-lexer.d.ts.map +1 -1
  88. package/dist/authorization/shell-lexer.js +113 -69
  89. package/dist/authorization/shell-lexer.js.map +1 -1
  90. package/dist/bridge/sse/mapper.d.ts.map +1 -1
  91. package/dist/bridge/sse/mapper.js +6 -0
  92. package/dist/bridge/sse/mapper.js.map +1 -1
  93. package/dist/capabilities/index.d.ts +54 -0
  94. package/dist/capabilities/index.d.ts.map +1 -0
  95. package/dist/capabilities/index.js +92 -0
  96. package/dist/capabilities/index.js.map +1 -0
  97. package/dist/config/registry.d.ts +2 -1
  98. package/dist/config/registry.d.ts.map +1 -1
  99. package/dist/config/registry.js +3 -2
  100. package/dist/config/registry.js.map +1 -1
  101. package/dist/connector/index.d.ts +4 -4
  102. package/dist/connector/index.d.ts.map +1 -1
  103. package/dist/connector/index.js +3 -3
  104. package/dist/connector/index.js.map +1 -1
  105. package/dist/connector/mcp/adapter.d.ts +16 -1
  106. package/dist/connector/mcp/adapter.d.ts.map +1 -1
  107. package/dist/connector/mcp/adapter.js +60 -4
  108. package/dist/connector/mcp/adapter.js.map +1 -1
  109. package/dist/connector/mcp/client.d.ts +13 -4
  110. package/dist/connector/mcp/client.d.ts.map +1 -1
  111. package/dist/connector/mcp/client.js +20 -3
  112. package/dist/connector/mcp/client.js.map +1 -1
  113. package/dist/connector/mcp/discovery.d.ts +24 -1
  114. package/dist/connector/mcp/discovery.d.ts.map +1 -1
  115. package/dist/connector/mcp/discovery.js +44 -0
  116. package/dist/connector/mcp/discovery.js.map +1 -1
  117. package/dist/connector/mcp/index.d.ts +2 -0
  118. package/dist/connector/mcp/index.d.ts.map +1 -1
  119. package/dist/connector/mcp/index.js +11 -0
  120. package/dist/connector/mcp/index.js.map +1 -1
  121. package/dist/connector/mcp/mcp-toolset.d.ts +133 -0
  122. package/dist/connector/mcp/mcp-toolset.d.ts.map +1 -0
  123. package/dist/connector/mcp/mcp-toolset.js +399 -0
  124. package/dist/connector/mcp/mcp-toolset.js.map +1 -0
  125. package/dist/connector/tools/index.d.ts +2 -2
  126. package/dist/connector/tools/index.d.ts.map +1 -1
  127. package/dist/connector/tools/index.js +1 -1
  128. package/dist/connector/tools/index.js.map +1 -1
  129. package/dist/connector/tools/router.d.ts +15 -13
  130. package/dist/connector/tools/router.d.ts.map +1 -1
  131. package/dist/connector/tools/router.js +30 -51
  132. package/dist/connector/tools/router.js.map +1 -1
  133. package/dist/contracts/a2a.d.ts +2 -2
  134. package/dist/directory/derive-supervisor.d.ts +2 -2
  135. package/dist/directory/derive-supervisor.d.ts.map +1 -1
  136. package/dist/directory/derive-supervisor.js +6 -7
  137. package/dist/directory/derive-supervisor.js.map +1 -1
  138. package/dist/directory/derive.d.ts.map +1 -1
  139. package/dist/directory/derive.js +5 -5
  140. package/dist/directory/derive.js.map +1 -1
  141. package/dist/execution/code-runtime/types.d.ts +2 -2
  142. package/dist/execution/code-runtime/types.js +1 -1
  143. package/dist/invariants/index.d.ts +2 -1
  144. package/dist/invariants/index.d.ts.map +1 -1
  145. package/dist/invariants/index.js +3 -2
  146. package/dist/invariants/index.js.map +1 -1
  147. package/dist/manager/agent/lifecycle.d.ts.map +1 -1
  148. package/dist/manager/agent/lifecycle.js +9 -0
  149. package/dist/manager/agent/lifecycle.js.map +1 -1
  150. package/dist/manager/connector/environment.d.ts +6 -0
  151. package/dist/manager/connector/environment.d.ts.map +1 -1
  152. package/dist/manager/connector/environment.js +11 -4
  153. package/dist/manager/connector/environment.js.map +1 -1
  154. package/dist/manager/connector/index.d.ts +2 -2
  155. package/dist/manager/connector/index.d.ts.map +1 -1
  156. package/dist/manager/connector/index.js +2 -2
  157. package/dist/manager/connector/index.js.map +1 -1
  158. package/dist/manager/connector/tenant.d.ts +6 -0
  159. package/dist/manager/connector/tenant.d.ts.map +1 -1
  160. package/dist/manager/connector/tenant.js +11 -4
  161. package/dist/manager/connector/tenant.js.map +1 -1
  162. package/dist/manager/index.d.ts +2 -2
  163. package/dist/manager/index.d.ts.map +1 -1
  164. package/dist/manager/index.js +2 -2
  165. package/dist/manager/index.js.map +1 -1
  166. package/dist/manager/resident/learning-observation.d.ts +4 -4
  167. package/dist/manager/resident/learning.d.ts +36 -36
  168. package/dist/manager/session/attribution.d.ts +22 -0
  169. package/dist/manager/session/attribution.d.ts.map +1 -0
  170. package/dist/manager/session/attribution.js +64 -0
  171. package/dist/manager/session/attribution.js.map +1 -0
  172. package/dist/manager/session/turn-recorder.d.ts +14 -0
  173. package/dist/manager/session/turn-recorder.d.ts.map +1 -1
  174. package/dist/manager/session/turn-recorder.js +208 -55
  175. package/dist/manager/session/turn-recorder.js.map +1 -1
  176. package/dist/peers/address.d.ts +36 -0
  177. package/dist/peers/address.d.ts.map +1 -0
  178. package/dist/peers/address.js +52 -0
  179. package/dist/peers/address.js.map +1 -0
  180. package/dist/peers/client.d.ts +47 -0
  181. package/dist/peers/client.d.ts.map +1 -0
  182. package/dist/peers/client.js +132 -0
  183. package/dist/peers/client.js.map +1 -0
  184. package/dist/peers/dir.d.ts +88 -0
  185. package/dist/peers/dir.d.ts.map +1 -0
  186. package/dist/peers/dir.js +139 -0
  187. package/dist/peers/dir.js.map +1 -0
  188. package/dist/peers/endpoint.d.ts +144 -0
  189. package/dist/peers/endpoint.d.ts.map +1 -0
  190. package/dist/peers/endpoint.js +420 -0
  191. package/dist/peers/endpoint.js.map +1 -0
  192. package/dist/peers/envelope.d.ts +42 -0
  193. package/dist/peers/envelope.d.ts.map +1 -0
  194. package/dist/peers/envelope.js +110 -0
  195. package/dist/peers/envelope.js.map +1 -0
  196. package/dist/peers/index.d.ts +30 -0
  197. package/dist/peers/index.d.ts.map +1 -0
  198. package/dist/peers/index.js +22 -0
  199. package/dist/peers/index.js.map +1 -0
  200. package/dist/peers/protocol.d.ts +645 -0
  201. package/dist/peers/protocol.d.ts.map +1 -0
  202. package/dist/peers/protocol.js +151 -0
  203. package/dist/peers/protocol.js.map +1 -0
  204. package/dist/peers/record.d.ts +71 -0
  205. package/dist/peers/record.d.ts.map +1 -0
  206. package/dist/peers/record.js +45 -0
  207. package/dist/peers/record.js.map +1 -0
  208. package/dist/peers/registry.d.ts +54 -0
  209. package/dist/peers/registry.d.ts.map +1 -0
  210. package/dist/peers/registry.js +213 -0
  211. package/dist/peers/registry.js.map +1 -0
  212. package/dist/plugin/define.d.ts +24 -0
  213. package/dist/plugin/define.d.ts.map +1 -0
  214. package/dist/plugin/define.js +42 -0
  215. package/dist/plugin/define.js.map +1 -0
  216. package/dist/plugin/index.d.ts +2 -0
  217. package/dist/plugin/index.d.ts.map +1 -1
  218. package/dist/plugin/index.js +1 -0
  219. package/dist/plugin/index.js.map +1 -1
  220. package/dist/plugin/lifecycle.d.ts +27 -3
  221. package/dist/plugin/lifecycle.d.ts.map +1 -1
  222. package/dist/plugin/lifecycle.js +242 -92
  223. package/dist/plugin/lifecycle.js.map +1 -1
  224. package/dist/plugin/resolver.d.ts +2 -2
  225. package/dist/plugin/resolver.d.ts.map +1 -1
  226. package/dist/plugin/resolver.js.map +1 -1
  227. package/dist/plugin/shell-hook.d.ts.map +1 -1
  228. package/dist/plugin/shell-hook.js +17 -3
  229. package/dist/plugin/shell-hook.js.map +1 -1
  230. package/dist/pricing/catalogue.generated.d.ts.map +1 -1
  231. package/dist/pricing/catalogue.generated.js +28 -4
  232. package/dist/pricing/catalogue.generated.js.map +1 -1
  233. package/dist/probe/errors.d.ts +2 -1
  234. package/dist/probe/errors.d.ts.map +1 -1
  235. package/dist/probe/errors.js +3 -2
  236. package/dist/probe/errors.js.map +1 -1
  237. package/dist/prompt/coding-agent-doctrine.d.ts +18 -7
  238. package/dist/prompt/coding-agent-doctrine.d.ts.map +1 -1
  239. package/dist/prompt/coding-agent-doctrine.js +11 -6
  240. package/dist/prompt/coding-agent-doctrine.js.map +1 -1
  241. package/dist/prompt/contributions.d.ts +4 -1
  242. package/dist/prompt/contributions.d.ts.map +1 -1
  243. package/dist/prompt/contributions.js +7 -2
  244. package/dist/prompt/contributions.js.map +1 -1
  245. package/dist/prompt/index.d.ts +1 -1
  246. package/dist/prompt/index.d.ts.map +1 -1
  247. package/dist/prompt/index.js +1 -1
  248. package/dist/prompt/index.js.map +1 -1
  249. package/dist/provider/collect-chat-completion.d.ts +6 -1
  250. package/dist/provider/collect-chat-completion.d.ts.map +1 -1
  251. package/dist/provider/collect-chat-completion.js +88 -10
  252. package/dist/provider/collect-chat-completion.js.map +1 -1
  253. package/dist/provider/mock.d.ts.map +1 -1
  254. package/dist/provider/mock.js +23 -6
  255. package/dist/provider/mock.js.map +1 -1
  256. package/dist/provider/registry.d.ts +2 -1
  257. package/dist/provider/registry.d.ts.map +1 -1
  258. package/dist/provider/registry.js +3 -2
  259. package/dist/provider/registry.js.map +1 -1
  260. package/dist/provider/tool-call-framing.d.ts +164 -0
  261. package/dist/provider/tool-call-framing.d.ts.map +1 -0
  262. package/dist/provider/tool-call-framing.js +163 -0
  263. package/dist/provider/tool-call-framing.js.map +1 -0
  264. package/dist/public-runtime.d.ts +27 -14
  265. package/dist/public-runtime.d.ts.map +1 -1
  266. package/dist/public-runtime.js +49 -11
  267. package/dist/public-runtime.js.map +1 -1
  268. package/dist/public-tools.d.ts +9 -6
  269. package/dist/public-tools.d.ts.map +1 -1
  270. package/dist/public-tools.js +13 -5
  271. package/dist/public-tools.js.map +1 -1
  272. package/dist/public-types.d.ts +16 -5
  273. package/dist/public-types.d.ts.map +1 -1
  274. package/dist/read-model/registry.d.ts +2 -1
  275. package/dist/read-model/registry.d.ts.map +1 -1
  276. package/dist/read-model/registry.js +3 -2
  277. package/dist/read-model/registry.js.map +1 -1
  278. package/dist/registry/ManagedRegistry.d.ts +30 -0
  279. package/dist/registry/ManagedRegistry.d.ts.map +1 -1
  280. package/dist/registry/ManagedRegistry.js +45 -6
  281. package/dist/registry/ManagedRegistry.js.map +1 -1
  282. package/dist/registry/collision.d.ts +57 -0
  283. package/dist/registry/collision.d.ts.map +1 -0
  284. package/dist/registry/collision.js +41 -0
  285. package/dist/registry/collision.js.map +1 -0
  286. package/dist/registry/command/index.d.ts +5 -3
  287. package/dist/registry/command/index.d.ts.map +1 -1
  288. package/dist/registry/command/index.js +6 -4
  289. package/dist/registry/command/index.js.map +1 -1
  290. package/dist/registry/index.d.ts +3 -4
  291. package/dist/registry/index.d.ts.map +1 -1
  292. package/dist/registry/index.js +2 -2
  293. package/dist/registry/index.js.map +1 -1
  294. package/dist/registry/plugin/index.d.ts.map +1 -1
  295. package/dist/registry/plugin/index.js +14 -1
  296. package/dist/registry/plugin/index.js.map +1 -1
  297. package/dist/registry/tool/callable.d.ts +22 -0
  298. package/dist/registry/tool/callable.d.ts.map +1 -0
  299. package/dist/registry/tool/callable.js +28 -0
  300. package/dist/registry/tool/callable.js.map +1 -0
  301. package/dist/registry/tool/execute.d.ts +14 -77
  302. package/dist/registry/tool/execute.d.ts.map +1 -1
  303. package/dist/registry/tool/execute.js +15 -720
  304. package/dist/registry/tool/execute.js.map +1 -1
  305. package/dist/registry/tool/portable.d.ts +25 -0
  306. package/dist/registry/tool/portable.d.ts.map +1 -1
  307. package/dist/registry/tool/portable.js +50 -0
  308. package/dist/registry/tool/portable.js.map +1 -1
  309. package/dist/registry/tool/presentation.d.ts +6 -5
  310. package/dist/registry/tool/presentation.d.ts.map +1 -1
  311. package/dist/registry/tool/presentation.js +3 -3
  312. package/dist/registry/tool/presentation.js.map +1 -1
  313. package/dist/runtime/bidi/session.d.ts +5 -4
  314. package/dist/runtime/bidi/session.d.ts.map +1 -1
  315. package/dist/runtime/bidi/session.js +18 -1
  316. package/dist/runtime/bidi/session.js.map +1 -1
  317. package/dist/runtime/query/executor/tool-call-admission.d.ts +82 -13
  318. package/dist/runtime/query/executor/tool-call-admission.d.ts.map +1 -1
  319. package/dist/runtime/query/executor/tool-call-admission.js +227 -17
  320. package/dist/runtime/query/executor/tool-call-admission.js.map +1 -1
  321. package/dist/runtime/query/executor.d.ts +37 -5
  322. package/dist/runtime/query/executor.d.ts.map +1 -1
  323. package/dist/runtime/query/executor.js +103 -14
  324. package/dist/runtime/query/executor.js.map +1 -1
  325. package/dist/runtime/query/file-evidence-replay.d.ts +1 -1
  326. package/dist/runtime/query/file-evidence-replay.d.ts.map +1 -1
  327. package/dist/runtime/query/file-evidence-replay.js +8 -7
  328. package/dist/runtime/query/file-evidence-replay.js.map +1 -1
  329. package/dist/runtime/query/fork/prepare.d.ts +4 -1
  330. package/dist/runtime/query/fork/prepare.d.ts.map +1 -1
  331. package/dist/runtime/query/fork/prepare.js +4 -0
  332. package/dist/runtime/query/fork/prepare.js.map +1 -1
  333. package/dist/runtime/query/guardrail-presets.d.ts +4 -3
  334. package/dist/runtime/query/guardrail-presets.d.ts.map +1 -1
  335. package/dist/runtime/query/guardrail-presets.js +4 -3
  336. package/dist/runtime/query/guardrail-presets.js.map +1 -1
  337. package/dist/runtime/query/index.d.ts +23 -10
  338. package/dist/runtime/query/index.d.ts.map +1 -1
  339. package/dist/runtime/query/index.js +149 -70
  340. package/dist/runtime/query/index.js.map +1 -1
  341. package/dist/runtime/query/iteration/index.d.ts.map +1 -1
  342. package/dist/runtime/query/iteration/index.js +8 -1
  343. package/dist/runtime/query/iteration/index.js.map +1 -1
  344. package/dist/runtime/query/iteration/phases/compaction.js +1 -1
  345. package/dist/runtime/query/iteration/phases/compaction.js.map +1 -1
  346. package/dist/runtime/query/iteration/phases/context.d.ts +2 -2
  347. package/dist/runtime/query/iteration/phases/context.d.ts.map +1 -1
  348. package/dist/runtime/query/iteration/phases/tool-review.d.ts.map +1 -1
  349. package/dist/runtime/query/iteration/phases/tool-review.js +55 -2
  350. package/dist/runtime/query/iteration/phases/tool-review.js.map +1 -1
  351. package/dist/runtime/query/iteration/stream-turn.d.ts.map +1 -1
  352. package/dist/runtime/query/iteration/stream-turn.js +342 -116
  353. package/dist/runtime/query/iteration/stream-turn.js.map +1 -1
  354. package/dist/runtime/query/iteration/tool-input.d.ts +79 -0
  355. package/dist/runtime/query/iteration/tool-input.d.ts.map +1 -0
  356. package/dist/runtime/query/iteration/tool-input.js +291 -0
  357. package/dist/runtime/query/iteration/tool-input.js.map +1 -0
  358. package/dist/runtime/query/observation-context.d.ts +2 -2
  359. package/dist/runtime/query/observation-context.d.ts.map +1 -1
  360. package/dist/runtime/query/observation-context.js.map +1 -1
  361. package/dist/runtime/query/prelude-lease.d.ts +18 -0
  362. package/dist/runtime/query/prelude-lease.d.ts.map +1 -0
  363. package/dist/runtime/query/prelude-lease.js +121 -0
  364. package/dist/runtime/query/prelude-lease.js.map +1 -0
  365. package/dist/runtime/query/prepare-turn.d.ts.map +1 -1
  366. package/dist/runtime/query/prepare-turn.js +386 -187
  367. package/dist/runtime/query/prepare-turn.js.map +1 -1
  368. package/dist/runtime/query/prompt-cache.d.ts +2 -2
  369. package/dist/runtime/query/prompt-cache.d.ts.map +1 -1
  370. package/dist/runtime/query/prompt.d.ts +2 -2
  371. package/dist/runtime/query/prompt.d.ts.map +1 -1
  372. package/dist/runtime/query/prompt.js +1 -1
  373. package/dist/runtime/query/prompt.js.map +1 -1
  374. package/dist/runtime/query/resume-session.d.ts.map +1 -1
  375. package/dist/runtime/query/resume-session.js +37 -2
  376. package/dist/runtime/query/resume-session.js.map +1 -1
  377. package/dist/runtime/query/review-policy.d.ts +65 -3
  378. package/dist/runtime/query/review-policy.d.ts.map +1 -1
  379. package/dist/runtime/query/review-policy.js +143 -22
  380. package/dist/runtime/query/review-policy.js.map +1 -1
  381. package/dist/runtime/query/tooling.d.ts +3 -2
  382. package/dist/runtime/query/tooling.d.ts.map +1 -1
  383. package/dist/runtime/query/tooling.js.map +1 -1
  384. package/dist/runtime/query/turn-state.d.ts.map +1 -1
  385. package/dist/runtime/query/turn-state.js +5 -0
  386. package/dist/runtime/query/turn-state.js.map +1 -1
  387. package/dist/runtime/system-events.d.ts +112 -0
  388. package/dist/runtime/system-events.d.ts.map +1 -0
  389. package/dist/runtime/system-events.js +183 -0
  390. package/dist/runtime/system-events.js.map +1 -0
  391. package/dist/scheduler/delegating.d.ts +2 -1
  392. package/dist/scheduler/delegating.d.ts.map +1 -1
  393. package/dist/scheduler/delegating.js +3 -2
  394. package/dist/scheduler/delegating.js.map +1 -1
  395. package/dist/skills/index.d.ts +1 -1
  396. package/dist/skills/index.d.ts.map +1 -1
  397. package/dist/skills/index.js +1 -1
  398. package/dist/skills/index.js.map +1 -1
  399. package/dist/skills/registry.d.ts +18 -0
  400. package/dist/skills/registry.d.ts.map +1 -1
  401. package/dist/skills/registry.js +20 -0
  402. package/dist/skills/registry.js.map +1 -1
  403. package/dist/store/evidence/index-page.d.ts +2 -2
  404. package/dist/store/session-log/conformance.d.ts +1 -1
  405. package/dist/store/session-log/conformance.d.ts.map +1 -1
  406. package/dist/store/session-log/conformance.js +49 -8
  407. package/dist/store/session-log/conformance.js.map +1 -1
  408. package/dist/store/session-log/core.d.ts +8 -3
  409. package/dist/store/session-log/core.d.ts.map +1 -1
  410. package/dist/store/session-log/core.js +2 -1
  411. package/dist/store/session-log/core.js.map +1 -1
  412. package/dist/store/session-log/fold.d.ts +12 -0
  413. package/dist/store/session-log/fold.d.ts.map +1 -1
  414. package/dist/store/session-log/fold.js +57 -7
  415. package/dist/store/session-log/fold.js.map +1 -1
  416. package/dist/store/session-log/index.d.ts +2 -2
  417. package/dist/store/session-log/index.d.ts.map +1 -1
  418. package/dist/store/session-log/index.js +1 -1
  419. package/dist/store/session-log/index.js.map +1 -1
  420. package/dist/test-support/toolset.d.ts +19 -0
  421. package/dist/test-support/toolset.d.ts.map +1 -0
  422. package/dist/test-support/toolset.js +20 -0
  423. package/dist/test-support/toolset.js.map +1 -0
  424. package/dist/tools/builtins/bash.d.ts +29 -0
  425. package/dist/tools/builtins/bash.d.ts.map +1 -1
  426. package/dist/tools/builtins/bash.js +19 -9
  427. package/dist/tools/builtins/bash.js.map +1 -1
  428. package/dist/tools/builtins/browser-url.d.ts +1 -1
  429. package/dist/tools/builtins/browser-url.js +1 -1
  430. package/dist/tools/builtins/browser.d.ts +6 -6
  431. package/dist/tools/builtins/computer-use-coordinates.d.ts +65 -0
  432. package/dist/tools/builtins/computer-use-coordinates.d.ts.map +1 -0
  433. package/dist/tools/builtins/computer-use-coordinates.js +123 -0
  434. package/dist/tools/builtins/computer-use-coordinates.js.map +1 -0
  435. package/dist/tools/builtins/computer-use-image.d.ts +77 -0
  436. package/dist/tools/builtins/computer-use-image.d.ts.map +1 -0
  437. package/dist/tools/builtins/computer-use-image.js +223 -0
  438. package/dist/tools/builtins/computer-use-image.js.map +1 -0
  439. package/dist/tools/builtins/computer-use.d.ts +519 -14
  440. package/dist/tools/builtins/computer-use.d.ts.map +1 -1
  441. package/dist/tools/builtins/computer-use.js +1196 -183
  442. package/dist/tools/builtins/computer-use.js.map +1 -1
  443. package/dist/tools/builtins/edit.d.ts.map +1 -1
  444. package/dist/tools/builtins/edit.js +9 -1
  445. package/dist/tools/builtins/edit.js.map +1 -1
  446. package/dist/tools/builtins/index.d.ts +2 -1
  447. package/dist/tools/builtins/index.d.ts.map +1 -1
  448. package/dist/tools/builtins/index.js +1 -1
  449. package/dist/tools/builtins/index.js.map +1 -1
  450. package/dist/tools/builtins/json-string-hint.d.ts +15 -0
  451. package/dist/tools/builtins/json-string-hint.d.ts.map +1 -0
  452. package/dist/tools/builtins/json-string-hint.js +17 -0
  453. package/dist/tools/builtins/json-string-hint.js.map +1 -0
  454. package/dist/tools/builtins/search-tools.d.ts.map +1 -1
  455. package/dist/tools/builtins/search-tools.js +7 -15
  456. package/dist/tools/builtins/search-tools.js.map +1 -1
  457. package/dist/tools/builtins/skill.d.ts +74 -0
  458. package/dist/tools/builtins/skill.d.ts.map +1 -1
  459. package/dist/tools/builtins/skill.js +214 -174
  460. package/dist/tools/builtins/skill.js.map +1 -1
  461. package/dist/tools/builtins/write-file.d.ts.map +1 -1
  462. package/dist/tools/builtins/write-file.js +11 -0
  463. package/dist/tools/builtins/write-file.js.map +1 -1
  464. package/dist/tools/command-shell.d.ts +10 -0
  465. package/dist/tools/command-shell.d.ts.map +1 -1
  466. package/dist/tools/command-shell.js +45 -1
  467. package/dist/tools/command-shell.js.map +1 -1
  468. package/dist/tools/coordinator/agent.d.ts.map +1 -1
  469. package/dist/tools/coordinator/agent.js +5 -0
  470. package/dist/tools/coordinator/agent.js.map +1 -1
  471. package/dist/tools/coordinator/ask-user-question.d.ts.map +1 -1
  472. package/dist/tools/coordinator/ask-user-question.js +26 -13
  473. package/dist/tools/coordinator/ask-user-question.js.map +1 -1
  474. package/dist/tools/coordinator/index.d.ts.map +1 -1
  475. package/dist/tools/coordinator/index.js +5 -0
  476. package/dist/tools/coordinator/index.js.map +1 -1
  477. package/dist/tools/coordinator/question-options.d.ts +78 -0
  478. package/dist/tools/coordinator/question-options.d.ts.map +1 -0
  479. package/dist/tools/coordinator/question-options.js +153 -0
  480. package/dist/tools/coordinator/question-options.js.map +1 -0
  481. package/dist/tools/defineTool.d.ts +12 -0
  482. package/dist/tools/defineTool.d.ts.map +1 -1
  483. package/dist/tools/defineTool.js +24 -0
  484. package/dist/tools/defineTool.js.map +1 -1
  485. package/dist/tools/memory/search.d.ts.map +1 -1
  486. package/dist/tools/memory/search.js +4 -1
  487. package/dist/tools/memory/search.js.map +1 -1
  488. package/dist/tools/memory/update.d.ts.map +1 -1
  489. package/dist/tools/memory/update.js +8 -5
  490. package/dist/tools/memory/update.js.map +1 -1
  491. package/dist/tools/render-nonce.d.ts +47 -0
  492. package/dist/tools/render-nonce.d.ts.map +1 -0
  493. package/dist/tools/render-nonce.js +63 -0
  494. package/dist/tools/render-nonce.js.map +1 -0
  495. package/dist/tools/roster.d.ts +46 -19
  496. package/dist/tools/roster.d.ts.map +1 -1
  497. package/dist/tools/roster.js +63 -33
  498. package/dist/tools/roster.js.map +1 -1
  499. package/dist/tools/schedules/present.d.ts.map +1 -1
  500. package/dist/tools/schedules/present.js +2 -0
  501. package/dist/tools/schedules/present.js.map +1 -1
  502. package/dist/tools/schedules/schedule-tool.d.ts +6 -5
  503. package/dist/tools/schedules/schedule-tool.d.ts.map +1 -1
  504. package/dist/tools/schedules/schedule-tool.js +208 -37
  505. package/dist/tools/schedules/schedule-tool.js.map +1 -1
  506. package/dist/tools/schedules/types.d.ts +120 -6
  507. package/dist/tools/schedules/types.d.ts.map +1 -1
  508. package/dist/tools/trusted-read-only.d.ts +9 -5
  509. package/dist/tools/trusted-read-only.d.ts.map +1 -1
  510. package/dist/tools/trusted-read-only.js +14 -10
  511. package/dist/tools/trusted-read-only.js.map +1 -1
  512. package/dist/tools/untrusted-envelope.d.ts +67 -28
  513. package/dist/tools/untrusted-envelope.d.ts.map +1 -1
  514. package/dist/tools/untrusted-envelope.js +108 -59
  515. package/dist/tools/untrusted-envelope.js.map +1 -1
  516. package/dist/toolsets/combine.d.ts +44 -0
  517. package/dist/toolsets/combine.d.ts.map +1 -0
  518. package/dist/toolsets/combine.js +153 -0
  519. package/dist/toolsets/combine.js.map +1 -0
  520. package/dist/toolsets/manager.d.ts +201 -0
  521. package/dist/toolsets/manager.d.ts.map +1 -0
  522. package/dist/toolsets/manager.js +837 -0
  523. package/dist/toolsets/manager.js.map +1 -0
  524. package/dist/toolsets/source-glob.d.ts +15 -0
  525. package/dist/toolsets/source-glob.d.ts.map +1 -0
  526. package/dist/toolsets/source-glob.js +23 -0
  527. package/dist/toolsets/source-glob.js.map +1 -0
  528. package/dist/toolsets/toolset.d.ts +20 -0
  529. package/dist/toolsets/toolset.d.ts.map +1 -0
  530. package/dist/toolsets/toolset.js +28 -0
  531. package/dist/toolsets/toolset.js.map +1 -0
  532. package/dist/toolsets/types.d.ts +128 -0
  533. package/dist/toolsets/types.d.ts.map +1 -0
  534. package/dist/toolsets/types.js +33 -0
  535. package/dist/toolsets/types.js.map +1 -0
  536. package/dist/toolsets/wrappers.d.ts +59 -0
  537. package/dist/toolsets/wrappers.d.ts.map +1 -0
  538. package/dist/toolsets/wrappers.js +165 -0
  539. package/dist/toolsets/wrappers.js.map +1 -0
  540. package/dist/types/agent/base.d.ts +27 -16
  541. package/dist/types/agent/base.d.ts.map +1 -1
  542. package/dist/types/agent/index.d.ts +1 -0
  543. package/dist/types/agent/index.d.ts.map +1 -1
  544. package/dist/types/agent/index.js +1 -0
  545. package/dist/types/agent/index.js.map +1 -1
  546. package/dist/types/agent/pipeline.d.ts +2 -0
  547. package/dist/types/agent/pipeline.d.ts.map +1 -1
  548. package/dist/types/agent/query.d.ts +117 -0
  549. package/dist/types/agent/query.d.ts.map +1 -0
  550. package/dist/types/agent/query.js +2 -0
  551. package/dist/types/agent/query.js.map +1 -0
  552. package/dist/types/agent/reactive.d.ts +2 -129
  553. package/dist/types/agent/reactive.d.ts.map +1 -1
  554. package/dist/types/agent/router.d.ts +2 -0
  555. package/dist/types/agent/router.d.ts.map +1 -1
  556. package/dist/types/agent/supervisor.d.ts +5 -2
  557. package/dist/types/agent/supervisor.d.ts.map +1 -1
  558. package/dist/types/authorization/index.d.ts +70 -12
  559. package/dist/types/authorization/index.d.ts.map +1 -1
  560. package/dist/types/authorization/index.js +11 -0
  561. package/dist/types/authorization/index.js.map +1 -1
  562. package/dist/types/computer-use/index.d.ts +176 -0
  563. package/dist/types/computer-use/index.d.ts.map +1 -1
  564. package/dist/types/computer-use/index.js.map +1 -1
  565. package/dist/types/connector/mcp.d.ts +32 -0
  566. package/dist/types/connector/mcp.d.ts.map +1 -1
  567. package/dist/types/errors/index.d.ts +15 -0
  568. package/dist/types/errors/index.d.ts.map +1 -1
  569. package/dist/types/errors/index.js.map +1 -1
  570. package/dist/types/hitl/index.d.ts +57 -0
  571. package/dist/types/hitl/index.d.ts.map +1 -1
  572. package/dist/types/hitl/index.js.map +1 -1
  573. package/dist/types/message/index.d.ts +130 -9
  574. package/dist/types/message/index.d.ts.map +1 -1
  575. package/dist/types/message/index.js +4 -1
  576. package/dist/types/message/index.js.map +1 -1
  577. package/dist/types/plugin/index.d.ts +22 -4
  578. package/dist/types/plugin/index.d.ts.map +1 -1
  579. package/dist/types/plugin/index.js +1 -0
  580. package/dist/types/plugin/index.js.map +1 -1
  581. package/dist/types/provider/chat.d.ts +5 -0
  582. package/dist/types/provider/chat.d.ts.map +1 -1
  583. package/dist/types/provider/config.d.ts +8 -3
  584. package/dist/types/provider/config.d.ts.map +1 -1
  585. package/dist/types/provider/stream.d.ts +39 -0
  586. package/dist/types/provider/stream.d.ts.map +1 -1
  587. package/dist/types/sandbox/index.d.ts +1 -1
  588. package/dist/types/session/events.d.ts +14 -3
  589. package/dist/types/session/events.d.ts.map +1 -1
  590. package/dist/types/session/events.js.map +1 -1
  591. package/dist/types/tool/index.d.ts +171 -91
  592. package/dist/types/tool/index.d.ts.map +1 -1
  593. package/dist/types/tool/index.js.map +1 -1
  594. package/dist/types/toolset/index.d.ts +10 -40
  595. package/dist/types/toolset/index.d.ts.map +1 -1
  596. package/package.json +3 -1
  597. package/src/advisory/history.ts +27 -2
  598. package/src/advisory/index.ts +1 -1
  599. package/src/advisory/registry.ts +33 -0
  600. package/src/agents/AGENTS.md +14 -7
  601. package/src/agents/PipelineAgent.ts +2 -303
  602. package/src/agents/QueryAgent.ts +269 -0
  603. package/src/agents/ReactiveAgent.ts +6 -216
  604. package/src/agents/RouterAgent.ts +2 -337
  605. package/src/agents/SupervisorAgent.ts +3 -476
  606. package/src/agents/defineAgent.ts +13 -2
  607. package/src/agents/examples/PipelineAgent.ts +302 -0
  608. package/src/agents/examples/RouterAgent.ts +338 -0
  609. package/src/agents/examples/SupervisorAgent.ts +472 -0
  610. package/src/agents/explore.ts +6 -3
  611. package/src/agents/forward-options.ts +37 -0
  612. package/src/agents/index.ts +2 -0
  613. package/src/agents/runAgent.ts +144 -37
  614. package/src/authorization/command-line.ts +2 -2
  615. package/src/authorization/gate.ts +46 -5
  616. package/src/authorization/program.ts +773 -0
  617. package/src/authorization/reexec-wrapper.ts +589 -0
  618. package/src/authorization/rules.ts +36 -1
  619. package/src/authorization/shell-lexer.ts +136 -63
  620. package/src/bridge/sse/mapper.ts +6 -0
  621. package/src/capabilities/index.ts +157 -0
  622. package/src/config/registry.ts +4 -1
  623. package/src/connector/index.ts +9 -2
  624. package/src/connector/mcp/adapter.ts +58 -3
  625. package/src/connector/mcp/client.ts +20 -4
  626. package/src/connector/mcp/discovery.ts +60 -0
  627. package/src/connector/mcp/index.ts +13 -0
  628. package/src/connector/mcp/mcp-toolset.ts +515 -0
  629. package/src/connector/tools/index.ts +2 -2
  630. package/src/connector/tools/router.ts +35 -58
  631. package/src/directory/derive-supervisor.ts +12 -8
  632. package/src/directory/derive.ts +8 -5
  633. package/src/execution/code-runtime/types.ts +2 -2
  634. package/src/invariants/index.ts +4 -1
  635. package/src/manager/agent/lifecycle.ts +9 -0
  636. package/src/manager/connector/environment.ts +17 -4
  637. package/src/manager/connector/index.ts +2 -2
  638. package/src/manager/connector/tenant.ts +17 -4
  639. package/src/manager/index.ts +2 -2
  640. package/src/manager/session/attribution.ts +79 -0
  641. package/src/manager/session/turn-recorder.ts +211 -55
  642. package/src/peers/address.ts +58 -0
  643. package/src/peers/client.ts +202 -0
  644. package/src/peers/dir.ts +176 -0
  645. package/src/peers/endpoint.ts +564 -0
  646. package/src/peers/envelope.ts +121 -0
  647. package/src/peers/index.ts +96 -0
  648. package/src/peers/protocol.ts +196 -0
  649. package/src/peers/record.ts +56 -0
  650. package/src/peers/registry.ts +241 -0
  651. package/src/plugin/define.ts +68 -0
  652. package/src/plugin/index.ts +2 -0
  653. package/src/plugin/lifecycle.ts +286 -106
  654. package/src/plugin/resolver.ts +6 -3
  655. package/src/plugin/shell-hook.ts +21 -5
  656. package/src/pricing/catalogue.generated.ts +28 -4
  657. package/src/pricing/rates.source.json +27 -6
  658. package/src/probe/errors.ts +4 -1
  659. package/src/prompt/coding-agent-doctrine.ts +22 -10
  660. package/src/prompt/contributions.ts +12 -2
  661. package/src/prompt/index.ts +1 -0
  662. package/src/provider/collect-chat-completion.ts +96 -11
  663. package/src/provider/mock.ts +24 -6
  664. package/src/provider/registry.ts +4 -1
  665. package/src/provider/tool-call-framing.ts +226 -0
  666. package/src/public-runtime.ts +152 -9
  667. package/src/public-tools.ts +43 -5
  668. package/src/public-types.ts +65 -6
  669. package/src/read-model/registry.ts +7 -2
  670. package/src/registry/ManagedRegistry.ts +57 -6
  671. package/src/registry/collision.ts +64 -0
  672. package/src/registry/command/index.ts +7 -3
  673. package/src/registry/index.ts +3 -9
  674. package/src/registry/plugin/index.ts +14 -1
  675. package/src/registry/tool/callable.ts +36 -0
  676. package/src/registry/tool/execute.ts +16 -839
  677. package/src/registry/tool/portable.ts +59 -0
  678. package/src/registry/tool/presentation.ts +6 -5
  679. package/src/runtime/bidi/session.ts +24 -5
  680. package/src/runtime/query/executor/tool-call-admission.ts +288 -22
  681. package/src/runtime/query/executor.ts +129 -16
  682. package/src/runtime/query/file-evidence-replay.ts +8 -7
  683. package/src/runtime/query/fork/prepare.ts +6 -1
  684. package/src/runtime/query/guardrail-presets.ts +4 -3
  685. package/src/runtime/query/index.ts +199 -101
  686. package/src/runtime/query/iteration/index.ts +13 -3
  687. package/src/runtime/query/iteration/phases/compaction.ts +1 -1
  688. package/src/runtime/query/iteration/phases/context.ts +2 -2
  689. package/src/runtime/query/iteration/phases/tool-review.ts +59 -2
  690. package/src/runtime/query/iteration/stream-turn.ts +390 -136
  691. package/src/runtime/query/iteration/tool-input.ts +284 -0
  692. package/src/runtime/query/observation-context.ts +2 -2
  693. package/src/runtime/query/prelude-lease.ts +132 -0
  694. package/src/runtime/query/prepare-turn.ts +477 -198
  695. package/src/runtime/query/prompt-cache.ts +2 -2
  696. package/src/runtime/query/prompt.ts +4 -4
  697. package/src/runtime/query/resume-session.ts +42 -3
  698. package/src/runtime/query/review-policy.ts +190 -24
  699. package/src/runtime/query/tooling.ts +3 -6
  700. package/src/runtime/query/turn-state.ts +4 -0
  701. package/src/runtime/system-events.ts +246 -0
  702. package/src/scheduler/delegating.ts +7 -2
  703. package/src/skills/index.ts +1 -1
  704. package/src/skills/registry.ts +33 -0
  705. package/src/store/session-log/conformance.ts +51 -8
  706. package/src/store/session-log/core.ts +10 -4
  707. package/src/store/session-log/fold.ts +33 -7
  708. package/src/store/session-log/index.ts +2 -0
  709. package/src/test-support/toolset.ts +23 -0
  710. package/src/tools/builtins/bash.ts +27 -10
  711. package/src/tools/builtins/browser-url.ts +1 -1
  712. package/src/tools/builtins/computer-use-coordinates.ts +144 -0
  713. package/src/tools/builtins/computer-use-image.ts +278 -0
  714. package/src/tools/builtins/computer-use.ts +1495 -191
  715. package/src/tools/builtins/edit.ts +12 -2
  716. package/src/tools/builtins/index.ts +7 -1
  717. package/src/tools/builtins/json-string-hint.ts +16 -0
  718. package/src/tools/builtins/search-tools.ts +7 -20
  719. package/src/tools/builtins/skill.ts +304 -174
  720. package/src/tools/builtins/write-file.ts +12 -0
  721. package/src/tools/command-shell.ts +46 -1
  722. package/src/tools/coordinator/agent.ts +6 -0
  723. package/src/tools/coordinator/ask-user-question.ts +29 -15
  724. package/src/tools/coordinator/index.ts +6 -0
  725. package/src/tools/coordinator/question-options.ts +195 -0
  726. package/src/tools/defineTool.ts +38 -0
  727. package/src/tools/memory/search.ts +4 -1
  728. package/src/tools/memory/update.ts +8 -5
  729. package/src/tools/render-nonce.ts +69 -0
  730. package/src/tools/roster.ts +84 -33
  731. package/src/tools/schedules/present.ts +2 -0
  732. package/src/tools/schedules/schedule-tool.ts +238 -39
  733. package/src/tools/schedules/types.ts +120 -6
  734. package/src/tools/trusted-read-only.ts +19 -10
  735. package/src/tools/untrusted-envelope.ts +121 -57
  736. package/src/toolsets/combine.ts +181 -0
  737. package/src/toolsets/manager.ts +996 -0
  738. package/src/toolsets/source-glob.ts +22 -0
  739. package/src/toolsets/toolset.ts +31 -0
  740. package/src/toolsets/types.ts +154 -0
  741. package/src/toolsets/wrappers.ts +191 -0
  742. package/src/types/agent/base.ts +29 -16
  743. package/src/types/agent/index.ts +1 -0
  744. package/src/types/agent/pipeline.ts +2 -0
  745. package/src/types/agent/query.ts +129 -0
  746. package/src/types/agent/reactive.ts +5 -142
  747. package/src/types/agent/router.ts +2 -0
  748. package/src/types/agent/supervisor.ts +5 -2
  749. package/src/types/authorization/index.ts +33 -0
  750. package/src/types/computer-use/index.ts +202 -0
  751. package/src/types/connector/mcp.ts +32 -0
  752. package/src/types/errors/index.ts +15 -0
  753. package/src/types/hitl/index.ts +57 -0
  754. package/src/types/message/index.ts +135 -7
  755. package/src/types/plugin/index.ts +44 -21
  756. package/src/types/provider/chat.ts +5 -0
  757. package/src/types/provider/config.ts +8 -3
  758. package/src/types/provider/stream.ts +39 -0
  759. package/src/types/sandbox/index.ts +1 -1
  760. package/src/types/session/events.ts +14 -3
  761. package/src/types/tool/index.ts +173 -105
  762. package/src/types/toolset/index.ts +10 -47
  763. package/dist/registry/toolset/catalog.d.ts +0 -42
  764. package/dist/registry/toolset/catalog.d.ts.map +0 -1
  765. package/dist/registry/toolset/catalog.js +0 -234
  766. package/dist/registry/toolset/catalog.js.map +0 -1
  767. package/src/registry/toolset/catalog.ts +0 -308
@@ -1,95 +1,217 @@
1
1
  import { z } from 'zod';
2
+ import { resolveProviderCapabilities } from '../../provider/capabilities.js';
3
+ import { sleep } from '../../utils/backoff.js';
2
4
  import { defineTool } from '../defineTool.js';
5
+ import { neutralizeEnvelopeDelimiter, wrapUntrusted } from '../untrusted-envelope.js';
6
+ import { ScreenshotFrames, assumedDisplay, desktopRectOnImage, pointOnImage, toDisplayPoint, toDisplayRect, toImagePoint, } from './computer-use-coordinates.js';
7
+ import { STANDARD_SCREENSHOT_LIMITS, cropAndFitPng, fitPng, pngSize, } from './computer-use-image.js';
8
+ export { HIGH_RES_SCREENSHOT_LIMITS, STANDARD_SCREENSHOT_LIMITS, screenshotTargetSize, } from './computer-use-image.js';
3
9
  export const COMPUTER_USE_TOOL_NAME = 'computer_use';
10
+ const DEFAULT_SETTLE_MS = 500;
11
+ const DEFAULT_MAX_BATCH_ACTIONS = 20;
12
+ const DEFAULT_MAX_WAIT_MS = 10_000;
13
+ const MAX_LISTED_WINDOWS = 50;
14
+ /** The most of a ui_snapshot the model is shown, in characters (about 4 000 tokens). */
15
+ const MAX_UI_SNAPSHOT_CHARS = 14_000;
16
+ /**
17
+ * Why `provider` cannot drive `computer_use`, or undefined when it can.
18
+ *
19
+ * The tool's only way to show the model the screen is an image in a tool
20
+ * result. A driver that declares `supportsToolResultImages: false` replaces
21
+ * that image with a line of text, so the model acts on a screen it has never
22
+ * seen while every call reports success. Pass the answer to
23
+ * {@link ComputerUseToolOptions.unavailableReason}.
24
+ */
25
+ export function computerUseUnavailableReason(provider) {
26
+ if (resolveProviderCapabilities(provider).supportsToolResultImages)
27
+ return undefined;
28
+ return `The ${provider.id} provider cannot return images in tool results, so the model would never see a screenshot. Use a provider that can (for example Anthropic, Codex or Google) for computer use.`;
29
+ }
4
30
  // ---------------------------------------------------------------------------
5
- // Input schema — discriminated union matching ComputerUseAction
31
+ // Input schema
6
32
  // ---------------------------------------------------------------------------
7
33
  const pointSchema = z.object({
8
34
  x: z.number().int(),
9
35
  y: z.number().int(),
10
36
  });
11
- const mouseButtonSchema = z.enum(['left', 'right', 'middle']);
37
+ const regionSchema = z.object({
38
+ x: z.number().int(),
39
+ y: z.number().int(),
40
+ width: z.number().int().positive(),
41
+ height: z.number().int().positive(),
42
+ });
43
+ // Left when omitted: a model asked to "click the Start button" often leaves
44
+ // the button out, and refusing that cost a whole round trip for nothing.
45
+ const mouseButtonSchema = z.enum(['left', 'right', 'middle']).default('left');
46
+ const screenshotIdSchema = z.string().min(1).optional();
47
+ const cursorPositionSchema = z.object({ type: z.literal('cursor_position') });
48
+ const mouseMoveSchema = z.object({ type: z.literal('mouse_move'), to: pointSchema });
49
+ const mouseClickSchema = z.object({
50
+ type: z.literal('mouse_click'),
51
+ at: pointSchema,
52
+ button: mouseButtonSchema,
53
+ });
54
+ const mouseDragSchema = z.object({
55
+ type: z.literal('mouse_drag'),
56
+ from: pointSchema,
57
+ to: pointSchema,
58
+ button: mouseButtonSchema,
59
+ });
60
+ const scrollSchema = z.object({
61
+ type: z.literal('scroll'),
62
+ at: pointSchema,
63
+ direction: z.enum(['up', 'down', 'left', 'right']),
64
+ amount: z.number().int().positive(),
65
+ });
66
+ const typeTextSchema = z.object({ type: z.literal('type_text'), text: z.string() });
67
+ const keySchema = z.object({ type: z.literal('key'), keys: z.string() });
68
+ const waitSchema = z.object({ type: z.literal('wait'), ms: z.number().int().nonnegative() });
69
+ const listWindowsSchema = z.object({ type: z.literal('list_windows') });
70
+ const focusWindowSchema = z.object({
71
+ type: z.literal('focus_window'),
72
+ window_id: z.string().min(1),
73
+ });
74
+ const UI_ACTIONS = [
75
+ 'invoke',
76
+ 'set_value',
77
+ 'toggle',
78
+ 'select',
79
+ 'expand',
80
+ 'collapse',
81
+ 'focus',
82
+ 'scroll_into_view',
83
+ ];
84
+ const uiSnapshotSchema = z.object({
85
+ type: z.literal('ui_snapshot'),
86
+ window_id: z.string().min(1).optional(),
87
+ });
88
+ const uiActSchema = z.object({
89
+ type: z.literal('ui_act'),
90
+ ref: z.string().min(1),
91
+ action: z.enum(UI_ACTIONS),
92
+ value: z.string().optional(),
93
+ });
94
+ /** What a batch may carry: everything but the image-returning actions and another batch. */
95
+ const batchItemSchema = z.discriminatedUnion('type', [
96
+ cursorPositionSchema,
97
+ mouseMoveSchema,
98
+ mouseClickSchema,
99
+ mouseDragSchema,
100
+ scrollSchema,
101
+ typeTextSchema,
102
+ keySchema,
103
+ waitSchema,
104
+ listWindowsSchema,
105
+ focusWindowSchema,
106
+ uiActSchema,
107
+ ]);
108
+ const withFrame = { screenshot_id: screenshotIdSchema };
12
109
  const actionSchema = z.discriminatedUnion('type', [
13
110
  z.object({ type: z.literal('screenshot') }),
14
- z.object({ type: z.literal('cursor_position') }),
15
- z.object({ type: z.literal('mouse_move'), to: pointSchema }),
16
- z.object({ type: z.literal('mouse_click'), at: pointSchema, button: mouseButtonSchema }),
17
- z.object({
18
- type: z.literal('mouse_drag'),
19
- from: pointSchema,
20
- to: pointSchema,
21
- button: mouseButtonSchema,
22
- }),
111
+ z.object({ type: z.literal('zoom'), region: regionSchema, ...withFrame }),
112
+ cursorPositionSchema.extend(withFrame),
113
+ mouseMoveSchema.extend(withFrame),
114
+ mouseClickSchema.extend(withFrame),
115
+ mouseDragSchema.extend(withFrame),
116
+ scrollSchema.extend(withFrame),
117
+ typeTextSchema.extend(withFrame),
118
+ keySchema.extend(withFrame),
119
+ waitSchema.extend(withFrame),
120
+ listWindowsSchema.extend(withFrame),
121
+ focusWindowSchema.extend(withFrame),
122
+ uiSnapshotSchema,
123
+ uiActSchema.extend(withFrame),
23
124
  z.object({
24
- type: z.literal('scroll'),
25
- at: pointSchema,
26
- direction: z.enum(['up', 'down', 'left', 'right']),
27
- amount: z.number().int().positive(),
125
+ type: z.literal('batch'),
126
+ actions: z.array(batchItemSchema).min(1),
127
+ ...withFrame,
28
128
  }),
29
- z.object({ type: z.literal('type_text'), text: z.string() }),
30
- z.object({ type: z.literal('key'), keys: z.string() }),
31
129
  ]);
32
- /**
33
- * The provider-facing shape is deliberately flat.
34
- *
35
- * The runtime schema above is the authoritative contract: it knows which
36
- * fields each action requires. Rendering that discriminated union produces a
37
- * root `anyOf`, however, and some custom-tool wires reject root combinators
38
- * even when every branch is an object. A model can still see every field and
39
- * every action here; incomplete combinations are rejected by `actionSchema`
40
- * before the host is called, with the recovery hint below.
41
- */
42
- const pointModelInputSchema = {
43
- type: 'object',
44
- properties: {
45
- x: { type: 'integer' },
46
- y: { type: 'integer' },
47
- },
48
- required: ['x', 'y'],
49
- additionalProperties: false,
50
- };
51
- const modelInputSchema = {
52
- type: 'object',
53
- properties: {
54
- type: {
55
- type: 'string',
56
- enum: [
57
- 'screenshot',
58
- 'cursor_position',
59
- 'mouse_move',
60
- 'mouse_click',
61
- 'mouse_drag',
62
- 'scroll',
63
- 'type_text',
64
- 'key',
65
- ],
66
- description: 'Desktop action. screenshot and cursor_position need no other fields; mouse_move needs to; mouse_click needs at and button; mouse_drag needs from, to, and button; scroll needs at, direction, and amount; type_text needs text; key needs keys.',
67
- },
68
- to: pointModelInputSchema,
69
- at: pointModelInputSchema,
70
- from: pointModelInputSchema,
71
- button: { type: 'string', enum: ['left', 'right', 'middle'] },
72
- direction: { type: 'string', enum: ['up', 'down', 'left', 'right'] },
73
- amount: { type: 'integer', description: 'Positive integer scroll distance.' },
74
- text: { type: 'string', description: 'Literal text to type.' },
75
- keys: {
76
- type: 'string',
77
- description: 'Key or key chord to press, for example ENTER or CTRL+R.',
78
- },
79
- },
80
- required: ['type'],
81
- additionalProperties: false,
82
- };
83
- const DESTRUCTIVE_ACTION_TYPES = new Set([
130
+ const HOST_ACTIONS = [
131
+ 'screenshot',
132
+ 'cursor_position',
133
+ 'mouse_move',
84
134
  'mouse_click',
85
135
  'mouse_drag',
136
+ 'scroll',
86
137
  'type_text',
87
138
  'key',
139
+ ];
140
+ const ALL_ACTIONS = [
141
+ 'screenshot',
142
+ 'zoom',
143
+ 'cursor_position',
144
+ 'mouse_move',
145
+ 'mouse_click',
146
+ 'mouse_drag',
88
147
  'scroll',
148
+ 'type_text',
149
+ 'key',
150
+ 'wait',
151
+ 'list_windows',
152
+ 'focus_window',
153
+ 'ui_snapshot',
154
+ 'ui_act',
155
+ 'batch',
156
+ ];
157
+ /** Observations: they change nothing on the desktop. */
158
+ const READ_ONLY_ACTIONS = new Set([
159
+ 'screenshot',
160
+ 'zoom',
161
+ 'cursor_position',
162
+ 'wait',
163
+ 'list_windows',
164
+ 'ui_snapshot',
89
165
  ]);
166
+ const DESTRUCTIVE_ACTIONS = new Set([
167
+ 'mouse_click',
168
+ 'mouse_drag',
169
+ 'type_text',
170
+ 'key',
171
+ 'scroll',
172
+ 'ui_act',
173
+ ]);
174
+ /** Observations that show the model what is on the screen, on their own. */
175
+ const SCREEN_OBSERVATIONS = new Set(['screenshot', 'zoom', 'list_windows', 'ui_snapshot']);
176
+ /**
177
+ * Terminal applications, by the process name a host reports in
178
+ * `WindowInfo.app` (on Windows without `.exe`). Keys are not typed into these.
179
+ */
180
+ const TERMINAL_APPS = /^(WindowsTerminal|OpenConsole|conhost|cmd|powershell|pwsh|wsl|mintty|wezterm(-gui)?|alacritty|Hyper|Tabby|kitty|ConEmu(64)?|putty|Terminal|iTerm2?|gnome-terminal(-server)?|konsole|xterm|xfce4-terminal|tilix|terminator|foot|ghostty|Warp)$/i;
181
+ /** Actions a batch cannot carry: the ones that return an image or a tree, and batch itself. */
182
+ const OUTSIDE_BATCH = new Set(['screenshot', 'zoom', 'ui_snapshot', 'batch']);
183
+ /** A single action's whole result when it only acted: `<label>: done`, then its screenshot. */
184
+ const ACKNOWLEDGEMENT = /^[^\n]*: done(\nScreenshot s\d+ \(\d+x\d+\)\.)?$/;
185
+ function isRecord(value) {
186
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
187
+ }
188
+ function batchActions(input) {
189
+ if (!isRecord(input) || input.type !== 'batch')
190
+ return null;
191
+ return Array.isArray(input.actions) ? input.actions : [];
192
+ }
193
+ /** Read-only when every action is: a batch with one click in it is not. Unknown shapes are not. */
194
+ function isReadOnlyInput(input) {
195
+ const actions = batchActions(input);
196
+ if (actions)
197
+ return (actions.length > 0 &&
198
+ actions.every((item) => isRecord(item) && READ_ONLY_ACTIONS.has(String(item.type))));
199
+ return isRecord(input) && READ_ONLY_ACTIONS.has(String(input.type));
200
+ }
201
+ function isDestructiveInput(input) {
202
+ const actions = batchActions(input);
203
+ if (actions)
204
+ return actions.some((item) => !isRecord(item) || DESTRUCTIVE_ACTIONS.has(String(item.type)));
205
+ return isRecord(input) && DESTRUCTIVE_ACTIONS.has(String(input.type));
206
+ }
207
+ // ---------------------------------------------------------------------------
208
+ // Capabilities
209
+ // ---------------------------------------------------------------------------
90
210
  function requiredCapability(type) {
91
211
  switch (type) {
92
212
  case 'screenshot':
213
+ case 'zoom':
214
+ case 'wait':
93
215
  return 'screenshot';
94
216
  case 'cursor_position':
95
217
  return 'cursorPosition';
@@ -101,13 +223,53 @@ function requiredCapability(type) {
101
223
  case 'type_text':
102
224
  case 'key':
103
225
  return 'keyboard';
226
+ case 'list_windows':
227
+ case 'focus_window':
228
+ return 'windows';
229
+ case 'ui_snapshot':
230
+ case 'ui_act':
231
+ return 'uiTree';
104
232
  default:
105
233
  return null;
106
234
  }
107
235
  }
108
- function buildDescription(host) {
109
- const caps = host.capabilities;
110
- const available = availableActions(caps);
236
+ function hostActionAvailable(caps, action) {
237
+ const required = requiredCapability(action);
238
+ return ((required === null || caps[required] === true) &&
239
+ (caps.supportedActions === undefined || caps.supportedActions.includes(action)) &&
240
+ (action !== 'mouse_click' || caps.mouseClickButtons?.length !== 0) &&
241
+ (action !== 'mouse_drag' || caps.mouseDragButtons?.length !== 0));
242
+ }
243
+ function availableActions(host, caps) {
244
+ const screenshot = hostActionAvailable(caps, 'screenshot');
245
+ const windows = caps.windows === true &&
246
+ typeof host.listWindows === 'function' &&
247
+ typeof host.focusWindow === 'function';
248
+ const uiTree = caps.uiTree === true &&
249
+ typeof host.uiSnapshot === 'function' &&
250
+ typeof host.uiAct === 'function';
251
+ const available = ALL_ACTIONS.filter((action) => {
252
+ switch (action) {
253
+ case 'zoom':
254
+ case 'wait':
255
+ return screenshot;
256
+ case 'list_windows':
257
+ case 'focus_window':
258
+ return windows;
259
+ case 'ui_snapshot':
260
+ case 'ui_act':
261
+ return uiTree;
262
+ case 'batch':
263
+ return false;
264
+ default:
265
+ return hostActionAvailable(caps, action);
266
+ }
267
+ });
268
+ if (available.some((action) => !OUTSIDE_BATCH.has(action)))
269
+ available.push('batch');
270
+ return available;
271
+ }
272
+ function unavailableHostActions(caps) {
111
273
  const unavailable = [];
112
274
  if (!caps.screenshot)
113
275
  unavailable.push('screenshot');
@@ -118,13 +280,21 @@ function buildDescription(host) {
118
280
  if (!caps.keyboard)
119
281
  unavailable.push('keyboard');
120
282
  if (caps.supportedActions) {
121
- for (const action of actionSchema.options.map((option) => option.shape.type.value)) {
122
- if (!available.includes(action))
283
+ for (const action of HOST_ACTIONS) {
284
+ if (!hostActionAvailable(caps, action) && !unavailable.includes(action))
123
285
  unavailable.push(action);
124
286
  }
125
287
  }
288
+ return unavailable;
289
+ }
290
+ // ---------------------------------------------------------------------------
291
+ // Model-facing description and schema
292
+ // ---------------------------------------------------------------------------
293
+ function buildDescription(host, caps, settings) {
294
+ const available = availableActions(host, caps);
295
+ const unavailable = unavailableHostActions(caps);
126
296
  const lines = [
127
- `Controls the user's desktop on a ${caps.displayServer} host. Use to take screenshots and drive mouse/keyboard input for GUI tasks.`,
297
+ `Controls the user's desktop on a ${caps.displayServer} host: screenshots, mouse and keyboard, for GUI tasks.`,
128
298
  `Available actions: ${available.join('; ') || 'none'}.`,
129
299
  ];
130
300
  if (unavailable.length > 0) {
@@ -132,31 +302,79 @@ function buildDescription(host) {
132
302
  ? `Unavailable on this host: ${unavailable.join(', ')} — ${caps.unavailableReason} Do not retry; tell the user.`
133
303
  : `Unavailable on this host: ${unavailable.join(', ')}.`);
134
304
  }
135
- lines.push('Coordinates are in logical pixels from the top-left of the primary display. Call getDisplayGeometry through screenshot output before clicking to confirm bounds.');
305
+ if (!available.includes('screenshot'))
306
+ return finish(lines, caps, available);
307
+ 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. The tool maps your coordinates onto the display. To aim at an earlier screenshot, pass its id as screenshot_id.', 'Take a screenshot before your first click.');
308
+ if (settings.screenshotAfterActions)
309
+ 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.`);
310
+ 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.`);
311
+ if (available.includes('batch'))
312
+ 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'}.`);
313
+ if (caps.displayServer === 'win32' &&
314
+ available.includes('key') &&
315
+ available.includes('type_text'))
316
+ lines.push('To start a Windows program, a shell command (Start-Process notepad, or cmd.exe /c start calc) is surest when you have a shell tool. The Start menu searches by display names in the system language, and ENTER on a name it does not find opens a web search in the browser.');
317
+ if (available.includes('list_windows'))
318
+ lines.push('list_windows names the open windows with their ids; focus_window brings one to the front.');
319
+ if (available.includes('ui_snapshot'))
320
+ 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. 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. Prefer ui_act to clicking pixels when the control is in the tree: it does not depend on coordinates or on which window is in front, and a batch of ui_act steps (for example pressing several buttons) runs in one call. Refs are valid only until the next ui_snapshot; take a new one after the window changes.`);
321
+ lines.push('Typing and keys go to whichever window has focus: confirm on a screenshot that the right window is in front before type_text or key.');
322
+ if (available.includes('list_windows'))
323
+ lines.push('type_text and key are refused while a terminal window is in front — usually the one running this agent, or the user’s own; bring the window you mean to the front first (focus_window, or click it).');
324
+ return finish(lines, caps, available);
325
+ }
326
+ function finish(lines, caps, available) {
136
327
  if (caps.mouseClickButtons && available.includes('mouse_click'))
137
328
  lines.push(`Click buttons: ${caps.mouseClickButtons.join(', ') || 'none'}.`);
138
329
  if (caps.mouseDragButtons && available.includes('mouse_drag'))
139
330
  lines.push(`Drag buttons: ${caps.mouseDragButtons.join(', ') || 'none'}.`);
140
331
  return lines.join(' ');
141
332
  }
142
- function availableActions(caps) {
143
- return actionSchema.options
144
- .map((option) => option.shape.type.value)
145
- .filter((action) => {
146
- const required = requiredCapability(action);
147
- return ((required === null || caps[required] === true) &&
148
- (caps.supportedActions === undefined || caps.supportedActions.includes(action)) &&
149
- (action !== 'mouse_click' || caps.mouseClickButtons?.length !== 0) &&
150
- (action !== 'mouse_drag' || caps.mouseDragButtons?.length !== 0));
151
- });
333
+ /**
334
+ * The provider-facing shape is deliberately flat.
335
+ *
336
+ * The runtime schema above is the authoritative contract: it knows which
337
+ * fields each action requires. Rendering that discriminated union produces a
338
+ * root `anyOf`, however, and some custom-tool wires reject root combinators
339
+ * even when every branch is an object. A model can still see every field and
340
+ * every action here; incomplete combinations are rejected by `actionSchema`
341
+ * before the host is called, with the recovery hint below.
342
+ */
343
+ function pointModelSchema(description) {
344
+ return {
345
+ type: 'object',
346
+ ...(description ? { description } : {}),
347
+ properties: {
348
+ x: { type: 'integer', description: 'Horizontal pixel coordinate, from the left edge.' },
349
+ y: { type: 'integer', description: 'Vertical pixel coordinate, from the top edge.' },
350
+ },
351
+ required: ['x', 'y'],
352
+ additionalProperties: false,
353
+ };
152
354
  }
153
- function hostModelSchema(caps) {
154
- const schema = structuredClone(modelInputSchema);
155
- const actions = availableActions(caps);
355
+ const ACTION_REQUIREMENTS = {
356
+ screenshot: 'screenshot needs no other fields',
357
+ zoom: 'zoom needs region',
358
+ cursor_position: 'cursor_position needs no other fields',
359
+ mouse_move: 'mouse_move needs to',
360
+ mouse_click: 'mouse_click needs at (button defaults to left)',
361
+ mouse_drag: 'mouse_drag needs from and to (button defaults to left)',
362
+ scroll: 'scroll needs at, direction, and amount',
363
+ type_text: 'type_text needs text',
364
+ key: 'key needs keys',
365
+ wait: 'wait needs ms',
366
+ list_windows: 'list_windows needs no other fields',
367
+ focus_window: 'focus_window needs window_id',
368
+ ui_snapshot: 'ui_snapshot takes an optional window_id',
369
+ ui_act: 'ui_act needs ref and action, and value for set_value',
370
+ batch: 'batch needs actions',
371
+ };
372
+ function hostModelSchema(host, caps, settings) {
156
373
  // An unavailable host remains a diagnostic tool. Avoid invalid empty enums
157
374
  // on provider wires; every execution is still refused before host access.
158
- if (actions.length > 0)
159
- schema.properties.type.enum = actions;
375
+ const offered = availableActions(host, caps);
376
+ const actions = offered.length > 0 ? offered : ALL_ACTIONS.filter((a) => a !== 'batch');
377
+ const items = actions.filter((action) => !OUTSIDE_BATCH.has(action));
160
378
  const buttons = new Set();
161
379
  if (actions.includes('mouse_click'))
162
380
  for (const button of caps.mouseClickButtons ?? ['left', 'right', 'middle'])
@@ -164,10 +382,101 @@ function hostModelSchema(caps) {
164
382
  if (actions.includes('mouse_drag'))
165
383
  for (const button of caps.mouseDragButtons ?? ['left', 'right', 'middle'])
166
384
  buttons.add(button);
167
- if (buttons.size > 0)
168
- schema.properties.button.enum = [...buttons];
169
- return schema;
385
+ const buttonEnum = buttons.size > 0 ? [...buttons] : ['left', 'right', 'middle'];
386
+ const fieldSchemas = (forItems) => {
387
+ const present = forItems ? items : actions;
388
+ const fields = {
389
+ to: pointModelSchema('Destination point: where mouse_move moves the cursor to, or where mouse_drag releases.'),
390
+ at: pointModelSchema('Point the action happens at: where to click, or where to scroll.'),
391
+ from: pointModelSchema('Drag start point, for mouse_drag.'),
392
+ button: { type: 'string', enum: buttonEnum, description: 'Mouse button; left when omitted.' },
393
+ direction: {
394
+ type: 'string',
395
+ enum: ['up', 'down', 'left', 'right'],
396
+ description: 'Which way to scroll.',
397
+ },
398
+ amount: { type: 'integer', description: 'Positive integer scroll distance.' },
399
+ text: { type: 'string', description: 'Literal text to type.' },
400
+ keys: {
401
+ type: 'string',
402
+ description: 'Key or key chord to press, for example ENTER or CTRL+R.',
403
+ },
404
+ ms: {
405
+ type: 'integer',
406
+ description: `Milliseconds to wait, 0 to ${settings.maxWaitMs}.`,
407
+ },
408
+ };
409
+ if (present.includes('focus_window') || (!forItems && present.includes('ui_snapshot')))
410
+ fields.window_id = { type: 'string', description: 'A window id from list_windows.' };
411
+ if (present.includes('ui_act')) {
412
+ fields.ref = {
413
+ type: 'string',
414
+ description: 'A ref from the latest ui_snapshot, such as e12.',
415
+ };
416
+ fields.action = {
417
+ type: 'string',
418
+ enum: [...UI_ACTIONS],
419
+ description: 'What ui_act does to the control.',
420
+ };
421
+ fields.value = { type: 'string', description: 'The text set_value puts in the control.' };
422
+ }
423
+ if (!forItems && present.includes('zoom'))
424
+ fields.region = {
425
+ type: 'object',
426
+ description: 'Area of the screenshot to zoom into, in its pixels.',
427
+ properties: {
428
+ x: { type: 'integer', description: 'Left edge of the region, in screenshot pixels.' },
429
+ y: { type: 'integer', description: 'Top edge of the region, in screenshot pixels.' },
430
+ width: { type: 'integer', description: 'Width of the region, in screenshot pixels.' },
431
+ height: { type: 'integer', description: 'Height of the region, in screenshot pixels.' },
432
+ },
433
+ required: ['x', 'y', 'width', 'height'],
434
+ additionalProperties: false,
435
+ };
436
+ return fields;
437
+ };
438
+ const properties = {
439
+ type: {
440
+ type: 'string',
441
+ enum: actions,
442
+ description: `Desktop action. ${actions.map((action) => ACTION_REQUIREMENTS[action]).join('; ')}.`,
443
+ },
444
+ ...fieldSchemas(false),
445
+ };
446
+ if (actions.includes('batch'))
447
+ properties.actions = {
448
+ type: 'array',
449
+ minItems: 1,
450
+ maxItems: settings.maxBatchActions,
451
+ description: `For type batch: up to ${settings.maxBatchActions} actions run in order (no screenshot, zoom, ui_snapshot or batch inside).`,
452
+ items: {
453
+ type: 'object',
454
+ properties: {
455
+ type: {
456
+ type: 'string',
457
+ enum: items,
458
+ description: 'This batched action.',
459
+ },
460
+ ...fieldSchemas(true),
461
+ },
462
+ required: ['type'],
463
+ additionalProperties: false,
464
+ },
465
+ };
466
+ properties.screenshot_id = {
467
+ type: 'string',
468
+ description: 'Optional id of the screenshot your coordinates were read from, such as s3. Defaults to the latest.',
469
+ };
470
+ return {
471
+ type: 'object',
472
+ properties,
473
+ required: ['type'],
474
+ additionalProperties: false,
475
+ };
170
476
  }
477
+ // ---------------------------------------------------------------------------
478
+ // Labels
479
+ // ---------------------------------------------------------------------------
171
480
  function pointLabel(point) {
172
481
  return `(${point.x}, ${point.y})`;
173
482
  }
@@ -176,11 +485,41 @@ function quotedText(value) {
176
485
  const visible = oneLine.length > 64 ? `${oneLine.slice(0, 63)}…` : oneLine;
177
486
  return JSON.stringify(visible);
178
487
  }
179
- /** Human activity text; the raw action union remains the model-facing input. */
180
- function actionLabel(input) {
488
+ function waitLabel(ms) {
489
+ return ms >= 1000 ? `Wait ${Number((ms / 1000).toFixed(1))} s` : `Wait ${ms} ms`;
490
+ }
491
+ /** What a ui_act does, as a verb phrase over the control's description. */
492
+ function uiActLabel(input, describe) {
493
+ const target = describe?.(input.ref) ?? input.ref;
494
+ switch (input.action) {
495
+ case 'invoke':
496
+ return `Press ${target}`;
497
+ case 'set_value':
498
+ return `Set ${target} to ${quotedText(input.value ?? '')}`;
499
+ case 'toggle':
500
+ return `Toggle ${target}`;
501
+ case 'select':
502
+ return `Select ${target}`;
503
+ case 'expand':
504
+ return `Expand ${target}`;
505
+ case 'collapse':
506
+ return `Collapse ${target}`;
507
+ case 'focus':
508
+ return `Focus ${target}`;
509
+ case 'scroll_into_view':
510
+ return `Scroll to ${target}`;
511
+ }
512
+ }
513
+ /**
514
+ * Human activity text for one action; the raw input remains the model-facing
515
+ * record. `describe` names a ui_act ref's control when the tool knows it.
516
+ */
517
+ function itemLabel(input, describe) {
181
518
  switch (input.type) {
182
519
  case 'screenshot':
183
520
  return 'Capture screenshot';
521
+ case 'zoom':
522
+ return `Zoom into ${input.region.width}x${input.region.height} at ${pointLabel(input.region)}`;
184
523
  case 'cursor_position':
185
524
  return 'Read cursor position';
186
525
  case 'mouse_move':
@@ -195,33 +534,49 @@ function actionLabel(input) {
195
534
  return `Type ${quotedText(input.text)}`;
196
535
  case 'key':
197
536
  return `Press ${input.keys}`;
537
+ case 'wait':
538
+ return waitLabel(input.ms);
539
+ case 'list_windows':
540
+ return 'List windows';
541
+ case 'focus_window':
542
+ return `Focus window ${input.window_id}`;
543
+ case 'ui_snapshot':
544
+ return input.window_id
545
+ ? `Read the controls of window ${input.window_id}`
546
+ : 'Read the controls of the front window';
547
+ case 'ui_act':
548
+ return uiActLabel(input, describe);
549
+ case 'batch':
550
+ return batchLabel(input.actions, describe);
198
551
  }
199
552
  }
200
- function resultToToolResult(result) {
201
- switch (result.type) {
202
- case 'screenshot': {
203
- const { data, mimeType, width, height } = result.result;
204
- // `output` used to BE the base64 payload, which meant the model
205
- // received 400 KB–2.7 MB of undecodable characters as text —
206
- // roughly 100k–670k tokens — and could not see the screen at
207
- // all. The image now travels as a content block; `output` keeps
208
- // the short human/transcript-facing description.
209
- return {
210
- success: true,
211
- output: `Screenshot captured (${width}x${height}, ${mimeType}).`,
212
- content: [{ type: 'image', data: data.toString('base64'), mediaType: mimeType }],
213
- data: { mimeType, width, height, encoding: 'base64' },
214
- };
215
- }
216
- case 'cursor_position':
217
- return {
218
- success: true,
219
- output: JSON.stringify(result.point),
220
- data: result.point,
221
- };
222
- case 'ok':
223
- return { success: true, output: 'ok' };
224
- }
553
+ function batchLabel(actions, describe) {
554
+ const parts = actions.map((item) => itemLabel(item, describe));
555
+ const head = `${actions.length} desktop action${actions.length === 1 ? '' : 's'}`;
556
+ const joined = parts.join(' · ');
557
+ return joined.length > 240 ? `${head}: ${joined.slice(0, 239)}…` : `${head}: ${joined}`;
558
+ }
559
+ function resolveSettings(options) {
560
+ const count = (value, fallback, min, name) => {
561
+ if (value === undefined)
562
+ return fallback;
563
+ if (!Number.isSafeInteger(value) || value < min)
564
+ throw new RangeError(`createComputerUseTool: ${name} must be an integer ≥ ${min}`);
565
+ return value;
566
+ };
567
+ const limits = options.screenshotLimits ?? STANDARD_SCREENSHOT_LIMITS;
568
+ if (!Number.isSafeInteger(limits.maxLongEdge) ||
569
+ !Number.isSafeInteger(limits.maxTiles) ||
570
+ limits.maxLongEdge < 28 ||
571
+ limits.maxTiles < 1)
572
+ throw new RangeError('createComputerUseTool: screenshotLimits needs an integer maxLongEdge ≥ 28 and maxTiles ≥ 1');
573
+ return {
574
+ limits,
575
+ settleMs: count(options.settleMs, DEFAULT_SETTLE_MS, 0, 'settleMs'),
576
+ screenshotAfterActions: options.screenshotAfterActions ?? true,
577
+ maxBatchActions: count(options.maxBatchActions, DEFAULT_MAX_BATCH_ACTIONS, 1, 'maxBatchActions'),
578
+ maxWaitMs: count(options.maxWaitMs, DEFAULT_MAX_WAIT_MS, 0, 'maxWaitMs'),
579
+ };
225
580
  }
226
581
  function isOutcomeUnknown(value, action) {
227
582
  if (typeof value !== 'object' || value === null)
@@ -237,30 +592,81 @@ function isOutcomeUnknown(value, action) {
237
592
  typeof candidate.message === 'string' &&
238
593
  candidate.message.length > 0);
239
594
  }
240
- function unknownOutcomeToToolResult(error) {
241
- return {
242
- success: false,
243
- output: '',
244
- error: error.message,
245
- data: {
246
- code: error.code,
247
- action: error.action,
248
- outcome: error.outcome,
249
- retrySafety: error.retrySafety,
250
- timedOut: error.timedOut,
251
- exitCode: error.exitCode,
252
- },
253
- };
595
+ function errorText(error) {
596
+ return error instanceof Error ? error.message : String(error);
597
+ }
598
+ class StepFailure extends Error {
599
+ unknown;
600
+ constructor(message, unknown) {
601
+ super(message);
602
+ this.unknown = unknown;
603
+ }
604
+ }
605
+ /** Whether a call sends the screen to the provider (see `ToolDefinition.capturesScreen`). */
606
+ function capturesScreenInput(input, screenshotAfterActions) {
607
+ const items = batchActions(input) ?? [input];
608
+ return items.some((item) => {
609
+ if (!isRecord(item))
610
+ return true;
611
+ const type = String(item.type);
612
+ if (SCREEN_OBSERVATIONS.has(type))
613
+ return true;
614
+ if (type === 'cursor_position')
615
+ return false;
616
+ // Everything else is followed by a screenshot unless that is switched off.
617
+ return screenshotAfterActions;
618
+ });
619
+ }
620
+ function safeRole(role) {
621
+ return /^[A-Za-z][\w-]{0,39}$/.test(role) ? role : 'Element';
622
+ }
623
+ /** `Button "Beş"`: the control's role and name, one line, cut to fit. */
624
+ function uiElementText(element) {
625
+ const name = element.name.trim();
626
+ return name.length > 0 ? `${safeRole(element.role)} ${quotedText(name)}` : safeRole(element.role);
627
+ }
628
+ /**
629
+ * One line of a ui_snapshot: `[e12] Button "Beş" (disabled) [invoke] @(212, 488)`.
630
+ * The ref and position are the tool's; the rest is the application's, and
631
+ * sits inside the untrusted frame.
632
+ */
633
+ function uiElementLine(element, ref, frame) {
634
+ const parts = [`${ref ? `[${ref}] ` : ''}${uiElementText(element)}`];
635
+ if (element.value !== undefined && element.value !== element.name)
636
+ parts.push(`value=${quotedText(element.value)}`);
637
+ const states = (element.states ?? []).filter((state) => /^[a-z_]{1,24}$/.test(state));
638
+ if (states.length > 0)
639
+ parts.push(`(${states.join(', ')})`);
640
+ if (ref) {
641
+ const actions = (element.actions ?? []).filter((action) => UI_ACTIONS.includes(action));
642
+ if (actions.length > 0)
643
+ parts.push(`[${actions.join(', ')}]`);
644
+ const at = frame && element.bounds ? centreOnImage(frame, element.bounds) : undefined;
645
+ if (at)
646
+ parts.push(`@${pointLabel(at)}`);
647
+ }
648
+ return neutralizeEnvelopeDelimiter(parts.join(' '));
649
+ }
650
+ /** The centre of a virtual-desktop rectangle on a screenshot, or undefined when it is not on its display. */
651
+ function centreOnImage(frame, bounds) {
652
+ const x = Math.floor(bounds.x + bounds.width / 2) - frame.display.x;
653
+ const y = Math.floor(bounds.y + bounds.height / 2) - frame.display.y;
654
+ if (x < 0 || y < 0 || x >= frame.display.width || y >= frame.display.height)
655
+ return undefined;
656
+ return toImagePoint(frame, { x, y });
254
657
  }
255
658
  /**
256
659
  * Factory: given a ComputerUseHost (provided by the consumer — e.g.
257
- * @namzu/computer-use's SubprocessComputerUseHost), returns a ToolDefinition
258
- * that routes the discriminated action to the host and maps results back to
259
- * the SDK's ToolResult shape.
660
+ * @namzu/computer-use's SubprocessComputerUseHost), returns the
661
+ * `computer_use` tool.
260
662
  *
261
- * The tool's description reflects the host's frozen capabilities, and any
262
- * action targeting an unavailable capability is rejected with a clear error
263
- * rather than hanging or failing silently.
663
+ * Every screenshot is fitted to the model's image limits and numbered;
664
+ * every coordinate the model sends is a pixel of one of those screenshots and
665
+ * is mapped onto the host's display. Actions that change something return a
666
+ * fresh screenshot after a short settle delay, and `batch` runs several in
667
+ * one call. The description and schema reflect the host's frozen
668
+ * capabilities, and any action targeting an unavailable capability is
669
+ * rejected before the host is touched.
264
670
  *
265
671
  * @example
266
672
  * ```ts
@@ -272,65 +678,672 @@ function unknownOutcomeToToolResult(error) {
272
678
  * registry.register(createComputerUseTool(host))
273
679
  * ```
274
680
  */
275
- export function createComputerUseTool(host) {
276
- return defineTool({
681
+ export function createComputerUseTool(host, options = {}) {
682
+ const settings = resolveSettings(options);
683
+ const caps = options.unavailableReason
684
+ ? {
685
+ ...host.capabilities,
686
+ screenshot: false,
687
+ mouse: false,
688
+ keyboard: false,
689
+ cursorPosition: false,
690
+ clipboard: false,
691
+ windows: false,
692
+ regionCapture: false,
693
+ uiTree: false,
694
+ unavailableReason: options.unavailableReason,
695
+ }
696
+ : host.capabilities;
697
+ const frames = new ScreenshotFrames();
698
+ const available = new Set(availableActions(host, caps));
699
+ // The controls of the latest ui_snapshot, by the ref the model was shown.
700
+ // Refs count up across snapshots, so a ref from an earlier one is never
701
+ // silently a different control of the latest: it is simply not here.
702
+ let uiRefs = new Map();
703
+ let uiSnapshots = 0;
704
+ let uiRefCount = 0;
705
+ const describeUiRef = (ref) => {
706
+ const entry = uiRefs.get(ref);
707
+ return entry ? `${uiElementText(entry.element)} (${ref})` : undefined;
708
+ };
709
+ const label = (input) => itemLabel(input, describeUiRef);
710
+ const refusal = (type) => {
711
+ const required = requiredCapability(type);
712
+ const why = caps.unavailableReason
713
+ ? ` ${caps.unavailableReason} Do not retry; tell the user.`
714
+ : '';
715
+ if (required !== null && caps[required] !== true)
716
+ return `computer_use: action "${type}" requires capability "${required}" which is not available on this host (displayServer=${caps.displayServer}).${why}`;
717
+ if (!available.has(type))
718
+ return `computer_use: action "${type}" is not supported on this host.${why}`;
719
+ return null;
720
+ };
721
+ /** Capture the display, fit it, and number it. */
722
+ const capture = async () => {
723
+ const result = await host.execute({ type: 'screenshot' });
724
+ if (result.type !== 'screenshot')
725
+ throw new Error(`computer_use: the host answered a screenshot with "${result.type}"`);
726
+ const shot = result.result;
727
+ const image = await fitPng(shot.data, settings.limits);
728
+ const display = shot.display ?? assumedDisplay(image.sourceWidth, image.sourceHeight);
729
+ return { frame: frames.record(image, display), image };
730
+ };
731
+ const frameFor = (id) => {
732
+ if (id !== undefined) {
733
+ const frame = frames.get(id);
734
+ if (!frame)
735
+ throw new StepFailure(`there is no screenshot ${id} (the latest is ${frames.latest()?.id ?? 'none'}); take a screenshot and use its coordinates`);
736
+ return frame;
737
+ }
738
+ const latest = frames.latest();
739
+ if (!latest)
740
+ throw new StepFailure('no screenshot has been taken yet, so there is nothing for coordinates to refer to; take a screenshot first');
741
+ return latest;
742
+ };
743
+ /**
744
+ * Keys go to whichever window has focus, and a model that has not looked
745
+ * does not know which one that is — the terminal running this agent is
746
+ * the usual answer. When the host can show the screen, look first.
747
+ */
748
+ const requireLook = () => {
749
+ if (available.has('screenshot') && !frames.latest())
750
+ throw new StepFailure('no screenshot has been taken yet, so nothing shows which window has focus and would receive the keys; take a screenshot first');
751
+ };
752
+ const mapPoint = (frame, point, field) => {
753
+ if (!pointOnImage(frame, point))
754
+ throw new StepFailure(`${field} ${pointLabel(point)} is outside screenshot ${frame.id}, which is ${frame.imageWidth}x${frame.imageHeight} (x 0–${frame.imageWidth - 1}, y 0–${frame.imageHeight - 1}); coordinates are pixels of the screenshot, not of the screen`);
755
+ return toDisplayPoint(frame, point);
756
+ };
757
+ const runHost = async (action) => {
758
+ try {
759
+ const result = await host.execute(action);
760
+ if (result.type === 'cursor_position') {
761
+ const frame = frames.latest();
762
+ if (!frame)
763
+ return `at display pixel ${pointLabel(result.point)}`;
764
+ return `at ${pointLabel(toImagePoint(frame, result.point))} in ${frame.id}`;
765
+ }
766
+ return 'done';
767
+ }
768
+ catch (error) {
769
+ if (isOutcomeUnknown(error, action.type))
770
+ throw new StepFailure(error.message, error);
771
+ throw new StepFailure(errorText(error));
772
+ }
773
+ };
774
+ const plan = (item, frameId) => {
775
+ const denied = refusal(item.type);
776
+ if (denied)
777
+ throw new StepFailure(denied);
778
+ const mutating = !READ_ONLY_ACTIONS.has(item.type);
779
+ const step = (run) => ({
780
+ item,
781
+ label: label(item),
782
+ mutating,
783
+ run,
784
+ });
785
+ switch (item.type) {
786
+ case 'cursor_position':
787
+ frameFor(frameId);
788
+ return step(() => runHost({ type: 'cursor_position' }));
789
+ case 'mouse_move': {
790
+ const frame = frameFor(frameId);
791
+ const to = mapPoint(frame, item.to, 'to');
792
+ return step(() => runHost({ type: 'mouse_move', to }));
793
+ }
794
+ case 'mouse_click': {
795
+ const buttons = caps.mouseClickButtons;
796
+ if (buttons && !buttons.includes(item.button))
797
+ throw new StepFailure(`computer_use: action "mouse_click" does not support button "${item.button}" on this host.`);
798
+ const frame = frameFor(frameId);
799
+ const at = mapPoint(frame, item.at, 'at');
800
+ return step(() => runHost({ type: 'mouse_click', at, button: item.button }));
801
+ }
802
+ case 'mouse_drag': {
803
+ const buttons = caps.mouseDragButtons;
804
+ if (buttons && !buttons.includes(item.button))
805
+ throw new StepFailure(`computer_use: action "mouse_drag" does not support button "${item.button}" on this host.`);
806
+ const frame = frameFor(frameId);
807
+ const from = mapPoint(frame, item.from, 'from');
808
+ const to = mapPoint(frame, item.to, 'to');
809
+ return step(() => runHost({ type: 'mouse_drag', from, to, button: item.button }));
810
+ }
811
+ case 'scroll': {
812
+ const frame = frameFor(frameId);
813
+ const at = mapPoint(frame, item.at, 'at');
814
+ return step(() => runHost({ type: 'scroll', at, direction: item.direction, amount: item.amount }));
815
+ }
816
+ case 'type_text':
817
+ requireLook();
818
+ return step(() => runHost({ type: 'type_text', text: item.text }));
819
+ case 'key':
820
+ requireLook();
821
+ return step(() => runHost({ type: 'key', keys: item.keys }));
822
+ case 'wait':
823
+ return step(async (signal) => {
824
+ await sleep(item.ms, signal);
825
+ return 'done';
826
+ });
827
+ case 'list_windows':
828
+ return step(() => listWindows());
829
+ case 'focus_window':
830
+ return step(async () => {
831
+ let outcome;
832
+ try {
833
+ outcome = await host.focusWindow(item.window_id);
834
+ }
835
+ catch (error) {
836
+ throw new StepFailure(errorText(error));
837
+ }
838
+ if (!outcome.ok)
839
+ throw new StepFailure(`window ${item.window_id} could not be brought to the front; ${outcome.focusedId ? `window ${outcome.focusedId} is in front` : 'the window in front could not be read'}`);
840
+ return 'done';
841
+ });
842
+ case 'ui_act': {
843
+ const entry = uiRefs.get(item.ref);
844
+ if (!entry)
845
+ throw new StepFailure(uiSnapshots === 0
846
+ ? `there is no ${item.ref}: no ui_snapshot has been taken yet; take one and use its refs`
847
+ : `${item.ref} is not a control of the latest ui_snapshot (u${uiSnapshots}); refs are valid only until the next ui_snapshot, so use the refs it showed`);
848
+ const offered = entry.element.actions;
849
+ if (offered && offered.length > 0 && !offered.includes(item.action))
850
+ throw new StepFailure(`${describeUiRef(item.ref)} offers ${offered.join(', ')}, not ${item.action}`);
851
+ if (item.action === 'set_value' && item.value === undefined)
852
+ throw new StepFailure('set_value needs value, the text to put in the control');
853
+ return step(async () => {
854
+ let outcome;
855
+ try {
856
+ outcome = await host.uiAct(entry.hostRef, item.action, item.value);
857
+ }
858
+ catch (error) {
859
+ throw new StepFailure(errorText(error));
860
+ }
861
+ if (!outcome.ok)
862
+ throw new StepFailure(outcome.detail ?? `${item.action} did not take effect on ${describeUiRef(item.ref)}`);
863
+ return outcome.detail ? `done (${outcome.detail})` : 'done';
864
+ });
865
+ }
866
+ }
867
+ };
868
+ /** Read one window's controls, number the ones the model can act on, and show them. */
869
+ const uiSnapshot = async (input) => {
870
+ let snapshot;
871
+ try {
872
+ snapshot = await host.uiSnapshot(input.window_id);
873
+ }
874
+ catch (error) {
875
+ throw new StepFailure(errorText(error));
876
+ }
877
+ uiSnapshots += 1;
878
+ const id = `u${uiSnapshots}`;
879
+ const refs = new Map();
880
+ const frame = frames.latest();
881
+ const lines = [];
882
+ let chars = 0;
883
+ let shown = 0;
884
+ let total = 0;
885
+ let cut = false;
886
+ const visit = (element, depth) => {
887
+ total += 1;
888
+ const actionable = element.ref.length > 0;
889
+ const children = element.children ?? [];
890
+ // A nameless control nobody can act on says nothing by itself; its
891
+ // children still stand, one level up.
892
+ const silent = !actionable && element.name.trim().length === 0 && element.value === undefined;
893
+ if (!silent && !cut) {
894
+ const ref = actionable ? `e${uiRefCount + 1}` : undefined;
895
+ const line = `${' '.repeat(depth)}${uiElementLine(element, ref, frame)}`;
896
+ if (chars + line.length + 1 > MAX_UI_SNAPSHOT_CHARS) {
897
+ cut = true;
898
+ }
899
+ else {
900
+ lines.push(line);
901
+ chars += line.length + 1;
902
+ shown += 1;
903
+ if (ref) {
904
+ uiRefCount += 1;
905
+ refs.set(ref, { hostRef: element.ref, element });
906
+ }
907
+ }
908
+ }
909
+ for (const child of children)
910
+ visit(child, silent ? depth : depth + 1);
911
+ };
912
+ visit(snapshot.root, 0);
913
+ uiRefs = refs;
914
+ const window = snapshot.windowId && /^[\w.:-]{1,64}$/.test(snapshot.windowId) ? snapshot.windowId : undefined;
915
+ const header = [
916
+ `UI snapshot ${id}${window ? ` of window ${window}` : ''}: ${shown} controls shown, ${refs.size} with a ref you can pass to ui_act. Refs are valid until the next ui_snapshot.`,
917
+ ...(frame
918
+ ? [
919
+ `@(x, y) is a control's centre on screenshot ${frame.id}, for a click when ui_act cannot reach it.`,
920
+ ]
921
+ : []),
922
+ ];
923
+ // The window's title and application, when the tree's own root does not
924
+ // already say them; inside the frame, since an application sets both.
925
+ const about = [
926
+ ...(snapshot.app !== undefined ? [`Application ${quotedText(snapshot.app)}`] : []),
927
+ ...(snapshot.title !== undefined && snapshot.title !== snapshot.root.name
928
+ ? [`Window title ${quotedText(snapshot.title)}`]
929
+ : []),
930
+ ];
931
+ const body = [...about, ...lines].join('\n');
932
+ const footer = cut || snapshot.truncated
933
+ ? [
934
+ cut
935
+ ? `The tree was cut at ${MAX_UI_SNAPSHOT_CHARS} characters after ${shown} of ${total} controls. Read a smaller window, or use a screenshot for the rest.`
936
+ : 'The host stopped reading the tree before it ended; controls further down are missing. Use a screenshot for the rest.',
937
+ ]
938
+ : [];
939
+ const text = [
940
+ ...header,
941
+ wrapUntrusted({
942
+ kind: 'desktop-ui',
943
+ ...(window ? { attributes: { window } } : {}),
944
+ 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.",
945
+ }, body),
946
+ ...footer,
947
+ ].join('\n');
948
+ return {
949
+ success: true,
950
+ output: header[0] ?? '',
951
+ content: [{ type: 'text', text }],
952
+ data: {
953
+ uiSnapshot: {
954
+ id,
955
+ ...(window ? { windowId: window } : {}),
956
+ controls: shown,
957
+ refs: refs.size,
958
+ truncated: cut || snapshot.truncated === true,
959
+ },
960
+ },
961
+ };
962
+ };
963
+ /**
964
+ * Keys and text go to the window in front, and a terminal there — the
965
+ * one running this agent, or the user's own — turns a model's typing into
966
+ * a command line: ENTER runs it or sends it. A session had a WIN+R that
967
+ * did not open the Run dialog type "notepad" and ENTER into the user's
968
+ * terminal, and submitted their half-typed message. So with a window list
969
+ * the tool reads what is in front before typing, and refuses a terminal.
970
+ * Without one it cannot tell, and the description's advice stands alone.
971
+ */
972
+ const refuseTerminalInFront = async () => {
973
+ if (!available.has('list_windows'))
974
+ return;
975
+ let windows;
976
+ try {
977
+ windows = await host.listWindows();
978
+ }
979
+ catch (error) {
980
+ throw new StepFailure(`the window in front could not be read, so nothing was typed: ${errorText(error)}`);
981
+ }
982
+ const front = windows.find((window) => window.focused);
983
+ if (front && TERMINAL_APPS.test(front.app))
984
+ 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`);
985
+ };
986
+ const listWindows = async () => {
987
+ let windows;
988
+ try {
989
+ windows = await host.listWindows();
990
+ }
991
+ catch (error) {
992
+ throw new StepFailure(errorText(error));
993
+ }
994
+ if (windows.length === 0)
995
+ return 'no windows are open';
996
+ const frame = frames.latest();
997
+ const lines = windows.slice(0, MAX_LISTED_WINDOWS).map((window) => {
998
+ const where = frame
999
+ ? (() => {
1000
+ const rect = window.minimized ? null : desktopRectOnImage(frame, window.bounds);
1001
+ return rect
1002
+ ? `at ${pointLabel(rect)} ${rect.width}x${rect.height} in ${frame.id}`
1003
+ : window.minimized
1004
+ ? 'minimized'
1005
+ : `not on the display of ${frame.id}`;
1006
+ })()
1007
+ : window.minimized
1008
+ ? 'minimized'
1009
+ : '';
1010
+ return [
1011
+ `- ${window.id}`,
1012
+ JSON.stringify(window.title),
1013
+ `${window.app} (pid ${window.pid})`,
1014
+ ...(window.focused ? ['focused'] : []),
1015
+ ...(where ? [where] : []),
1016
+ ].join(' · ');
1017
+ });
1018
+ const more = windows.length > MAX_LISTED_WINDOWS
1019
+ ? [`… and ${windows.length - MAX_LISTED_WINDOWS} more`]
1020
+ : [];
1021
+ // Titles are whatever an application puts there — a web page's title in
1022
+ // a browser window — so the list is framed as material, not direction.
1023
+ return `${windows.length} window${windows.length === 1 ? '' : 's'}, front to back:\n${wrapUntrusted({
1024
+ kind: 'desktop-windows',
1025
+ provenance: "The open windows on the user's desktop, as the host listed them. Titles are whatever each application shows, which can include text anyone wrote.",
1026
+ }, [...lines, ...more].join('\n'))}`;
1027
+ };
1028
+ const describeFrame = (frame) => {
1029
+ const { display } = frame;
1030
+ const scaled = frame.imageWidth !== display.width || frame.imageHeight !== display.height;
1031
+ return scaled
1032
+ ? `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.`
1033
+ : `Screenshot ${frame.id}: ${frame.imageWidth}x${frame.imageHeight} pixels, the display at full size. Send coordinates in this image's pixels (x 0–${frame.imageWidth - 1}, y 0–${frame.imageHeight - 1}).`;
1034
+ };
1035
+ const frameData = (frame) => ({
1036
+ id: frame.id,
1037
+ width: frame.imageWidth,
1038
+ height: frame.imageHeight,
1039
+ display: frame.display,
1040
+ mimeType: 'image/png',
1041
+ encoding: 'base64',
1042
+ });
1043
+ const pin = (frame) => [
1044
+ {
1045
+ key: 'computer_use.screenshot',
1046
+ text: `computer_use coordinates are pixels of screenshot ${frame.id} (${frame.imageWidth}x${frame.imageHeight}), origin top-left.`,
1047
+ },
1048
+ ];
1049
+ const imageBlock = (image) => ({
1050
+ type: 'image',
1051
+ data: image.data.toString('base64'),
1052
+ mediaType: 'image/png',
1053
+ });
1054
+ // Said once, beside the first screenshot, where it is read: a model that
1055
+ // has just seen the screen reaches for pixels unless told the host can
1056
+ // name the controls.
1057
+ const firstLookHint = (frame) => frame.id === 's1' && available.has('ui_snapshot')
1058
+ ? [
1059
+ 'This host can also read a window’s controls: list_windows, then ui_snapshot {window_id}, then ui_act by ref (a batch of them for several buttons) — surer than clicking pixels in an ordinary application.',
1060
+ ]
1061
+ : [];
1062
+ const screenshotResult = (shot) => ({
1063
+ success: true,
1064
+ output: `Screenshot ${shot.frame.id} captured (${shot.frame.imageWidth}x${shot.frame.imageHeight} of the ${shot.frame.display.width}x${shot.frame.display.height} display).`,
1065
+ content: [
1066
+ { type: 'text', text: [describeFrame(shot.frame), ...firstLookHint(shot.frame)].join('\n') },
1067
+ imageBlock(shot.image),
1068
+ ],
1069
+ data: { screenshot: frameData(shot.frame) },
1070
+ workingState: pin(shot.frame),
1071
+ });
1072
+ const zoom = async (input) => {
1073
+ const frame = frameFor(input.screenshot_id);
1074
+ const { region } = input;
1075
+ const onImage = {
1076
+ x: Math.max(0, region.x),
1077
+ y: Math.max(0, region.y),
1078
+ width: Math.min(region.x + region.width, frame.imageWidth) - Math.max(0, region.x),
1079
+ height: Math.min(region.y + region.height, frame.imageHeight) - Math.max(0, region.y),
1080
+ };
1081
+ if (onImage.width <= 0 || onImage.height <= 0)
1082
+ throw new StepFailure(`region ${region.width}x${region.height} at ${pointLabel(region)} is outside screenshot ${frame.id} (${frame.imageWidth}x${frame.imageHeight})`);
1083
+ const rect = toDisplayRect(frame, onImage);
1084
+ let fitted;
1085
+ if (caps.regionCapture === true && typeof host.captureRegion === 'function') {
1086
+ const piece = await host.captureRegion(rect);
1087
+ fitted = await fitPng(piece.data, settings.limits);
1088
+ }
1089
+ else {
1090
+ const result = await host.execute({ type: 'screenshot' });
1091
+ if (result.type !== 'screenshot')
1092
+ throw new Error(`computer_use: the host answered a screenshot with "${result.type}"`);
1093
+ const full = result.result;
1094
+ const size = pngSize(full.data);
1095
+ const display = full.display ?? assumedDisplay(size.width, size.height);
1096
+ if (display.width !== frame.display.width || display.height !== frame.display.height)
1097
+ throw new StepFailure(`the display is now ${display.width}x${display.height}, not what ${frame.id} showed; take a new screenshot`);
1098
+ // The capture's own pixels, in case a host captures at another scale than it reports.
1099
+ const sx = size.width / display.width;
1100
+ const sy = size.height / display.height;
1101
+ const left = Math.floor(rect.x * sx);
1102
+ const top = Math.floor(rect.y * sy);
1103
+ fitted = await cropAndFitPng(full.data, {
1104
+ x: left,
1105
+ y: top,
1106
+ width: Math.max(1, Math.min(size.width, Math.ceil((rect.x + rect.width) * sx)) - left),
1107
+ height: Math.max(1, Math.min(size.height, Math.ceil((rect.y + rect.height) * sy)) - top),
1108
+ }, settings.limits);
1109
+ }
1110
+ const detail = fitted.width / onImage.width;
1111
+ 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.`;
1112
+ return {
1113
+ success: true,
1114
+ output: `Zoomed into ${onImage.width}x${onImage.height} at ${pointLabel(onImage)} of ${frame.id} (shown at ${fitted.width}x${fitted.height}).`,
1115
+ content: [{ type: 'text', text }, imageBlock(fitted)],
1116
+ data: {
1117
+ zoom: {
1118
+ screenshot: frame.id,
1119
+ region: onImage,
1120
+ width: fitted.width,
1121
+ height: fitted.height,
1122
+ mimeType: 'image/png',
1123
+ encoding: 'base64',
1124
+ },
1125
+ },
1126
+ };
1127
+ };
1128
+ /** Run actions in order, stop at the first failure, then show the screen once. */
1129
+ const runSteps = async (items, frameId, context, single) => {
1130
+ if (items.length > settings.maxBatchActions)
1131
+ return {
1132
+ success: false,
1133
+ output: '',
1134
+ error: `computer_use: a batch carries at most ${settings.maxBatchActions} actions; got ${items.length}. Nothing was run.`,
1135
+ };
1136
+ // Waits share one budget, so a batch stays well inside the tool's
1137
+ // deadline however its waits are split.
1138
+ const waited = items.reduce((total, item) => total + (item.type === 'wait' ? item.ms : 0), 0);
1139
+ if (waited > settings.maxWaitMs)
1140
+ return {
1141
+ success: false,
1142
+ output: '',
1143
+ error: `computer_use: ${single ? 'wait is' : "a batch's waits add up to"} at most ${settings.maxWaitMs} ms; got ${waited}. Nothing was run.`,
1144
+ };
1145
+ // Plan everything before doing anything: a refusal or a coordinate off
1146
+ // the screenshot in step 5 should not arrive after steps 1–4 changed
1147
+ // the desktop.
1148
+ const planned = [];
1149
+ for (const [index, item] of items.entries()) {
1150
+ try {
1151
+ planned.push(plan(item, frameId));
1152
+ }
1153
+ catch (error) {
1154
+ const message = errorText(error);
1155
+ return {
1156
+ success: false,
1157
+ output: '',
1158
+ error: single
1159
+ ? message
1160
+ : `computer_use: action ${index + 1} of ${items.length} (${label(item)}) cannot run: ${message}. Nothing was run.`,
1161
+ };
1162
+ }
1163
+ }
1164
+ const signal = context?.abortSignal;
1165
+ const records = [];
1166
+ let changed = false;
1167
+ let failure;
1168
+ // Whether the window in front was checked since the last step that could
1169
+ // have changed it. Typing does not move focus; everything else may.
1170
+ let frontChecked = false;
1171
+ for (const [index, step] of planned.entries()) {
1172
+ if (signal?.aborted) {
1173
+ failure = { index, error: 'cancelled before it started' };
1174
+ records.push({ label: step.label, status: 'failed', error: failure.error });
1175
+ break;
1176
+ }
1177
+ try {
1178
+ const keyboard = step.item.type === 'type_text' || step.item.type === 'key';
1179
+ if (keyboard && !frontChecked) {
1180
+ await refuseTerminalInFront();
1181
+ frontChecked = true;
1182
+ }
1183
+ if (step.item.type !== 'type_text')
1184
+ frontChecked = false;
1185
+ const note = await step.run(signal);
1186
+ records.push({ label: step.label, status: 'done', note });
1187
+ if (step.mutating)
1188
+ changed = true;
1189
+ }
1190
+ catch (error) {
1191
+ const unknown = error instanceof StepFailure ? error.unknown : undefined;
1192
+ const message = signal?.aborted ? 'cancelled' : errorText(error);
1193
+ failure = { index, error: message, ...(unknown ? { unknown } : {}) };
1194
+ records.push({
1195
+ label: step.label,
1196
+ status: 'failed',
1197
+ error: message,
1198
+ ...(unknown ? { unknown } : {}),
1199
+ });
1200
+ if (unknown)
1201
+ changed = true;
1202
+ break;
1203
+ }
1204
+ }
1205
+ for (const step of planned.slice(records.length))
1206
+ records.push({ label: step.label, status: 'not run' });
1207
+ // The screen after the batch: after anything that may have changed it,
1208
+ // and after a wait, whose whole point is to look again.
1209
+ const looks = settings.screenshotAfterActions &&
1210
+ available.has('screenshot') &&
1211
+ (changed || planned.some((step) => step.item.type === 'wait')) &&
1212
+ !signal?.aborted;
1213
+ let shot;
1214
+ let shotError;
1215
+ if (looks) {
1216
+ try {
1217
+ await sleep(settings.settleMs, signal);
1218
+ shot = await capture();
1219
+ }
1220
+ catch (error) {
1221
+ shotError = signal?.aborted ? 'cancelled' : errorText(error);
1222
+ }
1223
+ }
1224
+ const summary = (record, index) => {
1225
+ const n = single ? '' : `${index + 1}. `;
1226
+ switch (record.status) {
1227
+ case 'done':
1228
+ return `${n}${record.label}: ${record.note}`;
1229
+ case 'failed':
1230
+ return `${n}${record.label}: failed — ${record.error}`;
1231
+ case 'not run':
1232
+ return `${n}${record.label}: not run`;
1233
+ }
1234
+ };
1235
+ const header = single
1236
+ ? []
1237
+ : failure
1238
+ ? [
1239
+ `Batch stopped at action ${failure.index + 1} of ${planned.length}; ${planned.length - failure.index - 1} not run.`,
1240
+ ]
1241
+ : [`Batch: all ${planned.length} actions done.`];
1242
+ const stepLines = records.map(summary);
1243
+ const shotLines = shot
1244
+ ? [describeFrame(shot.frame)]
1245
+ : shotError
1246
+ ? [`The screenshot after acting failed: ${shotError}. Take one before acting again.`]
1247
+ : [];
1248
+ const unknownLines = failure?.unknown ? [failure.unknown.message] : [];
1249
+ const text = [...header, ...stepLines, ...unknownLines, ...shotLines].join('\n');
1250
+ const output = [
1251
+ ...header,
1252
+ ...stepLines,
1253
+ ...(shot
1254
+ ? [`Screenshot ${shot.frame.id} (${shot.frame.imageWidth}x${shot.frame.imageHeight}).`]
1255
+ : []),
1256
+ ].join('\n');
1257
+ const data = {
1258
+ steps: records.map((record) => record.status === 'failed'
1259
+ ? { label: record.label, status: record.status, error: record.error }
1260
+ : { label: record.label, status: record.status }),
1261
+ ...(shot ? { screenshot: frameData(shot.frame) } : {}),
1262
+ ...(failure?.unknown
1263
+ ? {
1264
+ code: failure.unknown.code,
1265
+ action: failure.unknown.action,
1266
+ outcome: failure.unknown.outcome,
1267
+ retrySafety: failure.unknown.retrySafety,
1268
+ timedOut: failure.unknown.timedOut,
1269
+ exitCode: failure.unknown.exitCode,
1270
+ }
1271
+ : {}),
1272
+ };
1273
+ const content = [{ type: 'text', text }];
1274
+ if (shot)
1275
+ content.push(imageBlock(shot.image));
1276
+ const result = {
1277
+ success: failure === undefined,
1278
+ output,
1279
+ content,
1280
+ data,
1281
+ ...(shot ? { workingState: pin(shot.frame) } : {}),
1282
+ };
1283
+ if (failure)
1284
+ result.error = failure.unknown
1285
+ ? failure.unknown.message
1286
+ : single
1287
+ ? `computer_use failed: ${failure.error}`
1288
+ : `Batch stopped at action ${failure.index + 1} of ${planned.length} (${planned[failure.index]?.label}): ${failure.error}`;
1289
+ return result;
1290
+ };
1291
+ // Whether a call sends the screen to the provider: an observation, or an
1292
+ // action that returns a screenshot afterwards. A diagnostic tool that can
1293
+ // reach nothing captures nothing.
1294
+ const observes = available.has('screenshot') || available.has('list_windows') || available.has('ui_snapshot');
1295
+ const capturesScreen = (input) => observes && capturesScreenInput(input, settings.screenshotAfterActions);
1296
+ const tool = defineTool({
277
1297
  name: COMPUTER_USE_TOOL_NAME,
278
- description: buildDescription(host),
1298
+ description: buildDescription(host, caps, settings),
279
1299
  inputSchema: actionSchema,
280
- modelInputSchema: hostModelSchema(host.capabilities),
281
- validationErrorHint: 'Action requirements: mouse_move needs "to"; mouse_click needs "at" and "button"; mouse_drag needs "from", "to", and "button"; scroll needs "at", "direction", and positive "amount"; type_text needs "text"; key needs "keys".',
1300
+ modelInputSchema: hostModelSchema(host, caps, settings),
1301
+ validationErrorHint: `Action requirements: ${ALL_ACTIONS.map((action) => ACTION_REQUIREMENTS[action]).join('; ')}. A batch is {"type":"batch","actions":[...]} with at most ${settings.maxBatchActions} actions and no screenshot, zoom, ui_snapshot or batch inside.`,
282
1302
  category: 'custom',
283
1303
  permissions: [],
284
- readOnly: false,
285
- destructive: (input) => DESTRUCTIVE_ACTION_TYPES.has(input.type),
1304
+ readOnly: (input) => isReadOnlyInput(input),
1305
+ destructive: (input) => isDestructiveInput(input),
1306
+ capturesScreen,
286
1307
  concurrencySafe: false,
287
1308
  presentCall: (input) => ({
288
1309
  kind: 'generic',
289
- label: actionLabel(input),
1310
+ label: label(input),
290
1311
  presentation: 'activity',
291
1312
  }),
292
- presentResult: (_input, result) => result.success && result.output.trim().toLowerCase() === 'ok'
1313
+ // Decided from the result alone: a host may present a finished call
1314
+ // without its input (the CLI passes `{}`). An action that only reports
1315
+ // "done" — and the screenshot that followed it, which is for the model —
1316
+ // adds nothing to the call row; observations, batches and failures do.
1317
+ presentResult: (_input, result) => result.success && ACKNOWLEDGEMENT.test(result.output)
293
1318
  ? { kind: 'generic', label: result.output, visibility: 'hidden' }
294
1319
  : undefined,
295
- async execute(input, _context) {
296
- const required = requiredCapability(input.type);
297
- if (required !== null && host.capabilities[required] !== true) {
298
- return {
299
- success: false,
300
- output: '',
301
- error: `computer_use: action "${input.type}" requires capability "${required}" which is not available on this host (displayServer=${host.capabilities.displayServer}).${host.capabilities.unavailableReason ? ` ${host.capabilities.unavailableReason} Do not retry; tell the user.` : ''}`,
302
- };
303
- }
304
- if (!availableActions(host.capabilities).includes(input.type)) {
305
- return {
306
- success: false,
307
- output: '',
308
- error: `computer_use: action "${input.type}" is not supported on this host.`,
309
- };
310
- }
311
- const buttons = input.type === 'mouse_click'
312
- ? host.capabilities.mouseClickButtons
313
- : input.type === 'mouse_drag'
314
- ? host.capabilities.mouseDragButtons
315
- : undefined;
316
- if (buttons && 'button' in input && !buttons.includes(input.button)) {
317
- return {
318
- success: false,
319
- output: '',
320
- error: `computer_use: action "${input.type}" does not support button "${input.button}" on this host.`,
321
- };
322
- }
1320
+ async execute(input, context) {
1321
+ const denied = refusal(input.type);
1322
+ if (denied)
1323
+ return { success: false, output: '', error: denied };
323
1324
  try {
324
- const result = await host.execute(input);
325
- return resultToToolResult(result);
1325
+ switch (input.type) {
1326
+ case 'screenshot':
1327
+ return screenshotResult(await capture());
1328
+ case 'zoom':
1329
+ return await zoom(input);
1330
+ case 'ui_snapshot':
1331
+ return await uiSnapshot(input);
1332
+ case 'batch':
1333
+ return await runSteps(input.actions, input.screenshot_id, context, false);
1334
+ default: {
1335
+ const { screenshot_id: frameId, ...item } = input;
1336
+ return await runSteps([item], frameId, context, true);
1337
+ }
1338
+ }
326
1339
  }
327
1340
  catch (error) {
328
- if (isOutcomeUnknown(error, input.type)) {
329
- return unknownOutcomeToToolResult(error);
330
- }
1341
+ if (error instanceof StepFailure)
1342
+ return { success: false, output: '', error: `computer_use failed: ${error.message}` };
331
1343
  throw error;
332
1344
  }
333
1345
  },
334
1346
  });
1347
+ return Object.assign(tool, { describeUiRef });
335
1348
  }
336
1349
  //# sourceMappingURL=computer-use.js.map