farming-code 2.2.29 → 2.2.32

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 (385) hide show
  1. package/README.md +25 -66
  2. package/README.zh_cn.md +15 -66
  3. package/THIRD_PARTY_NOTICES.md +7 -0
  4. package/backend/acp/{client-services.js → client-services.cjs} +132 -134
  5. package/backend/acp/packaged-claude-acp.cjs +37 -0
  6. package/backend/acp/packaged-codex-acp.cjs +37 -0
  7. package/backend/acp/patch-decisions.cjs +182 -0
  8. package/backend/acp/permission-security.cjs +131 -0
  9. package/backend/{acp-checkpoint-store.js → acp-checkpoint-store.cjs} +90 -59
  10. package/backend/{acp-runtime.js → acp-runtime.cjs} +1219 -1125
  11. package/backend/acp-session-state.cjs +622 -0
  12. package/backend/acp-transcript.cjs +525 -0
  13. package/backend/agent-env.cjs +257 -0
  14. package/backend/agent-extension-discovery.cjs +452 -0
  15. package/backend/agent-extension-inventory.cjs +116 -0
  16. package/backend/agent-json-stream.cjs +283 -0
  17. package/backend/agent-lifecycle-journal.cjs +185 -0
  18. package/backend/{agent-manager.js → agent-manager.cjs} +3116 -4275
  19. package/backend/agent-order-transaction.cjs +85 -0
  20. package/backend/agent-order.cjs +159 -0
  21. package/backend/agent-provider-session.cjs +98 -0
  22. package/backend/agent-runtime-binding.cjs +179 -0
  23. package/backend/agent-session-history.cjs +1022 -0
  24. package/backend/agent-session-inventory.cjs +291 -0
  25. package/backend/async-cache.cjs +104 -0
  26. package/backend/atomic-json-store.cjs +67 -0
  27. package/backend/auth.cjs +261 -0
  28. package/backend/authoritative-inventory-cache.cjs +383 -0
  29. package/backend/business-health.cjs +68 -0
  30. package/backend/chat-runtime.cjs +50 -0
  31. package/backend/claude-settings.cjs +132 -0
  32. package/backend/cli-agents.cjs +435 -0
  33. package/backend/codex-context-window.cjs +196 -0
  34. package/backend/codex-models.cjs +228 -0
  35. package/backend/codex-session-archive.cjs +82 -0
  36. package/backend/codex-session-history.cjs +590 -0
  37. package/backend/{codex-terminal-profile.js → codex-terminal-profile.cjs} +149 -155
  38. package/backend/codex-transcript-sanitizer.cjs +130 -0
  39. package/backend/codex-transcript.cjs +2107 -0
  40. package/backend/command-runner-child.cjs +105 -0
  41. package/backend/config-manager.cjs +1263 -0
  42. package/backend/control-api.cjs +439 -0
  43. package/backend/data/LICENSE.cua +21 -0
  44. package/backend/executable-discovery.cjs +204 -0
  45. package/backend/farming-agent-bootstrap.cjs +81 -0
  46. package/backend/farming-agent-bootstrap.zh_cn.md +6 -2
  47. package/backend/{farming-app-cli.js → farming-app-cli.cjs} +441 -493
  48. package/backend/farming-cli.cjs +414 -0
  49. package/backend/farming-net-pass.cjs +319 -0
  50. package/backend/farming-net-registry.cjs +123 -0
  51. package/backend/farming-net-server.cjs +309 -0
  52. package/backend/farming-session-store.cjs +651 -0
  53. package/backend/git-worktree-info.cjs +181 -0
  54. package/backend/haiku-token.cjs +828 -0
  55. package/backend/index-html.cjs +96 -0
  56. package/backend/input-parts.cjs +68 -0
  57. package/backend/input-routing.cjs +40 -0
  58. package/backend/{local-session-engine.js → local-session-engine.cjs} +276 -282
  59. package/backend/main-agent-skills.cjs +309 -0
  60. package/backend/main-page-session.cjs +132 -0
  61. package/backend/native-pty-controller-generation.cjs +139 -0
  62. package/backend/{native-pty-host-client.js → native-pty-host-client.cjs} +338 -346
  63. package/backend/native-pty-host-identity.cjs +125 -0
  64. package/backend/native-pty-host-path.cjs +68 -0
  65. package/backend/{native-pty-host.js → native-pty-host.cjs} +480 -569
  66. package/backend/native-session-engine.cjs +296 -0
  67. package/backend/network.cjs +57 -0
  68. package/backend/npm-update-helper.cjs +399 -0
  69. package/backend/packaged-node-pty.cjs +120 -0
  70. package/backend/preview-session-manager.cjs +89 -0
  71. package/backend/provider-adapters.cjs +492 -0
  72. package/backend/provider-home-configuration.cjs +211 -0
  73. package/backend/provider-session-id.cjs +79 -0
  74. package/backend/provider-session-service.cjs +333 -0
  75. package/backend/qr-share-tickets.cjs +119 -0
  76. package/backend/resource-broadcast-protocol.cjs +50 -0
  77. package/backend/review-diff-router.cjs +202 -0
  78. package/backend/review-diff-service.cjs +1267 -0
  79. package/backend/review-session-router.cjs +93 -0
  80. package/backend/review-session-service.cjs +470 -0
  81. package/backend/review-session-store.cjs +161 -0
  82. package/backend/review-state-router.cjs +132 -0
  83. package/backend/review-state-store.cjs +299 -0
  84. package/backend/run-history-store.cjs +97 -0
  85. package/backend/runtime-dependency-manager.cjs +893 -0
  86. package/backend/runtime-executable-invocation.cjs +37 -0
  87. package/backend/runtime-observation.cjs +96 -0
  88. package/backend/server-process-identity.cjs +70 -0
  89. package/backend/server.cjs +3356 -0
  90. package/backend/session-engine-bridge.cjs +144 -0
  91. package/backend/session-engine-router.cjs +105 -0
  92. package/backend/session-engine.cjs +64 -0
  93. package/backend/session-stream-protocol.cjs +181 -0
  94. package/backend/shell-busy-integration.cjs +442 -0
  95. package/backend/slash-command-discovery.cjs +423 -0
  96. package/backend/storage-layout.cjs +263 -0
  97. package/backend/system-monitor.cjs +96 -0
  98. package/backend/terminal-attach-checkpoint.cjs +73 -0
  99. package/backend/terminal-exit-quiescence.cjs +57 -0
  100. package/backend/{terminal-reducer-flow-control.js → terminal-reducer-flow-control.cjs} +45 -22
  101. package/backend/terminal-runtime-cleanup.cjs +99 -0
  102. package/backend/{terminal-screen-state.js → terminal-screen-state.cjs} +100 -108
  103. package/backend/{terminal-screen-worker-pool.js → terminal-screen-worker-pool.cjs} +89 -79
  104. package/backend/{terminal-screen-worker-thread.js → terminal-screen-worker-thread.cjs} +64 -65
  105. package/backend/terminal-screen-worker.cjs +352 -0
  106. package/backend/terminal-state-serialization.cjs +147 -0
  107. package/backend/{terminal-status.js → terminal-status.cjs} +137 -187
  108. package/backend/theme-manager.cjs +185 -0
  109. package/backend/update-service.cjs +675 -0
  110. package/backend/usage-forecast.cjs +95 -0
  111. package/backend/{usage-history-client.js → usage-history-client.cjs} +144 -94
  112. package/backend/usage-history-smoke.cjs +85 -0
  113. package/backend/usage-history-worker.cjs +60 -0
  114. package/backend/{usage-monitor.js → usage-monitor.cjs} +363 -390
  115. package/backend/workspace-directory.cjs +239 -0
  116. package/backend/workspace-discovery.cjs +271 -0
  117. package/backend/{workspace-file-router.js → workspace-file-router.cjs} +213 -282
  118. package/backend/{workspace-file-service.js → workspace-file-service.cjs} +1139 -1318
  119. package/backend/workspace-root-registry.cjs +192 -0
  120. package/bin/farming +1 -1
  121. package/config/farming.deploy.env.example +1 -1
  122. package/config/farming.install.env.example +1 -1
  123. package/dist/acp/codex-acp-1.1.4.mjs +405 -8
  124. package/dist/assets/App-BCkdpWB6.css +1 -0
  125. package/dist/assets/App-CRjKpaGp.js +697 -0
  126. package/dist/assets/CodeSelect-Ci8sKZPU.js +1 -0
  127. package/dist/assets/CodeSelect-T2eNzrOc.css +1 -0
  128. package/dist/assets/{FileEditorMarkdownPreview-Cs9cLv8a.js → FileEditorMarkdownPreview-V06QHlAg.js} +55 -55
  129. package/dist/assets/FileEditorPane-BX-Wjg9U.js +2 -0
  130. package/dist/assets/IconGlyphs-YhV7tqd4.js +1 -0
  131. package/dist/assets/ProjectFilesSection-BDT2_r0o.js +12 -0
  132. package/dist/assets/ReviewPage-BqAs5sG1.js +3 -0
  133. package/dist/assets/code-dark-B7eM_9G9.css +1 -0
  134. package/dist/assets/{cssMode-Bdg5RpcJ.js → cssMode-ADdAlxTO.js} +1 -1
  135. package/dist/assets/{editor.api2-D74ufkbr.js → editor.api2-BFLAr0YF.js} +162 -162
  136. package/dist/assets/file-icons-BpeqWkIB.js +1 -0
  137. package/dist/assets/{freemarker2-DfMDJfnE.js → freemarker2-C90q5jrp.js} +1 -1
  138. package/dist/assets/{handlebars-BEdPtzMT.js → handlebars-BwUQcEDq.js} +1 -1
  139. package/dist/assets/{html-B1fPb1QD.js → html-1s3uPKfh.js} +1 -1
  140. package/dist/assets/{htmlMode-CY2ZjHxH.js → htmlMode-xtKD99de.js} +1 -1
  141. package/dist/assets/{index-CQNaZc3l.js → index-C8MchCem.js} +3 -3
  142. package/dist/assets/{javascript-BV2OsWA0.js → javascript-Ph7ijyny.js} +1 -1
  143. package/dist/assets/{jsonMode-zd07aeuX.js → jsonMode-D-jGAnFH.js} +1 -1
  144. package/dist/assets/linkComputer-CbGyI_qx.js +1 -0
  145. package/dist/assets/{liquid-BParI24X.js → liquid-0IamE_cI.js} +1 -1
  146. package/dist/assets/{lspLanguageFeatures-BzredkoV.js → lspLanguageFeatures-BxnQunWF.js} +1 -1
  147. package/dist/assets/main-CLKXa6hf.css +1 -0
  148. package/dist/assets/{mdx-vGzUJN98.js → mdx-DdNmfivn.js} +1 -1
  149. package/dist/assets/{monaco.contribution-BmaeBQEc.js → monaco.contribution-B43jsUs1.js} +2 -2
  150. package/dist/assets/{python-CUwdLgsI.js → python-IAt4X5TS.js} +1 -1
  151. package/dist/assets/{razor-BScebUxU.js → razor-DRkFYW0S.js} +1 -1
  152. package/dist/assets/review-C8-oPKXk.css +1 -0
  153. package/dist/assets/{tsMode-DzUAibXK.js → tsMode-_d_4U2gf.js} +1 -1
  154. package/dist/assets/{typescript-D9EOeM7N.js → typescript-C7zcMq9l.js} +1 -1
  155. package/dist/assets/{workers-DAiomYZM.js → workers-D0nOyJzf.js} +1 -1
  156. package/dist/assets/workspace-editor-model-DND_Y-Bj.js +1 -0
  157. package/dist/assets/workspace-editor-monaco-BPWhgcIB.js +4 -0
  158. package/dist/assets/workspace-editor-monaco-N641qPjX.js +1 -0
  159. package/dist/assets/workspace-view-state-k1bTlJ_Z.js +13 -0
  160. package/dist/assets/{xml-wWl1dhkQ.js → xml-BR-HvxT8.js} +1 -1
  161. package/dist/assets/{yaml-Dc2WDaOZ.js → yaml-YtFQwh4q.js} +1 -1
  162. package/dist/index.html +2 -1
  163. package/extensions/browser/backend/agent-browser-runtime.cjs +1040 -0
  164. package/extensions/browser/backend/agent-capability.cjs +85 -0
  165. package/extensions/browser/backend/browser-mcp-server.cjs +655 -0
  166. package/extensions/browser/backend/browser-resource-manager.cjs +1486 -0
  167. package/extensions/browser/backend/browser-resource-store.cjs +228 -0
  168. package/extensions/browser/backend/browser-router.cjs +203 -0
  169. package/extensions/browser/backend/executable-discovery.cjs +248 -0
  170. package/extensions/browser/backend/farming-browser-client.cjs +116 -0
  171. package/extensions/browser/backend/index.cjs +32 -0
  172. package/extensions/browser/backend/managed-chromium-installer.cjs +833 -0
  173. package/extensions/browser/bin/farming-browser +16 -7
  174. package/extensions/computer/backend/agent-capability.cjs +72 -0
  175. package/extensions/computer/backend/computer-constants.cjs +59 -0
  176. package/extensions/computer/backend/computer-mcp-server.cjs +182 -0
  177. package/extensions/computer/backend/computer-resource-manager.cjs +1219 -0
  178. package/extensions/computer/backend/computer-resource-store.cjs +190 -0
  179. package/extensions/computer/backend/computer-router.cjs +257 -0
  180. package/extensions/computer/backend/cua-tools.json +3067 -0
  181. package/extensions/computer/backend/farming-computer-client.cjs +84 -0
  182. package/extensions/computer/backend/index.cjs +35 -0
  183. package/extensions/computer/backend/isolated-browser-provider.cjs +157 -0
  184. package/extensions/computer/bin/farming-computer +131 -0
  185. package/frontend/farming-net/app.js +255 -262
  186. package/frontend/ghostty-loader.js +24 -20
  187. package/frontend/reading-anchor.js +210 -193
  188. package/frontend/runtime-paths.js +24 -26
  189. package/frontend/session-bridge.js +90 -111
  190. package/frontend/session-modal-bridge.js +184 -302
  191. package/frontend/skin-bridge.js +20 -23
  192. package/frontend/skins/crt/app.js +7686 -7901
  193. package/frontend/skins/crt/effects.js +7 -6
  194. package/frontend/skins/crt/index.html +6 -6
  195. package/frontend/skins/crt/styles/markdown.css +4 -4
  196. package/frontend/terminal-bridge.js +174 -181
  197. package/frontend/terminal-replay.js +320 -345
  198. package/frontend/theme-loader.js +55 -71
  199. package/index.html +1 -0
  200. package/package.json +64 -37
  201. package/shared/backend-connection-status.js +38 -69
  202. package/shared/browser-protocol.js +235 -110
  203. package/shared/websocket-liveness.js +40 -0
  204. package/backend/acp/packaged-claude-acp.js +0 -13
  205. package/backend/acp/packaged-codex-acp.js +0 -13
  206. package/backend/acp/patch-decisions.js +0 -153
  207. package/backend/acp/permission-security.js +0 -108
  208. package/backend/acp-session-state.js +0 -644
  209. package/backend/acp-transcript.js +0 -512
  210. package/backend/agent-env.js +0 -250
  211. package/backend/agent-json-stream.js +0 -268
  212. package/backend/agent-lifecycle-journal.js +0 -133
  213. package/backend/agent-memory-report.js +0 -583
  214. package/backend/agent-order.js +0 -166
  215. package/backend/agent-provider-session.js +0 -76
  216. package/backend/agent-runtime-binding.js +0 -174
  217. package/backend/agent-session-history.js +0 -953
  218. package/backend/async-cache.js +0 -94
  219. package/backend/atomic-json-store.js +0 -37
  220. package/backend/auth.js +0 -251
  221. package/backend/bundle-update-helper.js +0 -113
  222. package/backend/chat-runtime.js +0 -28
  223. package/backend/claude-settings.js +0 -121
  224. package/backend/cli-agents.js +0 -486
  225. package/backend/codex-context-window.js +0 -189
  226. package/backend/codex-models.js +0 -226
  227. package/backend/codex-rollout-follower.js +0 -326
  228. package/backend/codex-session-archive.js +0 -65
  229. package/backend/codex-session-history.js +0 -647
  230. package/backend/codex-transcript-sanitizer.js +0 -115
  231. package/backend/codex-transcript.js +0 -2564
  232. package/backend/command-runner-child.js +0 -67
  233. package/backend/config-manager.js +0 -1133
  234. package/backend/control-api.js +0 -455
  235. package/backend/executable-discovery.js +0 -216
  236. package/backend/farming-agent-bootstrap.js +0 -49
  237. package/backend/farming-cli.js +0 -457
  238. package/backend/farming-net-pass.js +0 -285
  239. package/backend/farming-net-registry.js +0 -112
  240. package/backend/farming-net-server.js +0 -298
  241. package/backend/farming-session-store.js +0 -677
  242. package/backend/git-worktree-info.js +0 -181
  243. package/backend/haiku-token.js +0 -772
  244. package/backend/index-html.js +0 -62
  245. package/backend/input-parts.js +0 -54
  246. package/backend/input-routing.js +0 -24
  247. package/backend/json-cli-runtime.js +0 -275
  248. package/backend/main-agent-skills.js +0 -305
  249. package/backend/main-page-session.js +0 -122
  250. package/backend/native-pty-controller-generation.js +0 -106
  251. package/backend/native-pty-host-identity.js +0 -86
  252. package/backend/native-pty-host-path.js +0 -42
  253. package/backend/native-session-engine.js +0 -268
  254. package/backend/network.js +0 -23
  255. package/backend/npm-update-helper.js +0 -374
  256. package/backend/packaged-node-pty.js +0 -99
  257. package/backend/preview-session-manager.js +0 -68
  258. package/backend/provider-adapters.js +0 -399
  259. package/backend/provider-session-id.js +0 -47
  260. package/backend/provider-session-service.js +0 -345
  261. package/backend/qr-share-tickets.js +0 -100
  262. package/backend/review-diff-router.js +0 -180
  263. package/backend/review-diff-service.js +0 -1270
  264. package/backend/review-session-router.js +0 -74
  265. package/backend/review-session-service.js +0 -446
  266. package/backend/review-session-store.js +0 -151
  267. package/backend/review-state-router.js +0 -116
  268. package/backend/review-state-store.js +0 -286
  269. package/backend/run-history-store.js +0 -67
  270. package/backend/runtime-dependency-manager.js +0 -759
  271. package/backend/runtime-executable-invocation.js +0 -20
  272. package/backend/runtime-observation.js +0 -81
  273. package/backend/server-process-identity.js +0 -47
  274. package/backend/server.js +0 -3267
  275. package/backend/session-engine-bridge.js +0 -129
  276. package/backend/session-engine-router.js +0 -66
  277. package/backend/session-engine.js +0 -39
  278. package/backend/session-stream-protocol.js +0 -185
  279. package/backend/shell-busy-integration.js +0 -472
  280. package/backend/slash-command-discovery.js +0 -433
  281. package/backend/storage-layout.js +0 -190
  282. package/backend/system-monitor.js +0 -77
  283. package/backend/terminal-attach-checkpoint.js +0 -74
  284. package/backend/terminal-exit-quiescence.js +0 -39
  285. package/backend/terminal-runtime-cleanup.js +0 -80
  286. package/backend/terminal-screen-worker.js +0 -337
  287. package/backend/terminal-state-serialization.js +0 -127
  288. package/backend/theme-manager.js +0 -163
  289. package/backend/update-service.js +0 -1545
  290. package/backend/usage-forecast.js +0 -86
  291. package/backend/usage-history-scanner.ts +0 -2718
  292. package/backend/usage-history-smoke.js +0 -64
  293. package/backend/usage-history-worker.js +0 -34
  294. package/backend/workspace-directory.js +0 -232
  295. package/backend/workspace-discovery.js +0 -311
  296. package/backend/workspace-root-registry.js +0 -166
  297. package/dist/assets/App-BKNUILuL.css +0 -1
  298. package/dist/assets/App-Ex2oVVXO.js +0 -693
  299. package/dist/assets/FileEditorPane-CNtuGjQ3.js +0 -2
  300. package/dist/assets/IconGlyphs-BClgag6E.js +0 -1
  301. package/dist/assets/ProjectFilesSection-Cf2BEcAN.js +0 -12
  302. package/dist/assets/ReviewPage-BRuxFaH5.js +0 -3
  303. package/dist/assets/code-dark-BEZTQwYZ.css +0 -1
  304. package/dist/assets/file-icons-BOlcJ0ZF.js +0 -1
  305. package/dist/assets/main-DK9Sy7-c.css +0 -1
  306. package/dist/assets/review-BcnwQtJv.css +0 -1
  307. package/dist/assets/workspace-editor-model-CSGCl21x.js +0 -1
  308. package/dist/assets/workspace-editor-monaco-CJNwbpCy.js +0 -4
  309. package/dist/assets/workspace-editor-monaco-CO9w8YV0.js +0 -1
  310. package/dist/assets/workspace-view-state-BjKPYp0E.js +0 -7
  311. package/extensions/browser/backend/agent-browser-runtime.js +0 -1041
  312. package/extensions/browser/backend/agent-capability.js +0 -55
  313. package/extensions/browser/backend/browser-mcp-server.js +0 -621
  314. package/extensions/browser/backend/browser-resource-manager.js +0 -1309
  315. package/extensions/browser/backend/browser-resource-store.js +0 -190
  316. package/extensions/browser/backend/browser-router.js +0 -133
  317. package/extensions/browser/backend/executable-discovery.js +0 -224
  318. package/extensions/browser/backend/farming-browser-client.js +0 -83
  319. package/extensions/browser/backend/index.js +0 -7
  320. package/extensions/browser/frontend/BrowserSidebarPortals.tsx +0 -360
  321. package/extensions/browser/frontend/BrowserViewer.tsx +0 -500
  322. package/extensions/browser/frontend/browser-resource-state.ts +0 -60
  323. package/extensions/browser/frontend/browser.css +0 -567
  324. package/extensions/browser/frontend/types.ts +0 -31
  325. package/extensions/browser/frontend/useBrowserResources.ts +0 -158
  326. package/frontend/vendor/ghostty-web/index.d.ts +0 -1842
  327. package/shared/backend-connection-status.d.ts +0 -37
  328. package/shared/browser-protocol.d.ts +0 -5
  329. /package/dist/assets/{api-w2x5QfxB.js → api-ByCV9MEr.js} +0 -0
  330. /package/dist/assets/{core-vPkV8P_m.js → core-Czwdx12k.js} +0 -0
  331. /package/dist/assets/{fsharp-DNZNZyEE.js → fsharp-BjPpkoJe.js} +0 -0
  332. /package/dist/assets/{go-_kPJjNc_.js → go-BkIDmSUP.js} +0 -0
  333. /package/dist/assets/{graphql-4HCNVt5g.js → graphql-CCJTpqi1.js} +0 -0
  334. /package/dist/assets/{hcl-C87ymY0o.js → hcl-s4z8lUFg.js} +0 -0
  335. /package/dist/assets/{ini-BYrrGNTc.js → ini-CyUW1I7Z.js} +0 -0
  336. /package/dist/assets/{java-B211rJbk.js → java-CFCcGRiM.js} +0 -0
  337. /package/dist/assets/{julia-DVPsRtBm.js → julia-DQyH_EYb.js} +0 -0
  338. /package/dist/assets/{kotlin-BYyNerjp.js → kotlin-B8hA5O51.js} +0 -0
  339. /package/dist/assets/{less-EC9UblGE.js → less-DaVdaas0.js} +0 -0
  340. /package/dist/assets/{lexon-B1yuUdqW.js → lexon-DLBhPd3y.js} +0 -0
  341. /package/dist/assets/{lua-Bo6GFzxT.js → lua-gB1c_cif.js} +0 -0
  342. /package/dist/assets/{m3-C-Y9cBVI.js → m3-C2T3z3gB.js} +0 -0
  343. /package/dist/assets/{markdown-BHu-wLbe.js → markdown-CKq-Euj1.js} +0 -0
  344. /package/dist/assets/{mips-Dkds26rX.js → mips-Bcs5qIDX.js} +0 -0
  345. /package/dist/assets/{msdax-PU4g-8_g.js → msdax-CBP48FHF.js} +0 -0
  346. /package/dist/assets/{mysql-fPpuGpS7.js → mysql-c7tiPcFj.js} +0 -0
  347. /package/dist/assets/{objective-c-Wy1e5JUf.js → objective-c-D4BZkeEV.js} +0 -0
  348. /package/dist/assets/{pascal-BIXwvrqU.js → pascal-CJDZg0MN.js} +0 -0
  349. /package/dist/assets/{pascaligo-DwR0AtL_.js → pascaligo-Bygi8Ynl.js} +0 -0
  350. /package/dist/assets/{perl-CGHAl8my.js → perl-aS8bkf7E.js} +0 -0
  351. /package/dist/assets/{pgsql-B91M73E2.js → pgsql-CzNAYFYl.js} +0 -0
  352. /package/dist/assets/{php-C70ttrCx.js → php-DOtoEFTT.js} +0 -0
  353. /package/dist/assets/{pla-BNrXaRh0.js → pla-DugRnao1.js} +0 -0
  354. /package/dist/assets/{postiats-Dv2IAZR9.js → postiats-DsXwusKh.js} +0 -0
  355. /package/dist/assets/{powerquery-CkY5Wq7J.js → powerquery-DL3o72oD.js} +0 -0
  356. /package/dist/assets/{powershell-uGIYLU3C.js → powershell-C1qHekys.js} +0 -0
  357. /package/dist/assets/{protobuf-CavfmJu-.js → protobuf-DHgsc-cH.js} +0 -0
  358. /package/dist/assets/{pug-Drqnyitx.js → pug-FZXlE_Iu.js} +0 -0
  359. /package/dist/assets/{qrcode-7uGsTEmi.js → qrcode-DJDTdjL7.js} +0 -0
  360. /package/dist/assets/{qsharp-C7yF-Dti.js → qsharp-bLyhI3DT.js} +0 -0
  361. /package/dist/assets/{r-HXLGP0_-.js → r-DjFGXbAa.js} +0 -0
  362. /package/dist/assets/{redis-C4y6mf2p.js → redis-DSoZ_V6u.js} +0 -0
  363. /package/dist/assets/{redshift-DdQrFPrv.js → redshift-CzkdCsrg.js} +0 -0
  364. /package/dist/assets/{restructuredtext-CBrf2PNj.js → restructuredtext-B_XPrGCQ.js} +0 -0
  365. /package/dist/assets/{ruby-CVtMoX2B.js → ruby-Cry2RneJ.js} +0 -0
  366. /package/dist/assets/{rust-Ckq4sbMP.js → rust-CWzdbFq1.js} +0 -0
  367. /package/dist/assets/{sb-er66OpE3.js → sb-DmofU59h.js} +0 -0
  368. /package/dist/assets/{scala-BdWZz-hH.js → scala-BUC2l-vN.js} +0 -0
  369. /package/dist/assets/{scheme-kTV_s2kP.js → scheme-CNIB_72f.js} +0 -0
  370. /package/dist/assets/{scss-Bymy2VJQ.js → scss-DcL4-NbX.js} +0 -0
  371. /package/dist/assets/{shell-bwEP1LQ1.js → shell-CgAGvSSA.js} +0 -0
  372. /package/dist/assets/{solidity-DCddeBgL.js → solidity-DSkt6O_P.js} +0 -0
  373. /package/dist/assets/{sophia-BMN3AQig.js → sophia--5ytcjDN.js} +0 -0
  374. /package/dist/assets/{sparql-CSXOLjzi.js → sparql-C1Srr7cD.js} +0 -0
  375. /package/dist/assets/{sql-COg8ewmK.js → sql-2k_O5fj7.js} +0 -0
  376. /package/dist/assets/{st-CIaZtBS_.js → st-DCCCPqfz.js} +0 -0
  377. /package/dist/assets/{swift-DXiOhUHu.js → swift-Dd8mAfOt.js} +0 -0
  378. /package/dist/assets/{systemverilog-BTDE6Dr2.js → systemverilog-B0-aZYXu.js} +0 -0
  379. /package/dist/assets/{tcl-B0zy9NvV.js → tcl-CZAZwPVX.js} +0 -0
  380. /package/dist/assets/{twig-D594l4Z1.js → twig-D-Ag0tdS.js} +0 -0
  381. /package/dist/assets/{typespec-XKVjaPqo.js → typespec-B7kTFp0Z.js} +0 -0
  382. /package/dist/assets/{useWorkspaceMenuKeyboard-Bpy_s69Z.js → useWorkspaceMenuKeyboard-uYZpDxhU.js} +0 -0
  383. /package/dist/assets/{vb-B2wYoKRV.js → vb-20w1JPum.js} +0 -0
  384. /package/dist/assets/{wgsl-D0Yf2LbK.js → wgsl-CLJfqFt0.js} +0 -0
  385. /package/dist/assets/{workspace-working-copy-C3FSR3N6.js → workspace-working-copy-Cfz07cOd.js} +0 -0
@@ -1,1041 +0,0 @@
1
- const fs = require('fs');
2
- const path = require('path');
3
- const crypto = require('crypto');
4
- const { execFile } = require('child_process');
5
- const { EventEmitter } = require('events');
6
- const WebSocket = require('ws');
7
- const {
8
- matchingProcessIdentity,
9
- readServerProcessIdentity,
10
- } = require('../../../backend/server-process-identity');
11
- const {
12
- runtimeExecutableInvocation,
13
- } = require('../../../backend/runtime-executable-invocation');
14
-
15
- const AGENT_BROWSER_VERSION = '0.32.3';
16
- const DEFAULT_VIEWPORT = Object.freeze({ width: 1280, height: 720, deviceScaleFactor: 1 });
17
- const MAX_VIEWPORT_DIMENSION = 4096;
18
- const MAX_VIEWPORT_PIXELS = 8_000_000;
19
- const COMMAND_TIMEOUT_MS = 30_000;
20
- const CLOSE_TIMEOUT_MS = 10_000;
21
- const PROCESS_EXIT_TIMEOUT_MS = 5_000;
22
- const PROCESS_EXIT_POLL_MS = 100;
23
- const MAX_ACTION_TIMEOUT_MS = 120_000;
24
- const MAX_SCRIPT_LENGTH = 100_000;
25
-
26
- function namespaceForResource(configDir, id, generation) {
27
- const digest = crypto
28
- .createHash('sha256')
29
- .update(`${path.resolve(configDir)}:${String(id)}:${Number(generation)}`)
30
- .digest('hex')
31
- .slice(0, 16);
32
- return `farming-${digest}`;
33
- }
34
-
35
- function sessionForResource(id, generation) {
36
- const digest = crypto
37
- .createHash('sha256')
38
- .update(`${String(id)}:${Number(generation)}`)
39
- .digest('hex')
40
- .slice(0, 16);
41
- return `fb-${digest}`;
42
- }
43
-
44
- function externalTabLabel(id, generation) {
45
- return `farming-${String(id)}-g${Number(generation)}`;
46
- }
47
-
48
- function clampViewport(value = {}) {
49
- let width = Math.max(320, Math.min(MAX_VIEWPORT_DIMENSION, Math.round(Number(value.width) || DEFAULT_VIEWPORT.width)));
50
- let height = Math.max(240, Math.min(MAX_VIEWPORT_DIMENSION, Math.round(Number(value.height) || DEFAULT_VIEWPORT.height)));
51
- const requestedScale = Number(value.deviceScaleFactor);
52
- let deviceScaleFactor = Number.isFinite(requestedScale)
53
- ? Math.max(1, Math.min(2, requestedScale))
54
- : DEFAULT_VIEWPORT.deviceScaleFactor;
55
- const pixels = width * height * deviceScaleFactor * deviceScaleFactor;
56
- if (pixels > MAX_VIEWPORT_PIXELS) {
57
- deviceScaleFactor = Math.max(1, Math.sqrt(MAX_VIEWPORT_PIXELS / (width * height)));
58
- }
59
- if (width * height * deviceScaleFactor * deviceScaleFactor > MAX_VIEWPORT_PIXELS) {
60
- const ratio = Math.sqrt(MAX_VIEWPORT_PIXELS / (width * height));
61
- width = Math.max(320, Math.floor(width * ratio));
62
- height = Math.max(240, Math.floor(height * ratio));
63
- deviceScaleFactor = 1;
64
- }
65
- return { width, height, deviceScaleFactor };
66
- }
67
-
68
- function parseJsonOutput(stdout) {
69
- const text = String(stdout || '').trim();
70
- if (!text) throw new Error('agent-browser returned no JSON output');
71
- const candidates = [text, ...text.split(/\r?\n/).reverse()];
72
- for (const candidate of candidates) {
73
- try {
74
- return JSON.parse(candidate);
75
- } catch {
76
- // Some agent-browser builds may write a diagnostic line before the JSON result.
77
- }
78
- }
79
- throw new Error(`agent-browser returned invalid JSON: ${text.slice(0, 240)}`);
80
- }
81
-
82
- function defaultRunCommand(executablePath, args, options = {}) {
83
- const env = options.env || process.env;
84
- const invocation = runtimeExecutableInvocation(executablePath, args, env);
85
- return new Promise((resolve, reject) => {
86
- execFile(invocation.command, invocation.args, {
87
- encoding: 'utf8',
88
- timeout: options.timeoutMs || COMMAND_TIMEOUT_MS,
89
- maxBuffer: options.maxBuffer || 4 * 1024 * 1024,
90
- env,
91
- }, (error, stdout, stderr) => {
92
- let result;
93
- try {
94
- result = parseJsonOutput(stdout);
95
- } catch (parseError) {
96
- if (!error) {
97
- reject(parseError);
98
- return;
99
- }
100
- }
101
- if (error || result?.success === false) {
102
- const detail = error?.killed
103
- ? `Browser command timed out after ${options.timeoutMs || COMMAND_TIMEOUT_MS} ms`
104
- : (result?.error
105
- || result?.message
106
- || String(stderr || '').trim()
107
- || error?.message
108
- || 'agent-browser command failed');
109
- const commandError = new Error(detail);
110
- commandError.code = result?.code || error?.code || 'AGENT_BROWSER_COMMAND_FAILED';
111
- commandError.cause = error;
112
- reject(commandError);
113
- return;
114
- }
115
- resolve(result);
116
- });
117
- });
118
- }
119
-
120
- function commandData(result) {
121
- return result && typeof result.data === 'object' && result.data !== null ? result.data : {};
122
- }
123
-
124
- function publicCommandData(result) {
125
- if (!result || !Object.prototype.hasOwnProperty.call(result, 'data')) return {};
126
- const data = result.data;
127
- return data && typeof data === 'object' ? data : { value: data };
128
- }
129
-
130
- function normalizeRef(input = {}) {
131
- const ref = String(input.ref || '').trim();
132
- if (ref) return ref.startsWith('@') ? ref : `@${ref}`;
133
- const selector = String(input.selector || '').trim();
134
- if (selector) return selector;
135
- throw new Error('ref or selector is required');
136
- }
137
-
138
- function normalizeTimeoutMs(value, fallback = COMMAND_TIMEOUT_MS) {
139
- const timeoutMs = Number(value);
140
- if (!Number.isFinite(timeoutMs)) return fallback;
141
- return Math.max(100, Math.min(MAX_ACTION_TIMEOUT_MS, Math.round(timeoutMs)));
142
- }
143
-
144
- function requiredText(value, name, maxLength = 10_000) {
145
- const text = String(value ?? '');
146
- if (!text.trim()) throw new Error(`${name} is required`);
147
- if (text.length > maxLength) throw new Error(`${name} is too long`);
148
- return text;
149
- }
150
-
151
- function oneOf(value, values, name) {
152
- const normalized = String(value || '').trim();
153
- if (!values.includes(normalized)) {
154
- throw new Error(`${name} must be one of: ${values.join(', ')}`);
155
- }
156
- return normalized;
157
- }
158
-
159
- function normalizedTabs(data) {
160
- const tabs = Array.isArray(data?.tabs) ? data.tabs : (Array.isArray(data) ? data : []);
161
- return tabs
162
- .filter(tab => tab && String(tab.tabId || tab.id || '').trim())
163
- .map(tab => ({
164
- tabId: String(tab.tabId || tab.id).trim(),
165
- label: String(tab.label || ''),
166
- title: String(tab.title || ''),
167
- type: String(tab.type || 'page'),
168
- url: String(tab.url || 'about:blank'),
169
- active: tab.active === true,
170
- }));
171
- }
172
-
173
- function snapshotElements(refs) {
174
- if (!refs || typeof refs !== 'object') return [];
175
- return Object.entries(refs).slice(0, 500).map(([ref, value]) => ({
176
- ref: String(ref).replace(/^@/, ''),
177
- role: String(value?.role || ''),
178
- name: String(value?.name || '').slice(0, 240),
179
- value: String(value?.value || '').slice(0, 240),
180
- disabled: value?.disabled === true,
181
- }));
182
- }
183
-
184
- function processIdFromSessionInfo(data) {
185
- const candidates = [
186
- data?.pid,
187
- data?.runtime?.backgroundPid,
188
- data?.daemonPid,
189
- data?.daemon?.pid,
190
- data?.session?.pid,
191
- ];
192
- for (const candidate of candidates) {
193
- const pid = Number(candidate);
194
- if (Number.isSafeInteger(pid) && pid > 0) return pid;
195
- }
196
- return null;
197
- }
198
-
199
- function versionFromSessionInfo(data) {
200
- return String(
201
- data?.version
202
- || data?.agentBrowserVersion
203
- || data?.daemon?.version
204
- || '',
205
- ).replace(/^agent-browser\s+/i, '').trim();
206
- }
207
-
208
- function webSocketPort(data) {
209
- const port = Number(data?.port || data?.streamPort || data?.server?.port);
210
- return Number.isSafeInteger(port) && port > 0 && port <= 65_535 ? port : null;
211
- }
212
-
213
- function keyCodeFor(key) {
214
- const named = {
215
- Backspace: 8,
216
- Tab: 9,
217
- Enter: 13,
218
- Shift: 16,
219
- Control: 17,
220
- Alt: 18,
221
- Escape: 27,
222
- ' ': 32,
223
- ArrowLeft: 37,
224
- ArrowUp: 38,
225
- ArrowRight: 39,
226
- ArrowDown: 40,
227
- Delete: 46,
228
- Meta: 91,
229
- };
230
- if (named[key]) return named[key];
231
- return key?.length === 1 ? key.toUpperCase().charCodeAt(0) : 0;
232
- }
233
-
234
- async function waitForIdentityExit(expected, options = {}) {
235
- if (!expected) return true;
236
- const readProcessIdentity = options.readProcessIdentity || readServerProcessIdentity;
237
- const wait = options.wait || (durationMs => new Promise(resolve => setTimeout(resolve, durationMs)));
238
- const timeoutMs = options.timeoutMs || PROCESS_EXIT_TIMEOUT_MS;
239
- const startedAt = Date.now();
240
- while (matchingProcessIdentity(expected, await readProcessIdentity(expected.pid))) {
241
- if (Date.now() - startedAt >= timeoutMs) return false;
242
- await wait(PROCESS_EXIT_POLL_MS);
243
- }
244
- return true;
245
- }
246
-
247
- class AgentBrowserRuntime extends EventEmitter {
248
- constructor(options) {
249
- super();
250
- this.id = options.id;
251
- this.generation = options.generation;
252
- this.configDir = options.configDir;
253
- this.agentBrowserPath = options.agentBrowserPath;
254
- this.requiredVersion = options.requiredVersion || AGENT_BROWSER_VERSION;
255
- this.executablePath = options.executablePath || '';
256
- this.externalCdpUrl = options.externalCdpUrl || '';
257
- this.profileDir = options.profileDir;
258
- this.namespace = options.namespace || namespaceForResource(
259
- this.configDir,
260
- this.id,
261
- this.generation,
262
- );
263
- this.session = options.session || sessionForResource(this.id, this.generation);
264
- this.tabLabel = options.tabLabel || externalTabLabel(this.id, this.generation);
265
- this.runCommand = options.runCommand || defaultRunCommand;
266
- this.createWebSocket = options.createWebSocket || (url => new WebSocket(url));
267
- this.readProcessIdentity = options.readProcessIdentity || readServerProcessIdentity;
268
- this.wait = options.wait || (durationMs => new Promise(resolve => setTimeout(resolve, durationMs)));
269
- this.viewport = { ...DEFAULT_VIEWPORT };
270
- this.viewportRevision = 0;
271
- this.latestFrame = null;
272
- this.processIdentity = null;
273
- this.connectedCdp = false;
274
- this.stream = null;
275
- this.streamReady = false;
276
- this.activeTabId = '';
277
- this.streamTabId = '';
278
- this.knownTabIds = new Set();
279
- this.ownedTabIds = new Set();
280
- this.popupAdmissionUntil = 0;
281
- this.started = false;
282
- this.closedByOwner = false;
283
- this.closeComplete = false;
284
- this.closePromise = null;
285
- this.commandChain = Promise.resolve();
286
- this.screenshotChain = Promise.resolve();
287
- }
288
-
289
- baseArgs() {
290
- return ['--namespace', this.namespace, '--session', this.session];
291
- }
292
-
293
- async command(args, options = {}) {
294
- if (!this.agentBrowserPath) throw new Error('agent-browser runtime is unavailable');
295
- const env = {
296
- ...process.env,
297
- ...options.env,
298
- AGENT_BROWSER_NO_AUTO_DIALOG: 'true',
299
- ...(!this.externalCdpUrl ? {
300
- AGENT_BROWSER_EXECUTABLE_PATH: this.executablePath,
301
- AGENT_BROWSER_PROFILE: this.profileDir,
302
- } : {}),
303
- };
304
- const execute = () => this.runCommand(
305
- this.agentBrowserPath,
306
- [...this.baseArgs(), ...args, '--json'],
307
- { ...options, env },
308
- );
309
- const result = this.commandChain.catch(() => {}).then(execute);
310
- this.commandChain = result;
311
- return result;
312
- }
313
-
314
- async sessionInfo() {
315
- return commandData(await this.command(['session', 'info']));
316
- }
317
-
318
- async start(initialUrl) {
319
- const url = initialUrl || 'about:blank';
320
- try {
321
- fs.mkdirSync(path.dirname(this.profileDir), { recursive: true, mode: 0o700 });
322
- if (this.externalCdpUrl) {
323
- await this.command(['connect', this.externalCdpUrl]);
324
- this.connectedCdp = true;
325
- const created = commandData(await this.command([
326
- 'tab', 'new', '--label', this.tabLabel, 'about:blank',
327
- ]));
328
- const tabId = String(created.tabId || created.id || created.targetId || this.tabLabel);
329
- await this.command(['tab', tabId]);
330
- this.ownedTabIds.add(tabId);
331
- if (url !== 'about:blank') await this.command(['open', url]);
332
- } else {
333
- if (!this.executablePath) throw new Error('A compatible system browser is required');
334
- await this.command(['open', url]);
335
- }
336
-
337
- const tabs = await this.listTabs();
338
- const activeTab = tabs.find(tab => tab.active) || tabs[0];
339
- if (!activeTab) throw new Error('agent-browser did not create an initial tab');
340
- this.activeTabId = activeTab.tabId;
341
- this.streamTabId = activeTab.tabId;
342
- this.knownTabIds = new Set(tabs.map(tab => tab.tabId));
343
- if (!this.externalCdpUrl) {
344
- for (const tab of tabs) this.ownedTabIds.add(tab.tabId);
345
- }
346
-
347
- const info = await this.sessionInfo();
348
- const version = versionFromSessionInfo(info);
349
- if (version && version !== this.requiredVersion) {
350
- throw new Error(`agent-browser ${this.requiredVersion} is required, but session uses ${version}`);
351
- }
352
- const pid = processIdFromSessionInfo(info);
353
- if (!pid) throw new Error('agent-browser did not report its daemon process identity');
354
- const processIdentity = await this.readProcessIdentity(pid);
355
- if (!processIdentity || processIdentity.processGroupId !== pid) {
356
- throw new Error('agent-browser daemon process identity could not be verified');
357
- }
358
- this.processIdentity = processIdentity;
359
- this.emit('process-identity', processIdentity);
360
-
361
- let status = commandData(await this.command(['stream', 'status']));
362
- if (!webSocketPort(status)) {
363
- try {
364
- status = commandData(await this.command(['stream', 'enable']));
365
- } catch (error) {
366
- if (!/already enabled/i.test(String(error?.message || ''))) throw error;
367
- status = commandData(await this.command(['stream', 'status']));
368
- }
369
- }
370
- const port = webSocketPort(status);
371
- if (!port) throw new Error('agent-browser stream did not report a loopback port');
372
- await this.connectStream(`ws://127.0.0.1:${port}`);
373
- this.started = true;
374
- const metadata = await this.metadata();
375
- this.emit('metadata', metadata);
376
- return metadata;
377
- } catch (error) {
378
- try {
379
- await this.close();
380
- } catch (cleanupError) {
381
- throw new Error(
382
- `${error?.message || error}; agent-browser cleanup failed: ${cleanupError?.message || cleanupError}`,
383
- { cause: cleanupError },
384
- );
385
- }
386
- throw error;
387
- }
388
- }
389
-
390
- connectStream(url) {
391
- return new Promise((resolve, reject) => {
392
- const socket = this.createWebSocket(url);
393
- this.stream = socket;
394
- let settled = false;
395
- const failStart = error => {
396
- if (settled) return;
397
- settled = true;
398
- reject(error instanceof Error ? error : new Error(String(error || 'agent-browser stream failed')));
399
- };
400
- socket.once('open', () => {
401
- if (settled) return;
402
- settled = true;
403
- this.streamReady = true;
404
- resolve();
405
- });
406
- socket.on('message', raw => this.handleStreamMessage(raw));
407
- socket.once('error', error => {
408
- if (!settled) {
409
- failStart(error);
410
- return;
411
- }
412
- if (!this.closedByOwner) this.emit('error', error);
413
- });
414
- socket.once('close', () => {
415
- this.streamReady = false;
416
- if (!settled) {
417
- failStart(new Error('agent-browser stream closed before it was ready'));
418
- return;
419
- }
420
- if (!this.closedByOwner) this.emit('exit', 'agent-browser stream closed');
421
- });
422
- });
423
- }
424
-
425
- handleStreamMessage(raw) {
426
- let message;
427
- try {
428
- message = JSON.parse(raw.toString());
429
- } catch {
430
- return;
431
- }
432
- if (message.type === 'frame' && message.data) {
433
- const metadata = message.metadata || {};
434
- const width = Number(metadata.deviceWidth) || this.viewport.width;
435
- const height = Number(metadata.deviceHeight) || this.viewport.height;
436
- const frame = {
437
- type: 'browser-frame',
438
- generation: this.generation,
439
- viewportRevision: this.viewportRevision,
440
- viewport: { width, height },
441
- deviceScaleFactor: Number(metadata.pageScaleFactor) || this.viewport.deviceScaleFactor,
442
- format: 'jpeg',
443
- data: String(message.data),
444
- metadata,
445
- };
446
- this.latestFrame = frame;
447
- this.emit('frame', frame);
448
- return;
449
- }
450
- if (message.type === 'tabs') {
451
- const tabs = normalizedTabs(message.data || message);
452
- const active = tabs.find(tab => tab.active) || tabs[0];
453
- if (active) this.activeTabId = active.tabId;
454
- const newTabIds = tabs
455
- .map(tab => tab.tabId)
456
- .filter(tabId => !this.knownTabIds.has(tabId));
457
- this.knownTabIds = new Set(tabs.map(tab => tab.tabId));
458
- this.emit('tabs', {
459
- tabs,
460
- newTabIds,
461
- popupAdmitted: Date.now() <= this.popupAdmissionUntil,
462
- });
463
- }
464
- }
465
-
466
- sendStream(message) {
467
- if (!this.stream || !this.streamReady || this.stream.readyState !== WebSocket.OPEN) {
468
- throw new Error('agent-browser stream is not connected');
469
- }
470
- this.stream.send(JSON.stringify(message));
471
- }
472
-
473
- async metadata() {
474
- const [urlResult, titleResult] = await Promise.all([
475
- this.command(['get', 'url']),
476
- this.command(['get', 'title']),
477
- ]);
478
- return {
479
- url: String(commandData(urlResult).url || 'about:blank'),
480
- title: String(commandData(titleResult).title || ''),
481
- };
482
- }
483
-
484
- async listTabs() {
485
- return normalizedTabs(commandData(await this.command(['tab', 'list'])));
486
- }
487
-
488
- async createTab(url = 'about:blank', label = '') {
489
- const args = ['tab', 'new'];
490
- if (label) args.push('--label', label);
491
- args.push(url);
492
- const created = commandData(await this.command(args));
493
- const tabs = await this.listTabs();
494
- const tabId = String(created.tabId || created.id || created.targetId || '').trim();
495
- const tab = tabs.find(candidate => candidate.tabId === tabId)
496
- || tabs.find(candidate => candidate.active)
497
- || tabs.at(-1);
498
- if (!tab) throw new Error('agent-browser did not report the new tab');
499
- this.knownTabIds = new Set(tabs.map(candidate => candidate.tabId));
500
- this.ownedTabIds.add(tab.tabId);
501
- await this.switchTab(tab.tabId);
502
- return tab;
503
- }
504
-
505
- async switchTab(tabId) {
506
- const target = String(tabId || '').trim();
507
- if (!target) throw new Error('tab id is required');
508
- await this.command(['tab', target]);
509
- this.activeTabId = target;
510
- this.streamTabId = target;
511
- const tabs = await this.listTabs();
512
- const tab = tabs.find(candidate => candidate.tabId === target);
513
- if (!tab) throw new Error(`Browser tab ${target} is unavailable`);
514
- this.knownTabIds = new Set(tabs.map(candidate => candidate.tabId));
515
- return tab;
516
- }
517
-
518
- async closeTab(tabId) {
519
- const target = String(tabId || '').trim();
520
- if (!target) throw new Error('tab id is required');
521
- await this.command(['tab', 'close', target], { timeoutMs: CLOSE_TIMEOUT_MS });
522
- this.knownTabIds.delete(target);
523
- this.ownedTabIds.delete(target);
524
- const tabs = await this.listTabs();
525
- const active = tabs.find(tab => tab.active) || tabs[0];
526
- this.activeTabId = active?.tabId || '';
527
- if (this.streamTabId === target) this.streamTabId = '';
528
- return tabs;
529
- }
530
-
531
- admitPopup() {
532
- this.popupAdmissionUntil = Date.now() + 2_000;
533
- }
534
-
535
- async navigate(url) {
536
- await this.command(['open', url]);
537
- const metadata = await this.metadata();
538
- this.emit('metadata', metadata);
539
- return metadata;
540
- }
541
-
542
- async navigationCommand(command) {
543
- await this.command([command]);
544
- const metadata = await this.metadata();
545
- this.emit('metadata', metadata);
546
- return metadata;
547
- }
548
-
549
- goBack() {
550
- return this.navigationCommand('back');
551
- }
552
-
553
- goForward() {
554
- return this.navigationCommand('forward');
555
- }
556
-
557
- reload() {
558
- return this.navigationCommand('reload');
559
- }
560
-
561
- async snapshot() {
562
- const data = commandData(await this.command(['snapshot']));
563
- const metadata = await this.metadata();
564
- return {
565
- ...metadata,
566
- elements: snapshotElements(data.refs),
567
- accessibilityTree: String(data.snapshot || ''),
568
- origin: String(data.origin || ''),
569
- };
570
- }
571
-
572
- async screenshot() {
573
- const operation = async () => {
574
- const output = path.join(
575
- path.dirname(this.profileDir),
576
- `screenshot-${this.generation}-${crypto.randomUUID()}.png`,
577
- );
578
- const data = commandData(await this.command(['screenshot', output]));
579
- const resolved = path.resolve(String(data.path || output));
580
- const resourceDir = path.resolve(path.dirname(this.profileDir));
581
- if (resolved !== path.resolve(output) && !resolved.startsWith(`${resourceDir}${path.sep}`)) {
582
- throw new Error('agent-browser returned an unsafe screenshot path');
583
- }
584
- try {
585
- return { mimeType: 'image/png', data: fs.readFileSync(resolved).toString('base64') };
586
- } finally {
587
- fs.rmSync(resolved, { force: true });
588
- }
589
- };
590
- const next = this.screenshotChain.catch(() => {}).then(operation);
591
- this.screenshotChain = next;
592
- return next;
593
- }
594
-
595
- async click(input) {
596
- this.admitPopup();
597
- await this.command(['click', normalizeRef(input)]);
598
- return { ok: true };
599
- }
600
-
601
- async elementAction(kind, input) {
602
- const command = oneOf(
603
- kind,
604
- ['dblclick', 'hover', 'focus', 'check', 'uncheck', 'scrollintoview', 'highlight'],
605
- 'element action',
606
- );
607
- const result = await this.command([command, normalizeRef(input)]);
608
- return publicCommandData(result);
609
- }
610
-
611
- async type(input, clear) {
612
- const action = clear ? 'fill' : 'type';
613
- await this.command([action, normalizeRef(input), String(input.text ?? '')]);
614
- return { ok: true };
615
- }
616
-
617
- async keyboard(input) {
618
- const mode = oneOf(input?.mode, ['type', 'inserttext'], 'keyboard mode');
619
- const text = String(input?.text ?? '');
620
- const result = await this.command(['keyboard', mode, text]);
621
- return publicCommandData(result);
622
- }
623
-
624
- async select(input) {
625
- const values = Array.isArray(input?.values)
626
- ? input.values.map(value => String(value))
627
- : [String(input?.value ?? '')];
628
- if (values.length === 0 || values.some(value => !value)) {
629
- throw new Error('at least one select value is required');
630
- }
631
- const result = await this.command(['select', normalizeRef(input), ...values]);
632
- return publicCommandData(result);
633
- }
634
-
635
- async drag(input) {
636
- const source = normalizeRef({
637
- ref: input?.sourceRef,
638
- selector: input?.sourceSelector,
639
- });
640
- const target = normalizeRef({
641
- ref: input?.targetRef,
642
- selector: input?.targetSelector,
643
- });
644
- const result = await this.command(['drag', source, target]);
645
- return publicCommandData(result);
646
- }
647
-
648
- async upload(input) {
649
- const files = Array.isArray(input?.files) ? input.files.map(file => String(file)) : [];
650
- if (files.length === 0) throw new Error('at least one upload file is required');
651
- const result = await this.command(['upload', normalizeRef(input), ...files], {
652
- timeoutMs: normalizeTimeoutMs(input?.timeoutMs),
653
- });
654
- return publicCommandData(result);
655
- }
656
-
657
- async download(input) {
658
- const outputPath = requiredText(input?.outputPath, 'download output path');
659
- const timeoutMs = normalizeTimeoutMs(input?.timeoutMs);
660
- const result = await this.command([
661
- 'download',
662
- normalizeRef(input),
663
- outputPath,
664
- '--timeout',
665
- String(timeoutMs),
666
- ], {
667
- timeoutMs: timeoutMs + 5_000,
668
- });
669
- return publicCommandData(result);
670
- }
671
-
672
- async waitFor(input) {
673
- const mode = oneOf(
674
- input?.mode || 'selector',
675
- ['selector', 'time', 'url', 'load', 'function', 'text'],
676
- 'wait mode',
677
- );
678
- const args = ['wait'];
679
- if (mode === 'selector') {
680
- args.push(normalizeRef(input));
681
- if (input?.state) {
682
- args.push('--state', oneOf(
683
- input.state,
684
- ['visible', 'hidden', 'attached', 'detached'],
685
- 'wait state',
686
- ));
687
- }
688
- } else if (mode === 'time') {
689
- const durationMs = normalizeTimeoutMs(input?.durationMs, 1_000);
690
- args.push(String(durationMs));
691
- } else {
692
- const option = mode === 'function' ? 'fn' : mode;
693
- const value = mode === 'load'
694
- ? oneOf(input?.value, ['load', 'domcontentloaded', 'networkidle'], 'load state')
695
- : requiredText(input?.value, `${mode} wait value`, mode === 'function' ? MAX_SCRIPT_LENGTH : 10_000);
696
- args.push(`--${option}`, value);
697
- }
698
- const timeoutMs = normalizeTimeoutMs(input?.timeoutMs);
699
- args.push('--timeout', String(timeoutMs));
700
- const result = await this.command(args, {
701
- timeoutMs: timeoutMs + 5_000,
702
- });
703
- return publicCommandData(result);
704
- }
705
-
706
- async get(input) {
707
- const what = oneOf(
708
- input?.what,
709
- ['text', 'html', 'value', 'attr', 'title', 'url', 'count', 'box', 'styles'],
710
- 'get type',
711
- );
712
- const args = ['get', what];
713
- if (!['title', 'url'].includes(what)) args.push(normalizeRef(input));
714
- if (what === 'attr') args.push(requiredText(input?.attribute, 'attribute name', 256));
715
- return publicCommandData(await this.command(args));
716
- }
717
-
718
- async is(input) {
719
- const state = oneOf(input?.state, ['visible', 'enabled', 'checked'], 'element state');
720
- return publicCommandData(await this.command(['is', state, normalizeRef(input)]));
721
- }
722
-
723
- async find(input) {
724
- const locator = oneOf(
725
- input?.locator,
726
- ['role', 'text', 'label', 'placeholder', 'alt', 'title', 'testid', 'first', 'last', 'nth'],
727
- 'find locator',
728
- );
729
- const action = oneOf(
730
- input?.action || 'click',
731
- ['click', 'fill', 'type', 'hover', 'focus', 'check', 'uncheck'],
732
- 'find action',
733
- );
734
- const args = ['find', locator];
735
- if (locator === 'nth') {
736
- const index = Number(input?.index);
737
- if (!Number.isSafeInteger(index) || index < 0) throw new Error('find index must be a non-negative integer');
738
- args.push(String(index), requiredText(input?.value, 'find selector'));
739
- } else {
740
- args.push(requiredText(input?.value, 'find value'));
741
- }
742
- args.push(action);
743
- if (['fill', 'type'].includes(action)) args.push(String(input?.text ?? ''));
744
- if (input?.name) args.push('--name', String(input.name));
745
- if (input?.exact === true) args.push('--exact');
746
- const result = await this.command(args);
747
- return publicCommandData(result);
748
- }
749
-
750
- async evaluate(input) {
751
- const expression = requiredText(input?.expression, 'JavaScript expression', MAX_SCRIPT_LENGTH);
752
- const encoded = Buffer.from(expression).toString('base64');
753
- return publicCommandData(await this.command(['eval', '--base64', encoded]));
754
- }
755
-
756
- async debugLog(kind, input) {
757
- const command = oneOf(kind, ['console', 'errors'], 'debug log');
758
- const args = [command];
759
- if (input?.clear === true) args.push('--clear');
760
- return publicCommandData(await this.command(args));
761
- }
762
-
763
- async network(input) {
764
- const operation = oneOf(input?.operation || 'requests', ['requests', 'request'], 'network operation');
765
- if (operation === 'request') {
766
- return publicCommandData(await this.command([
767
- 'network',
768
- 'request',
769
- requiredText(input?.requestId, 'request id', 256),
770
- ]));
771
- }
772
- const args = ['network', 'requests'];
773
- if (input?.clear === true) args.push('--clear');
774
- for (const [key, flag] of [
775
- ['filter', '--filter'],
776
- ['resourceType', '--type'],
777
- ['method', '--method'],
778
- ['status', '--status'],
779
- ]) {
780
- if (input?.[key] !== undefined && input[key] !== '') {
781
- args.push(flag, String(input[key]));
782
- }
783
- }
784
- return publicCommandData(await this.command(args));
785
- }
786
-
787
- async cookies(input) {
788
- const operation = oneOf(input?.operation || 'get', ['get', 'set', 'clear'], 'cookie operation');
789
- const args = ['cookies', operation];
790
- if (operation === 'set') {
791
- args.push(
792
- requiredText(input?.name, 'cookie name', 1_024),
793
- String(input?.value ?? ''),
794
- );
795
- for (const [key, flag] of [
796
- ['url', '--url'],
797
- ['domain', '--domain'],
798
- ['path', '--path'],
799
- ['sameSite', '--sameSite'],
800
- ['expires', '--expires'],
801
- ]) {
802
- if (input?.[key] !== undefined && input[key] !== '') {
803
- args.push(flag, String(input[key]));
804
- }
805
- }
806
- if (input?.httpOnly === true) args.push('--httpOnly');
807
- if (input?.secure === true) args.push('--secure');
808
- }
809
- const result = await this.command(args);
810
- return publicCommandData(result);
811
- }
812
-
813
- async storage(input) {
814
- const storageType = oneOf(input?.storageType, ['local', 'session'], 'storage type');
815
- const operation = oneOf(input?.operation || 'get', ['get', 'set', 'clear'], 'storage operation');
816
- const args = ['storage', storageType, operation];
817
- if (operation === 'get' && input?.key) args.push(String(input.key));
818
- if (operation === 'set') {
819
- args.push(requiredText(input?.key, 'storage key', 10_000), String(input?.value ?? ''));
820
- }
821
- const result = await this.command(args);
822
- return publicCommandData(result);
823
- }
824
-
825
- async frame(input) {
826
- const target = input?.main === true ? 'main' : normalizeRef(input);
827
- return publicCommandData(await this.command(['frame', target]));
828
- }
829
-
830
- async dialog(input) {
831
- const operation = oneOf(input?.operation || 'status', ['status', 'accept', 'dismiss'], 'dialog operation');
832
- const args = ['dialog', operation];
833
- if (operation === 'accept' && input?.text !== undefined) args.push(String(input.text));
834
- const result = await this.command(args);
835
- return publicCommandData(result);
836
- }
837
-
838
- async press(input) {
839
- if (input?.type === 'key') {
840
- const key = String(input.key || '');
841
- if (!key) throw new Error('key is required');
842
- const code = String(input.code || '');
843
- const windowsVirtualKeyCode = keyCodeFor(key);
844
- const common = {
845
- key,
846
- code,
847
- modifiers: Number(input.modifiers) || 0,
848
- windowsVirtualKeyCode,
849
- };
850
- this.sendStream({ type: 'input_keyboard', eventType: 'keyDown', ...common });
851
- this.sendStream({ type: 'input_keyboard', eventType: 'keyUp', ...common });
852
- return { ok: true };
853
- }
854
- const key = String(input?.key || '').trim();
855
- if (!key) throw new Error('key is required');
856
- await this.command(['press', key]);
857
- return { ok: true };
858
- }
859
-
860
- async resize(value) {
861
- const next = clampViewport(value);
862
- if (
863
- next.width === this.viewport.width
864
- && next.height === this.viewport.height
865
- && next.deviceScaleFactor === this.viewport.deviceScaleFactor
866
- ) return this.viewport;
867
- await this.command([
868
- 'set',
869
- 'viewport',
870
- String(next.width),
871
- String(next.height),
872
- String(next.deviceScaleFactor),
873
- ]);
874
- this.viewport = next;
875
- this.viewportRevision += 1;
876
- return this.viewport;
877
- }
878
-
879
- async pointer(input) {
880
- const x = Number(input.x);
881
- const y = Number(input.y);
882
- if (!Number.isFinite(x) || !Number.isFinite(y)) return;
883
- const eventTypes = {
884
- move: 'mouseMoved',
885
- down: 'mousePressed',
886
- up: 'mouseReleased',
887
- };
888
- const eventType = eventTypes[input.action];
889
- if (!eventType) return;
890
- if (input.action === 'down') this.admitPopup();
891
- this.sendStream({
892
- type: 'input_mouse',
893
- eventType,
894
- x,
895
- y,
896
- button: input.action === 'move' ? 'none' : (input.button || 'left'),
897
- clickCount: input.action === 'move' ? 0 : 1,
898
- modifiers: Number(input.modifiers) || 0,
899
- });
900
- }
901
-
902
- async wheel(input) {
903
- const x = Number(input.x);
904
- const y = Number(input.y);
905
- this.sendStream({
906
- type: 'input_mouse',
907
- eventType: 'mouseWheel',
908
- x: Number.isFinite(x) ? x : this.viewport.width / 2,
909
- y: Number.isFinite(y) ? y : this.viewport.height / 2,
910
- deltaX: Number(input.deltaX) || 0,
911
- deltaY: Number(input.deltaY) || 0,
912
- modifiers: Number(input.modifiers) || 0,
913
- });
914
- }
915
-
916
- async insertText(text) {
917
- const value = String(text || '');
918
- if (/[^\x20-\x7e]/.test(value)) {
919
- await this.command(['keyboard', 'inserttext', value]);
920
- return;
921
- }
922
- for (const key of value) {
923
- const common = {
924
- key,
925
- code: '',
926
- windowsVirtualKeyCode: keyCodeFor(key),
927
- modifiers: 0,
928
- };
929
- this.sendStream({
930
- type: 'input_keyboard',
931
- eventType: 'keyDown',
932
- ...common,
933
- text: key,
934
- });
935
- this.sendStream({
936
- type: 'input_keyboard',
937
- eventType: 'keyUp',
938
- ...common,
939
- });
940
- }
941
- }
942
-
943
- async closeOwnedExternalTabs() {
944
- for (const tabId of [...this.ownedTabIds]) {
945
- try {
946
- await this.command(['tab', 'close', tabId], { timeoutMs: CLOSE_TIMEOUT_MS });
947
- this.ownedTabIds.delete(tabId);
948
- } catch (error) {
949
- const tabs = await this.listTabs();
950
- if (tabs.some(tab => tab.tabId === tabId)) throw error;
951
- this.ownedTabIds.delete(tabId);
952
- }
953
- }
954
- }
955
-
956
- async closeSession() {
957
- const info = await this.sessionInfo();
958
- if (info.active === false) return;
959
- if (!this.processIdentity) {
960
- const pid = processIdFromSessionInfo(info);
961
- if (pid) this.processIdentity = await this.readProcessIdentity(pid);
962
- }
963
- if (this.connectedCdp) {
964
- // Keep the daemon/session identity alive when target cleanup is not
965
- // proven, so an operator can restore the endpoint and retry safely.
966
- await this.closeOwnedExternalTabs();
967
- }
968
- let closeError = null;
969
- try {
970
- await this.command(['close'], { timeoutMs: CLOSE_TIMEOUT_MS });
971
- } catch (error) {
972
- if (!this.processIdentity || matchingProcessIdentity(
973
- this.processIdentity,
974
- await this.readProcessIdentity(this.processIdentity.pid),
975
- )) {
976
- closeError ||= error;
977
- }
978
- }
979
- if (closeError) throw closeError;
980
- }
981
-
982
- async close() {
983
- if (this.closeComplete) return;
984
- if (this.closePromise) return this.closePromise;
985
- this.closedByOwner = true;
986
- this.closePromise = (async () => {
987
- if (this.stream) {
988
- this.stream.removeAllListeners();
989
- this.stream.close();
990
- this.stream = null;
991
- this.streamReady = false;
992
- }
993
- const cleanupErrors = [];
994
- try {
995
- await this.closeSession();
996
- if (!await waitForIdentityExit(this.processIdentity, {
997
- readProcessIdentity: this.readProcessIdentity,
998
- wait: this.wait,
999
- })) {
1000
- throw new Error(`agent-browser daemon ${this.processIdentity.pid} did not exit`);
1001
- }
1002
- } catch (error) {
1003
- cleanupErrors.push(error);
1004
- }
1005
- if (cleanupErrors.length) {
1006
- throw new Error(cleanupErrors.map(error => error?.message || error).join('; '), {
1007
- cause: cleanupErrors[0],
1008
- });
1009
- }
1010
- this.closeComplete = true;
1011
- })().finally(() => {
1012
- this.closePromise = null;
1013
- });
1014
- return this.closePromise;
1015
- }
1016
-
1017
- static async recover(options) {
1018
- const runtime = new AgentBrowserRuntime({
1019
- ...options,
1020
- id: options.id,
1021
- generation: options.generation,
1022
- externalCdpUrl: 'recovery',
1023
- });
1024
- runtime.processIdentity = options.processIdentity || null;
1025
- runtime.connectedCdp = true;
1026
- runtime.closedByOwner = true;
1027
- await runtime.close();
1028
- }
1029
- }
1030
-
1031
- module.exports = {
1032
- AGENT_BROWSER_VERSION,
1033
- AgentBrowserRuntime,
1034
- DEFAULT_VIEWPORT,
1035
- clampViewport,
1036
- defaultRunCommand,
1037
- externalTabLabel,
1038
- namespaceForResource,
1039
- sessionForResource,
1040
- waitForIdentityExit,
1041
- };