farming-code 2.2.30 → 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 (377) hide show
  1. package/THIRD_PARTY_NOTICES.md +7 -0
  2. package/backend/acp/{client-services.js → client-services.cjs} +132 -134
  3. package/backend/acp/packaged-claude-acp.cjs +37 -0
  4. package/backend/acp/packaged-codex-acp.cjs +37 -0
  5. package/backend/acp/patch-decisions.cjs +182 -0
  6. package/backend/acp/permission-security.cjs +131 -0
  7. package/backend/{acp-checkpoint-store.js → acp-checkpoint-store.cjs} +90 -59
  8. package/backend/{acp-runtime.js → acp-runtime.cjs} +1220 -1112
  9. package/backend/acp-session-state.cjs +622 -0
  10. package/backend/acp-transcript.cjs +525 -0
  11. package/backend/agent-env.cjs +257 -0
  12. package/backend/agent-extension-discovery.cjs +452 -0
  13. package/backend/agent-extension-inventory.cjs +116 -0
  14. package/backend/agent-json-stream.cjs +283 -0
  15. package/backend/agent-lifecycle-journal.cjs +185 -0
  16. package/backend/{agent-manager.js → agent-manager.cjs} +3116 -4275
  17. package/backend/agent-order-transaction.cjs +85 -0
  18. package/backend/agent-order.cjs +159 -0
  19. package/backend/agent-provider-session.cjs +98 -0
  20. package/backend/agent-runtime-binding.cjs +179 -0
  21. package/backend/agent-session-history.cjs +1022 -0
  22. package/backend/agent-session-inventory.cjs +291 -0
  23. package/backend/async-cache.cjs +104 -0
  24. package/backend/atomic-json-store.cjs +67 -0
  25. package/backend/auth.cjs +261 -0
  26. package/backend/authoritative-inventory-cache.cjs +383 -0
  27. package/backend/business-health.cjs +68 -0
  28. package/backend/chat-runtime.cjs +50 -0
  29. package/backend/claude-settings.cjs +132 -0
  30. package/backend/cli-agents.cjs +435 -0
  31. package/backend/codex-context-window.cjs +196 -0
  32. package/backend/codex-models.cjs +228 -0
  33. package/backend/codex-session-archive.cjs +82 -0
  34. package/backend/codex-session-history.cjs +590 -0
  35. package/backend/{codex-terminal-profile.js → codex-terminal-profile.cjs} +149 -155
  36. package/backend/codex-transcript-sanitizer.cjs +130 -0
  37. package/backend/codex-transcript.cjs +2107 -0
  38. package/backend/command-runner-child.cjs +105 -0
  39. package/backend/config-manager.cjs +1263 -0
  40. package/backend/control-api.cjs +439 -0
  41. package/backend/data/LICENSE.cua +21 -0
  42. package/backend/executable-discovery.cjs +204 -0
  43. package/backend/farming-agent-bootstrap.cjs +81 -0
  44. package/backend/farming-agent-bootstrap.zh_cn.md +6 -2
  45. package/backend/{farming-app-cli.js → farming-app-cli.cjs} +441 -493
  46. package/backend/farming-cli.cjs +414 -0
  47. package/backend/farming-net-pass.cjs +319 -0
  48. package/backend/farming-net-registry.cjs +123 -0
  49. package/backend/farming-net-server.cjs +309 -0
  50. package/backend/farming-session-store.cjs +651 -0
  51. package/backend/git-worktree-info.cjs +181 -0
  52. package/backend/haiku-token.cjs +828 -0
  53. package/backend/index-html.cjs +96 -0
  54. package/backend/input-parts.cjs +68 -0
  55. package/backend/input-routing.cjs +40 -0
  56. package/backend/{local-session-engine.js → local-session-engine.cjs} +276 -282
  57. package/backend/main-agent-skills.cjs +309 -0
  58. package/backend/main-page-session.cjs +132 -0
  59. package/backend/native-pty-controller-generation.cjs +139 -0
  60. package/backend/{native-pty-host-client.js → native-pty-host-client.cjs} +338 -346
  61. package/backend/native-pty-host-identity.cjs +125 -0
  62. package/backend/native-pty-host-path.cjs +68 -0
  63. package/backend/{native-pty-host.js → native-pty-host.cjs} +480 -569
  64. package/backend/native-session-engine.cjs +296 -0
  65. package/backend/network.cjs +57 -0
  66. package/backend/npm-update-helper.cjs +399 -0
  67. package/backend/packaged-node-pty.cjs +120 -0
  68. package/backend/preview-session-manager.cjs +89 -0
  69. package/backend/provider-adapters.cjs +492 -0
  70. package/backend/provider-home-configuration.cjs +211 -0
  71. package/backend/provider-session-id.cjs +79 -0
  72. package/backend/provider-session-service.cjs +333 -0
  73. package/backend/qr-share-tickets.cjs +119 -0
  74. package/backend/resource-broadcast-protocol.cjs +50 -0
  75. package/backend/review-diff-router.cjs +202 -0
  76. package/backend/review-diff-service.cjs +1267 -0
  77. package/backend/review-session-router.cjs +93 -0
  78. package/backend/review-session-service.cjs +470 -0
  79. package/backend/review-session-store.cjs +161 -0
  80. package/backend/review-state-router.cjs +132 -0
  81. package/backend/review-state-store.cjs +299 -0
  82. package/backend/run-history-store.cjs +97 -0
  83. package/backend/runtime-dependency-manager.cjs +893 -0
  84. package/backend/runtime-executable-invocation.cjs +37 -0
  85. package/backend/runtime-observation.cjs +96 -0
  86. package/backend/server-process-identity.cjs +70 -0
  87. package/backend/server.cjs +3356 -0
  88. package/backend/session-engine-bridge.cjs +144 -0
  89. package/backend/session-engine-router.cjs +105 -0
  90. package/backend/session-engine.cjs +64 -0
  91. package/backend/session-stream-protocol.cjs +181 -0
  92. package/backend/shell-busy-integration.cjs +442 -0
  93. package/backend/slash-command-discovery.cjs +423 -0
  94. package/backend/storage-layout.cjs +263 -0
  95. package/backend/system-monitor.cjs +96 -0
  96. package/backend/terminal-attach-checkpoint.cjs +73 -0
  97. package/backend/terminal-exit-quiescence.cjs +57 -0
  98. package/backend/{terminal-reducer-flow-control.js → terminal-reducer-flow-control.cjs} +45 -22
  99. package/backend/terminal-runtime-cleanup.cjs +99 -0
  100. package/backend/{terminal-screen-state.js → terminal-screen-state.cjs} +100 -108
  101. package/backend/{terminal-screen-worker-pool.js → terminal-screen-worker-pool.cjs} +89 -79
  102. package/backend/{terminal-screen-worker-thread.js → terminal-screen-worker-thread.cjs} +64 -65
  103. package/backend/terminal-screen-worker.cjs +352 -0
  104. package/backend/terminal-state-serialization.cjs +147 -0
  105. package/backend/{terminal-status.js → terminal-status.cjs} +137 -187
  106. package/backend/theme-manager.cjs +185 -0
  107. package/backend/{update-service.js → update-service.cjs} +258 -248
  108. package/backend/usage-forecast.cjs +95 -0
  109. package/backend/{usage-history-client.js → usage-history-client.cjs} +144 -94
  110. package/backend/usage-history-smoke.cjs +85 -0
  111. package/backend/usage-history-worker.cjs +60 -0
  112. package/backend/{usage-monitor.js → usage-monitor.cjs} +363 -390
  113. package/backend/workspace-directory.cjs +239 -0
  114. package/backend/workspace-discovery.cjs +271 -0
  115. package/backend/{workspace-file-router.js → workspace-file-router.cjs} +213 -282
  116. package/backend/{workspace-file-service.js → workspace-file-service.cjs} +1139 -1318
  117. package/backend/workspace-root-registry.cjs +192 -0
  118. package/bin/farming +1 -1
  119. package/dist/acp/codex-acp-1.1.4.mjs +18 -1
  120. package/dist/assets/App-BCkdpWB6.css +1 -0
  121. package/dist/assets/App-CRjKpaGp.js +697 -0
  122. package/dist/assets/CodeSelect-Ci8sKZPU.js +1 -0
  123. package/dist/assets/CodeSelect-T2eNzrOc.css +1 -0
  124. package/dist/assets/{FileEditorMarkdownPreview-Cs9cLv8a.js → FileEditorMarkdownPreview-V06QHlAg.js} +55 -55
  125. package/dist/assets/FileEditorPane-BX-Wjg9U.js +2 -0
  126. package/dist/assets/IconGlyphs-YhV7tqd4.js +1 -0
  127. package/dist/assets/ProjectFilesSection-BDT2_r0o.js +12 -0
  128. package/dist/assets/ReviewPage-BqAs5sG1.js +3 -0
  129. package/dist/assets/code-dark-B7eM_9G9.css +1 -0
  130. package/dist/assets/{cssMode-Bdg5RpcJ.js → cssMode-ADdAlxTO.js} +1 -1
  131. package/dist/assets/{editor.api2-D74ufkbr.js → editor.api2-BFLAr0YF.js} +162 -162
  132. package/dist/assets/file-icons-BpeqWkIB.js +1 -0
  133. package/dist/assets/{freemarker2-DfMDJfnE.js → freemarker2-C90q5jrp.js} +1 -1
  134. package/dist/assets/{handlebars-BEdPtzMT.js → handlebars-BwUQcEDq.js} +1 -1
  135. package/dist/assets/{html-B1fPb1QD.js → html-1s3uPKfh.js} +1 -1
  136. package/dist/assets/{htmlMode-CY2ZjHxH.js → htmlMode-xtKD99de.js} +1 -1
  137. package/dist/assets/{index-D-zetSol.js → index-C8MchCem.js} +3 -3
  138. package/dist/assets/{javascript-BV2OsWA0.js → javascript-Ph7ijyny.js} +1 -1
  139. package/dist/assets/{jsonMode-zd07aeuX.js → jsonMode-D-jGAnFH.js} +1 -1
  140. package/dist/assets/linkComputer-CbGyI_qx.js +1 -0
  141. package/dist/assets/{liquid-BParI24X.js → liquid-0IamE_cI.js} +1 -1
  142. package/dist/assets/{lspLanguageFeatures-BzredkoV.js → lspLanguageFeatures-BxnQunWF.js} +1 -1
  143. package/dist/assets/main-CLKXa6hf.css +1 -0
  144. package/dist/assets/{mdx-vGzUJN98.js → mdx-DdNmfivn.js} +1 -1
  145. package/dist/assets/{monaco.contribution-BmaeBQEc.js → monaco.contribution-B43jsUs1.js} +2 -2
  146. package/dist/assets/{python-CUwdLgsI.js → python-IAt4X5TS.js} +1 -1
  147. package/dist/assets/{razor-BScebUxU.js → razor-DRkFYW0S.js} +1 -1
  148. package/dist/assets/review-C8-oPKXk.css +1 -0
  149. package/dist/assets/{tsMode-DzUAibXK.js → tsMode-_d_4U2gf.js} +1 -1
  150. package/dist/assets/{typescript-D9EOeM7N.js → typescript-C7zcMq9l.js} +1 -1
  151. package/dist/assets/{workers-DAiomYZM.js → workers-D0nOyJzf.js} +1 -1
  152. package/dist/assets/workspace-editor-model-DND_Y-Bj.js +1 -0
  153. package/dist/assets/workspace-editor-monaco-BPWhgcIB.js +4 -0
  154. package/dist/assets/workspace-editor-monaco-N641qPjX.js +1 -0
  155. package/dist/assets/workspace-view-state-k1bTlJ_Z.js +13 -0
  156. package/dist/assets/{xml-wWl1dhkQ.js → xml-BR-HvxT8.js} +1 -1
  157. package/dist/assets/{yaml-Dc2WDaOZ.js → yaml-YtFQwh4q.js} +1 -1
  158. package/dist/index.html +1 -1
  159. package/extensions/browser/backend/agent-browser-runtime.cjs +1040 -0
  160. package/extensions/browser/backend/agent-capability.cjs +85 -0
  161. package/extensions/browser/backend/browser-mcp-server.cjs +655 -0
  162. package/extensions/browser/backend/browser-resource-manager.cjs +1486 -0
  163. package/extensions/browser/backend/browser-resource-store.cjs +228 -0
  164. package/extensions/browser/backend/browser-router.cjs +203 -0
  165. package/extensions/browser/backend/executable-discovery.cjs +248 -0
  166. package/extensions/browser/backend/farming-browser-client.cjs +116 -0
  167. package/extensions/browser/backend/index.cjs +32 -0
  168. package/extensions/browser/backend/managed-chromium-installer.cjs +833 -0
  169. package/extensions/browser/bin/farming-browser +16 -7
  170. package/extensions/computer/backend/agent-capability.cjs +72 -0
  171. package/extensions/computer/backend/computer-constants.cjs +59 -0
  172. package/extensions/computer/backend/computer-mcp-server.cjs +182 -0
  173. package/extensions/computer/backend/computer-resource-manager.cjs +1219 -0
  174. package/extensions/computer/backend/computer-resource-store.cjs +190 -0
  175. package/extensions/computer/backend/computer-router.cjs +257 -0
  176. package/extensions/computer/backend/cua-tools.json +3067 -0
  177. package/extensions/computer/backend/farming-computer-client.cjs +84 -0
  178. package/extensions/computer/backend/index.cjs +35 -0
  179. package/extensions/computer/backend/isolated-browser-provider.cjs +157 -0
  180. package/extensions/computer/bin/farming-computer +131 -0
  181. package/frontend/farming-net/app.js +255 -262
  182. package/frontend/ghostty-loader.js +24 -20
  183. package/frontend/reading-anchor.js +210 -193
  184. package/frontend/runtime-paths.js +24 -26
  185. package/frontend/session-bridge.js +90 -111
  186. package/frontend/session-modal-bridge.js +184 -302
  187. package/frontend/skin-bridge.js +20 -23
  188. package/frontend/skins/crt/app.js +7686 -7901
  189. package/frontend/skins/crt/effects.js +7 -6
  190. package/frontend/skins/crt/index.html +6 -6
  191. package/frontend/skins/crt/styles/markdown.css +4 -4
  192. package/frontend/terminal-bridge.js +174 -181
  193. package/frontend/terminal-replay.js +320 -345
  194. package/frontend/theme-loader.js +55 -71
  195. package/package.json +64 -37
  196. package/shared/backend-connection-status.js +38 -69
  197. package/shared/browser-protocol.js +235 -110
  198. package/shared/websocket-liveness.js +40 -0
  199. package/backend/acp/packaged-claude-acp.js +0 -13
  200. package/backend/acp/packaged-codex-acp.js +0 -13
  201. package/backend/acp/patch-decisions.js +0 -153
  202. package/backend/acp/permission-security.js +0 -108
  203. package/backend/acp-session-state.js +0 -634
  204. package/backend/acp-transcript.js +0 -512
  205. package/backend/agent-env.js +0 -250
  206. package/backend/agent-json-stream.js +0 -268
  207. package/backend/agent-lifecycle-journal.js +0 -133
  208. package/backend/agent-order.js +0 -166
  209. package/backend/agent-provider-session.js +0 -76
  210. package/backend/agent-runtime-binding.js +0 -174
  211. package/backend/agent-session-history.js +0 -986
  212. package/backend/async-cache.js +0 -94
  213. package/backend/atomic-json-store.js +0 -37
  214. package/backend/auth.js +0 -251
  215. package/backend/chat-runtime.js +0 -28
  216. package/backend/claude-settings.js +0 -121
  217. package/backend/cli-agents.js +0 -486
  218. package/backend/codex-context-window.js +0 -189
  219. package/backend/codex-models.js +0 -226
  220. package/backend/codex-session-archive.js +0 -65
  221. package/backend/codex-session-history.js +0 -647
  222. package/backend/codex-transcript-sanitizer.js +0 -115
  223. package/backend/codex-transcript.js +0 -2362
  224. package/backend/command-runner-child.js +0 -67
  225. package/backend/config-manager.js +0 -1117
  226. package/backend/control-api.js +0 -455
  227. package/backend/executable-discovery.js +0 -216
  228. package/backend/farming-agent-bootstrap.js +0 -49
  229. package/backend/farming-cli.js +0 -403
  230. package/backend/farming-net-pass.js +0 -285
  231. package/backend/farming-net-registry.js +0 -112
  232. package/backend/farming-net-server.js +0 -298
  233. package/backend/farming-session-store.js +0 -677
  234. package/backend/git-worktree-info.js +0 -181
  235. package/backend/haiku-token.js +0 -772
  236. package/backend/index-html.js +0 -80
  237. package/backend/input-parts.js +0 -54
  238. package/backend/input-routing.js +0 -24
  239. package/backend/json-cli-runtime.js +0 -275
  240. package/backend/main-agent-skills.js +0 -288
  241. package/backend/main-page-session.js +0 -122
  242. package/backend/native-pty-controller-generation.js +0 -106
  243. package/backend/native-pty-host-identity.js +0 -86
  244. package/backend/native-pty-host-path.js +0 -42
  245. package/backend/native-session-engine.js +0 -268
  246. package/backend/network.js +0 -23
  247. package/backend/npm-update-helper.js +0 -374
  248. package/backend/packaged-node-pty.js +0 -99
  249. package/backend/preview-session-manager.js +0 -68
  250. package/backend/provider-adapters.js +0 -399
  251. package/backend/provider-session-id.js +0 -47
  252. package/backend/provider-session-service.js +0 -345
  253. package/backend/qr-share-tickets.js +0 -100
  254. package/backend/review-diff-router.js +0 -180
  255. package/backend/review-diff-service.js +0 -1270
  256. package/backend/review-session-router.js +0 -74
  257. package/backend/review-session-service.js +0 -446
  258. package/backend/review-session-store.js +0 -151
  259. package/backend/review-state-router.js +0 -116
  260. package/backend/review-state-store.js +0 -286
  261. package/backend/run-history-store.js +0 -67
  262. package/backend/runtime-dependency-manager.js +0 -759
  263. package/backend/runtime-executable-invocation.js +0 -20
  264. package/backend/runtime-observation.js +0 -81
  265. package/backend/server-process-identity.js +0 -47
  266. package/backend/server.js +0 -3225
  267. package/backend/session-engine-bridge.js +0 -129
  268. package/backend/session-engine-router.js +0 -66
  269. package/backend/session-engine.js +0 -39
  270. package/backend/session-stream-protocol.js +0 -185
  271. package/backend/shell-busy-integration.js +0 -472
  272. package/backend/slash-command-discovery.js +0 -433
  273. package/backend/storage-layout.js +0 -205
  274. package/backend/system-monitor.js +0 -77
  275. package/backend/terminal-attach-checkpoint.js +0 -74
  276. package/backend/terminal-exit-quiescence.js +0 -39
  277. package/backend/terminal-runtime-cleanup.js +0 -80
  278. package/backend/terminal-screen-worker.js +0 -337
  279. package/backend/terminal-state-serialization.js +0 -127
  280. package/backend/theme-manager.js +0 -163
  281. package/backend/usage-forecast.js +0 -86
  282. package/backend/usage-history-scanner.ts +0 -2718
  283. package/backend/usage-history-smoke.js +0 -64
  284. package/backend/usage-history-worker.js +0 -34
  285. package/backend/workspace-directory.js +0 -232
  286. package/backend/workspace-discovery.js +0 -311
  287. package/backend/workspace-root-registry.js +0 -166
  288. package/dist/assets/App-BKNUILuL.css +0 -1
  289. package/dist/assets/App-Z1N7T0eM.js +0 -695
  290. package/dist/assets/FileEditorPane-CNtuGjQ3.js +0 -2
  291. package/dist/assets/IconGlyphs-BClgag6E.js +0 -1
  292. package/dist/assets/ProjectFilesSection-K3GHuQ4U.js +0 -12
  293. package/dist/assets/ReviewPage-BRuxFaH5.js +0 -3
  294. package/dist/assets/code-dark-kLsQLvpf.css +0 -1
  295. package/dist/assets/file-icons-BOlcJ0ZF.js +0 -1
  296. package/dist/assets/main-DUTz-Rd2.css +0 -1
  297. package/dist/assets/review-BcnwQtJv.css +0 -1
  298. package/dist/assets/workspace-editor-model-CSGCl21x.js +0 -1
  299. package/dist/assets/workspace-editor-monaco-CJNwbpCy.js +0 -4
  300. package/dist/assets/workspace-editor-monaco-CO9w8YV0.js +0 -1
  301. package/dist/assets/workspace-view-state-BjKPYp0E.js +0 -7
  302. package/extensions/browser/backend/agent-browser-runtime.js +0 -1041
  303. package/extensions/browser/backend/agent-capability.js +0 -55
  304. package/extensions/browser/backend/browser-mcp-server.js +0 -621
  305. package/extensions/browser/backend/browser-resource-manager.js +0 -1331
  306. package/extensions/browser/backend/browser-resource-store.js +0 -190
  307. package/extensions/browser/backend/browser-router.js +0 -141
  308. package/extensions/browser/backend/executable-discovery.js +0 -238
  309. package/extensions/browser/backend/farming-browser-client.js +0 -83
  310. package/extensions/browser/backend/index.js +0 -7
  311. package/extensions/browser/backend/managed-chromium-installer.js +0 -593
  312. package/extensions/browser/frontend/BrowserSidebarPortals.tsx +0 -360
  313. package/extensions/browser/frontend/BrowserViewer.tsx +0 -500
  314. package/extensions/browser/frontend/browser-resource-state.ts +0 -60
  315. package/extensions/browser/frontend/browser.css +0 -567
  316. package/extensions/browser/frontend/types.ts +0 -38
  317. package/extensions/browser/frontend/useBrowserResources.ts +0 -166
  318. package/frontend/vendor/ghostty-web/index.d.ts +0 -1842
  319. package/shared/backend-connection-status.d.ts +0 -37
  320. package/shared/browser-protocol.d.ts +0 -5
  321. /package/dist/assets/{api-w2x5QfxB.js → api-ByCV9MEr.js} +0 -0
  322. /package/dist/assets/{core-vPkV8P_m.js → core-Czwdx12k.js} +0 -0
  323. /package/dist/assets/{fsharp-DNZNZyEE.js → fsharp-BjPpkoJe.js} +0 -0
  324. /package/dist/assets/{go-_kPJjNc_.js → go-BkIDmSUP.js} +0 -0
  325. /package/dist/assets/{graphql-4HCNVt5g.js → graphql-CCJTpqi1.js} +0 -0
  326. /package/dist/assets/{hcl-C87ymY0o.js → hcl-s4z8lUFg.js} +0 -0
  327. /package/dist/assets/{ini-BYrrGNTc.js → ini-CyUW1I7Z.js} +0 -0
  328. /package/dist/assets/{java-B211rJbk.js → java-CFCcGRiM.js} +0 -0
  329. /package/dist/assets/{julia-DVPsRtBm.js → julia-DQyH_EYb.js} +0 -0
  330. /package/dist/assets/{kotlin-BYyNerjp.js → kotlin-B8hA5O51.js} +0 -0
  331. /package/dist/assets/{less-EC9UblGE.js → less-DaVdaas0.js} +0 -0
  332. /package/dist/assets/{lexon-B1yuUdqW.js → lexon-DLBhPd3y.js} +0 -0
  333. /package/dist/assets/{lua-Bo6GFzxT.js → lua-gB1c_cif.js} +0 -0
  334. /package/dist/assets/{m3-C-Y9cBVI.js → m3-C2T3z3gB.js} +0 -0
  335. /package/dist/assets/{markdown-BHu-wLbe.js → markdown-CKq-Euj1.js} +0 -0
  336. /package/dist/assets/{mips-Dkds26rX.js → mips-Bcs5qIDX.js} +0 -0
  337. /package/dist/assets/{msdax-PU4g-8_g.js → msdax-CBP48FHF.js} +0 -0
  338. /package/dist/assets/{mysql-fPpuGpS7.js → mysql-c7tiPcFj.js} +0 -0
  339. /package/dist/assets/{objective-c-Wy1e5JUf.js → objective-c-D4BZkeEV.js} +0 -0
  340. /package/dist/assets/{pascal-BIXwvrqU.js → pascal-CJDZg0MN.js} +0 -0
  341. /package/dist/assets/{pascaligo-DwR0AtL_.js → pascaligo-Bygi8Ynl.js} +0 -0
  342. /package/dist/assets/{perl-CGHAl8my.js → perl-aS8bkf7E.js} +0 -0
  343. /package/dist/assets/{pgsql-B91M73E2.js → pgsql-CzNAYFYl.js} +0 -0
  344. /package/dist/assets/{php-C70ttrCx.js → php-DOtoEFTT.js} +0 -0
  345. /package/dist/assets/{pla-BNrXaRh0.js → pla-DugRnao1.js} +0 -0
  346. /package/dist/assets/{postiats-Dv2IAZR9.js → postiats-DsXwusKh.js} +0 -0
  347. /package/dist/assets/{powerquery-CkY5Wq7J.js → powerquery-DL3o72oD.js} +0 -0
  348. /package/dist/assets/{powershell-uGIYLU3C.js → powershell-C1qHekys.js} +0 -0
  349. /package/dist/assets/{protobuf-CavfmJu-.js → protobuf-DHgsc-cH.js} +0 -0
  350. /package/dist/assets/{pug-Drqnyitx.js → pug-FZXlE_Iu.js} +0 -0
  351. /package/dist/assets/{qrcode-7uGsTEmi.js → qrcode-DJDTdjL7.js} +0 -0
  352. /package/dist/assets/{qsharp-C7yF-Dti.js → qsharp-bLyhI3DT.js} +0 -0
  353. /package/dist/assets/{r-HXLGP0_-.js → r-DjFGXbAa.js} +0 -0
  354. /package/dist/assets/{redis-C4y6mf2p.js → redis-DSoZ_V6u.js} +0 -0
  355. /package/dist/assets/{redshift-DdQrFPrv.js → redshift-CzkdCsrg.js} +0 -0
  356. /package/dist/assets/{restructuredtext-CBrf2PNj.js → restructuredtext-B_XPrGCQ.js} +0 -0
  357. /package/dist/assets/{ruby-CVtMoX2B.js → ruby-Cry2RneJ.js} +0 -0
  358. /package/dist/assets/{rust-Ckq4sbMP.js → rust-CWzdbFq1.js} +0 -0
  359. /package/dist/assets/{sb-er66OpE3.js → sb-DmofU59h.js} +0 -0
  360. /package/dist/assets/{scala-BdWZz-hH.js → scala-BUC2l-vN.js} +0 -0
  361. /package/dist/assets/{scheme-kTV_s2kP.js → scheme-CNIB_72f.js} +0 -0
  362. /package/dist/assets/{scss-Bymy2VJQ.js → scss-DcL4-NbX.js} +0 -0
  363. /package/dist/assets/{shell-bwEP1LQ1.js → shell-CgAGvSSA.js} +0 -0
  364. /package/dist/assets/{solidity-DCddeBgL.js → solidity-DSkt6O_P.js} +0 -0
  365. /package/dist/assets/{sophia-BMN3AQig.js → sophia--5ytcjDN.js} +0 -0
  366. /package/dist/assets/{sparql-CSXOLjzi.js → sparql-C1Srr7cD.js} +0 -0
  367. /package/dist/assets/{sql-COg8ewmK.js → sql-2k_O5fj7.js} +0 -0
  368. /package/dist/assets/{st-CIaZtBS_.js → st-DCCCPqfz.js} +0 -0
  369. /package/dist/assets/{swift-DXiOhUHu.js → swift-Dd8mAfOt.js} +0 -0
  370. /package/dist/assets/{systemverilog-BTDE6Dr2.js → systemverilog-B0-aZYXu.js} +0 -0
  371. /package/dist/assets/{tcl-B0zy9NvV.js → tcl-CZAZwPVX.js} +0 -0
  372. /package/dist/assets/{twig-D594l4Z1.js → twig-D-Ag0tdS.js} +0 -0
  373. /package/dist/assets/{typespec-XKVjaPqo.js → typespec-B7kTFp0Z.js} +0 -0
  374. /package/dist/assets/{useWorkspaceMenuKeyboard-Bpy_s69Z.js → useWorkspaceMenuKeyboard-uYZpDxhU.js} +0 -0
  375. /package/dist/assets/{vb-B2wYoKRV.js → vb-20w1JPum.js} +0 -0
  376. /package/dist/assets/{wgsl-D0Yf2LbK.js → wgsl-CLJfqFt0.js} +0 -0
  377. /package/dist/assets/{workspace-working-copy-C3FSR3N6.js → workspace-working-copy-Cfz07cOd.js} +0 -0
@@ -1,1331 +0,0 @@
1
- const fs = require('fs');
2
- const path = require('path');
3
- const crypto = require('crypto');
4
- const { EventEmitter } = require('events');
5
- const storageLayout = require('../../../backend/storage-layout');
6
- const {
7
- matchingProcessIdentity,
8
- readServerProcessIdentity,
9
- } = require('../../../backend/server-process-identity');
10
- const { BrowserResourceStore, RESOURCE_ID_RE } = require('./browser-resource-store');
11
- const { AgentBrowserRuntime } = require('./agent-browser-runtime');
12
- const {
13
- discoverBrowserExecutables,
14
- discoverBrowserRuntime,
15
- } = require('./executable-discovery');
16
- const { ManagedChromiumInstaller } = require('./managed-chromium-installer');
17
-
18
- const MAX_VIEWER_BUFFER_BYTES = 2 * 1024 * 1024;
19
- const VIEWER_RESIZE_SETTLE_MS = 80;
20
- const BROWSER_RECOVERY_TIMEOUT_MS = 5_000;
21
- const BROWSER_RECOVERY_POLL_MS = 100;
22
- const MAX_UPLOAD_FILES = 20;
23
-
24
- function publicResource(resource, collectionRevision) {
25
- return {
26
- id: resource.id,
27
- projectRootId: resource.projectRootId,
28
- workspace: resource.workspace,
29
- name: resource.name,
30
- status: resource.status,
31
- generation: resource.generation,
32
- revision: resource.revision,
33
- collectionRevision,
34
- url: resource.url,
35
- title: resource.title,
36
- browserKind: resource.browserKind,
37
- error: resource.error,
38
- createdAt: resource.createdAt,
39
- updatedAt: resource.updatedAt,
40
- };
41
- }
42
-
43
- function browserError(message, status = 400, code = 'BROWSER_INVALID_REQUEST') {
44
- const error = new Error(message);
45
- error.status = status;
46
- error.code = code;
47
- return error;
48
- }
49
-
50
- function externalBrowserFailure(action, cause) {
51
- const error = browserError(
52
- `${action}; verify the Browser plugin's external CDP address and the browser's /json/version endpoint`,
53
- 500,
54
- 'BROWSER_EXTERNAL_CDP_FAILED',
55
- );
56
- error.cause = cause;
57
- return error;
58
- }
59
-
60
- function normalizeUrl(value) {
61
- const input = String(value || '').trim();
62
- if (!input) return 'about:blank';
63
- if (input === 'about:blank') return input;
64
- let url = input;
65
- if (!/^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(input)) {
66
- const authority = input.split(/[/?#]/, 1)[0];
67
- const hostname = authority.replace(/:\d+$/, '').replace(/^\[|\]$/g, '').toLowerCase();
68
- const explicitPort = authority.match(/:(\d+)$/)?.[1] || '';
69
- const isIpLiteral = /^\d{1,3}(?:\.\d{1,3}){3}$/.test(hostname) || authority.startsWith('[');
70
- const localHost = hostname === 'localhost'
71
- || hostname.endsWith('.localhost')
72
- || !hostname.includes('.')
73
- || isIpLiteral;
74
- url = `${localHost || (explicitPort && explicitPort !== '443') ? 'http' : 'https'}://${input}`;
75
- }
76
- try {
77
- const parsed = new URL(url);
78
- if (!['http:', 'https:'].includes(parsed.protocol)) {
79
- throw browserError('Browser navigation supports only http, https, and about:blank URLs');
80
- }
81
- return parsed.href;
82
- } catch (error) {
83
- if (error?.status) throw error;
84
- throw browserError('Invalid Browser URL');
85
- }
86
- }
87
-
88
- function tabResourceName(tab) {
89
- const title = String(tab?.title || '').trim();
90
- if (title) return title.slice(0, 120);
91
- try {
92
- return new URL(String(tab?.url || '')).hostname.slice(0, 120) || 'Browser';
93
- } catch {
94
- return 'Browser';
95
- }
96
- }
97
-
98
- function pathInside(root, candidate) {
99
- return candidate === root || candidate.startsWith(`${root}${path.sep}`);
100
- }
101
-
102
- function resolveWorkspaceInputFile(resource, value) {
103
- const workspace = fs.realpathSync(resource.workspace);
104
- const requested = path.resolve(resource.workspace, String(value || ''));
105
- let resolved;
106
- try {
107
- resolved = fs.realpathSync(requested);
108
- } catch {
109
- throw browserError(`Upload file does not exist: ${value}`);
110
- }
111
- if (!pathInside(workspace, resolved)) {
112
- throw browserError('Browser uploads must stay inside the Browser Project workspace');
113
- }
114
- if (!fs.statSync(resolved).isFile()) {
115
- throw browserError(`Browser upload path is not a file: ${value}`);
116
- }
117
- return resolved;
118
- }
119
-
120
- function resolveWorkspaceOutputFile(resource, value) {
121
- const requestedValue = String(value || '').trim();
122
- if (!requestedValue) throw browserError('Download output path is required');
123
- const workspace = fs.realpathSync(resource.workspace);
124
- const requested = path.resolve(resource.workspace, requestedValue);
125
- if (!pathInside(path.resolve(resource.workspace), requested)) {
126
- throw browserError('Browser downloads must stay inside the Browser Project workspace');
127
- }
128
- let parent;
129
- try {
130
- parent = fs.realpathSync(path.dirname(requested));
131
- } catch {
132
- throw browserError('Browser download parent directory does not exist');
133
- }
134
- if (!pathInside(workspace, parent)) {
135
- throw browserError('Browser downloads must stay inside the Browser Project workspace');
136
- }
137
- if (fs.existsSync(requested)) {
138
- throw browserError('Browser download target already exists');
139
- }
140
- return requested;
141
- }
142
-
143
- class BrowserResourceManager extends EventEmitter {
144
- constructor(options) {
145
- super();
146
- this.configDir = options.configDir;
147
- this.store = options.store || new BrowserResourceStore(options.configDir);
148
- this.chromiumInstaller = options.chromiumInstaller || new ManagedChromiumInstaller({
149
- ...options,
150
- configDir: this.configDir,
151
- });
152
- this.discoverExecutable = options.discoverExecutable || (selection => discoverBrowserRuntime({
153
- ...options,
154
- ...selection,
155
- configDir: this.configDir,
156
- managedBrowserPath: this.chromiumInstaller.browserOption()?.path || '',
157
- }));
158
- this.discoverBrowserOptions = options.discoverBrowserOptions
159
- || (options.discoverExecutable
160
- ? () => []
161
- : () => discoverBrowserExecutables({
162
- ...options,
163
- managedBrowserPath: this.chromiumInstaller.browserOption()?.path || '',
164
- }));
165
- this.getBrowserSettings = typeof options.getBrowserSettings === 'function'
166
- ? options.getBrowserSettings
167
- : () => ({ browserSource: 'system', browserExecutablePath: '', browserExternalCdpUrl: '' });
168
- this.createRuntime = options.createRuntime || (input => new AgentBrowserRuntime(input));
169
- this.recoverRuntime = options.recoverRuntime || (input => AgentBrowserRuntime.recover(input));
170
- this.isEnabled = typeof options.isEnabled === 'function' ? options.isEnabled : () => true;
171
- this.readProcessIdentity = options.readProcessIdentity || readServerProcessIdentity;
172
- this.killProcessGroup = options.killProcessGroup || ((processGroupId, signal) => process.kill(-processGroupId, signal));
173
- this.wait = options.wait || (durationMs => new Promise(resolve => setTimeout(resolve, durationMs)));
174
- this.scheduleTimeout = options.scheduleTimeout || setTimeout;
175
- this.cancelTimeout = options.cancelTimeout || clearTimeout;
176
- this.runtimes = new Map();
177
- this.sessions = new Map();
178
- this.operations = new Map();
179
- this.disposed = false;
180
- this.runtimeCapability = null;
181
- this.browserOptions = [];
182
- }
183
-
184
- async init() {
185
- this.store.init();
186
- await this.refreshCapability();
187
- const interrupted = this.store.list().filter(resource =>
188
- ['running', 'starting', 'stopping'].includes(resource.status)
189
- );
190
- const groups = new Map();
191
- for (const resource of interrupted) {
192
- const key = resource.runtimeKind === 'agent-browser'
193
- ? (resource.sessionId || resource.id)
194
- : resource.id;
195
- if (!groups.has(key)) groups.set(key, []);
196
- groups.get(key).push(resource);
197
- }
198
- await Promise.all([...groups.values()].map(resources => {
199
- const owner = resources.find(resource => resource.processIdentity) || resources[0];
200
- return this.recoverInterruptedRuntime(owner, resources);
201
- }));
202
- }
203
-
204
- async recoverInterruptedRuntime(resource, relatedResources = [resource]) {
205
- if (resource.runtimeKind === 'agent-browser') {
206
- const capability = this.runtimeCapability || await this.refreshCapability();
207
- let runtimeError = null;
208
- if (!capability || capability.error || !capability.agentBrowserPath) {
209
- runtimeError = new Error(
210
- capability?.error
211
- || 'The exact agent-browser runtime required to clean up this Browser is unavailable',
212
- );
213
- } else {
214
- try {
215
- await this.recoverRuntime({
216
- id: resource.sessionId || resource.id,
217
- generation: resource.sessionGeneration || resource.generation,
218
- browserKind: resource.browserKind,
219
- processIdentity: resource.processIdentity,
220
- configDir: this.configDir,
221
- profileDir: storageLayout.browserProfileDir(
222
- this.configDir,
223
- resource.sessionId || resource.id,
224
- ),
225
- agentBrowserPath: capability.agentBrowserPath,
226
- readProcessIdentity: this.readProcessIdentity,
227
- wait: this.wait,
228
- });
229
- } catch (error) {
230
- runtimeError = error;
231
- }
232
- }
233
- for (const related of relatedResources) {
234
- this.store.update(related.id, {
235
- status: 'failed',
236
- error: runtimeError
237
- ? `agent-browser Session cleanup failed: ${runtimeError.message || runtimeError}`
238
- : 'Farming restarted and cleaned up the previous Browser runtime',
239
- ...(!runtimeError ? { processIdentity: null } : {}),
240
- tabId: '',
241
- });
242
- }
243
- return;
244
- }
245
-
246
- // Migration cleanup for Browser rows created by Farming's former raw-CDP runtime.
247
- const expected = resource.processIdentity;
248
- if (!expected) {
249
- this.store.update(resource.id, {
250
- status: 'failed',
251
- error: resource.browserKind === 'external-cdp'
252
- ? 'Farming restarted and disconnected from the external Browser'
253
- : 'Farming restarted before the Browser runtime identity was committed',
254
- processIdentity: null,
255
- });
256
- return;
257
- }
258
- const current = await this.readProcessIdentity(expected.pid);
259
- if (!matchingProcessIdentity(expected, current)) {
260
- this.store.update(resource.id, {
261
- status: 'failed',
262
- error: 'Farming restarted after the previous Browser runtime exited',
263
- processIdentity: null,
264
- });
265
- return;
266
- }
267
- if (expected.processGroupId !== expected.pid) {
268
- this.store.update(resource.id, {
269
- status: 'failed',
270
- error: `Previous Browser process ${expected.pid} has an unsafe process-group identity; stop it manually`,
271
- });
272
- return;
273
- }
274
- try {
275
- this.killProcessGroup(expected.processGroupId, 'SIGKILL');
276
- } catch (error) {
277
- if (error?.code !== 'ESRCH') {
278
- const permission = error?.code === 'EPERM' || error?.code === 'EACCES';
279
- this.store.update(resource.id, {
280
- status: 'failed',
281
- error: permission
282
- ? `Farming cannot clean up previous Browser process ${expected.pid} because it lacks permission`
283
- : `Farming could not clean up previous Browser process ${expected.pid}: ${error?.message || error}`,
284
- });
285
- return;
286
- }
287
- }
288
- const startedAt = Date.now();
289
- while (matchingProcessIdentity(expected, await this.readProcessIdentity(expected.pid))) {
290
- if (Date.now() - startedAt >= BROWSER_RECOVERY_TIMEOUT_MS) {
291
- this.store.update(resource.id, {
292
- status: 'failed',
293
- error: `Previous Browser process ${expected.pid} did not exit after SIGKILL`,
294
- });
295
- return;
296
- }
297
- await this.wait(BROWSER_RECOVERY_POLL_MS);
298
- }
299
- this.store.update(resource.id, {
300
- status: 'failed',
301
- error: 'Farming restarted and cleaned up the previous Browser runtime',
302
- processIdentity: null,
303
- });
304
- }
305
-
306
- capability() {
307
- const executable = this.runtimeCapability;
308
- const runnable = executable && !executable.error;
309
- const enabled = this.isEnabled() === true;
310
- const selection = this.browserSelection();
311
- return {
312
- enabled,
313
- available: enabled && Boolean(runnable),
314
- browser: runnable ? { kind: executable.kind, path: executable.path } : null,
315
- selection,
316
- options: this.browserOptions.map(option => ({ kind: option.kind, path: option.path })),
317
- installation: this.chromiumInstaller.status(),
318
- message: !enabled
319
- ? 'Browser extension is disabled'
320
- : (executable?.error || (runnable
321
- ? ''
322
- : 'Install Farming-managed Chromium, choose a system Chromium browser, or configure a loopback external CDP endpoint')),
323
- };
324
- }
325
-
326
- browserSelection(settings = this.getBrowserSettings()) {
327
- const source = settings?.browserSource;
328
- return {
329
- source: ['external-cdp', 'managed'].includes(source) ? source : 'system',
330
- executablePath: String(settings?.browserExecutablePath || ''),
331
- externalCdpUrl: String(settings?.browserExternalCdpUrl || 'http://127.0.0.1:9222'),
332
- };
333
- }
334
-
335
- async probeCapability(selection = this.browserSelection()) {
336
- const browserOptions = this.discoverBrowserOptions();
337
- const selectedOption = browserOptions.find(option => option.path === selection.executablePath);
338
- const runtimeCapability = await this.discoverExecutable({
339
- source: selection.source,
340
- executablePath: selection.executablePath,
341
- executableKind: selectedOption?.kind,
342
- externalCdpUrl: selection.externalCdpUrl,
343
- });
344
- return { browserOptions, runtimeCapability };
345
- }
346
-
347
- async refreshCapability(selection = this.browserSelection()) {
348
- const probe = await this.probeCapability(selection);
349
- this.browserOptions = probe.browserOptions;
350
- this.runtimeCapability = probe.runtimeCapability;
351
- return this.runtimeCapability;
352
- }
353
-
354
- async installManagedChromium() {
355
- if (this.disposed) {
356
- throw browserError('Browser manager is stopping', 503, 'BROWSER_MANAGER_STOPPING');
357
- }
358
- await this.chromiumInstaller.install();
359
- await this.refreshCapability();
360
- return this.capability();
361
- }
362
-
363
- list() {
364
- this.requireEnabled();
365
- return this.store.list().map(resource => publicResource(resource, this.store.revision));
366
- }
367
-
368
- snapshot() {
369
- return {
370
- collectionRevision: this.store.revision,
371
- resources: this.list(),
372
- };
373
- }
374
-
375
- get(id) {
376
- this.requireEnabled();
377
- return publicResource(this.requireStored(id), this.store.revision);
378
- }
379
-
380
- create(input) {
381
- this.requireAvailable();
382
- if (this.disposed) throw browserError('Browser manager is stopping', 503, 'BROWSER_MANAGER_STOPPING');
383
- const resource = this.store.create({
384
- projectRootId: input.projectRootId,
385
- workspace: input.workspace,
386
- name: input.name,
387
- url: normalizeUrl(input.url),
388
- });
389
- this.emitResource(resource);
390
- return publicResource(resource, this.store.revision);
391
- }
392
-
393
- rename(id, name) {
394
- this.requireEnabled();
395
- const title = String(name || '').trim();
396
- if (!title) throw browserError('Browser name is required');
397
- const resource = this.requireStored(id);
398
- const next = this.store.update(resource.id, {
399
- name: title.slice(0, 120),
400
- autoName: false,
401
- });
402
- this.emitResource(next);
403
- return publicResource(next, this.store.revision);
404
- }
405
-
406
- start(id) {
407
- this.requireEnabled();
408
- return this.enqueue(id, async () => {
409
- const resource = this.requireStored(id);
410
- const existingBinding = this.runtimes.get(id);
411
- if (resource.status === 'running' && existingBinding) {
412
- return publicResource(resource, this.store.revision);
413
- }
414
- if (existingBinding) {
415
- throw browserError(
416
- 'A previous Browser runtime still owns this resource; stop it before restarting',
417
- 409,
418
- 'BROWSER_RUNTIME_OWNED',
419
- );
420
- }
421
- if (resource.status === 'starting' || resource.status === 'stopping') {
422
- throw browserError(`Browser is ${resource.status}`, 409, 'BROWSER_BUSY');
423
- }
424
- if (resource.processIdentity) {
425
- const blockedIdentity = resource.processIdentity;
426
- throw browserError(
427
- `Previous Browser process ${blockedIdentity.pid} still requires cleanup`,
428
- 409,
429
- 'BROWSER_RECOVERY_CLEANUP_REQUIRED',
430
- );
431
- }
432
- const executable = await this.refreshCapability();
433
- if (!executable || executable.error) {
434
- const failed = this.store.update(id, {
435
- status: 'failed',
436
- error: executable?.error
437
- || 'Install Farming-managed Chromium, choose a system Chromium browser, or configure a loopback external CDP endpoint',
438
- });
439
- this.emitResource(failed);
440
- throw browserError(failed.error, 503, 'BROWSER_EXECUTABLE_NOT_FOUND');
441
- }
442
-
443
- const generation = resource.generation + 1;
444
- const starting = this.store.update(id, {
445
- status: 'starting',
446
- generation,
447
- browserKind: executable.kind,
448
- runtimeKind: 'agent-browser',
449
- error: '',
450
- processIdentity: null,
451
- });
452
- this.emitResource(starting);
453
-
454
- const reusableSession = [...this.sessions.values()].find(session => (
455
- !session.closing
456
- && session.projectRootId === resource.projectRootId
457
- && session.browserKind === executable.kind
458
- ));
459
- if (reusableSession) {
460
- try {
461
- let running;
462
- let binding;
463
- const operation = (reusableSession.actionChain || Promise.resolve())
464
- .catch(() => {})
465
- .then(async () => {
466
- const tab = await reusableSession.runtime.createTab(
467
- resource.url,
468
- executable.kind === 'external-cdp'
469
- ? `farming-${resource.id}-g${generation}`
470
- : '',
471
- );
472
- binding = this.createBinding(reusableSession, {
473
- ...starting,
474
- tabId: tab.tabId,
475
- });
476
- reusableSession.bindings.set(id, binding);
477
- reusableSession.activeResourceId = id;
478
- this.runtimes.set(id, binding);
479
- running = this.store.update(id, {
480
- status: 'running',
481
- sessionId: reusableSession.id,
482
- sessionGeneration: reusableSession.generation,
483
- tabId: tab.tabId,
484
- url: tab.url || resource.url,
485
- title: tab.title || '',
486
- error: '',
487
- processIdentity: null,
488
- });
489
- });
490
- reusableSession.actionChain = operation;
491
- await operation;
492
- this.emitResource(running);
493
- this.broadcastRuntimeState(binding);
494
- return publicResource(running, this.store.revision);
495
- } catch (error) {
496
- const failed = this.store.update(id, {
497
- status: 'failed',
498
- error: error?.message || 'Failed to create Browser tab',
499
- tabId: '',
500
- });
501
- this.emitResource(failed);
502
- throw browserError(failed.error, 500, 'BROWSER_START_FAILED');
503
- }
504
- }
505
-
506
- const sessionId = resource.sessionId || id;
507
- const previousSessionGeneration = this.store.list()
508
- .filter(candidate => candidate.sessionId === sessionId)
509
- .reduce((maximum, candidate) => Math.max(maximum, candidate.sessionGeneration || 0), 0);
510
- const sessionGeneration = previousSessionGeneration + 1;
511
- const runtime = this.createRuntime({
512
- id: sessionId,
513
- generation: sessionGeneration,
514
- configDir: this.configDir,
515
- agentBrowserPath: executable.agentBrowserPath,
516
- executablePath: executable.path,
517
- externalCdpUrl: executable.cdpUrl || '',
518
- profileDir: storageLayout.browserProfileDir(this.configDir, sessionId),
519
- });
520
- const session = {
521
- id: sessionId,
522
- generation: sessionGeneration,
523
- projectRootId: resource.projectRootId,
524
- browserKind: executable.kind,
525
- runtime,
526
- bindings: new Map(),
527
- activeResourceId: id,
528
- processOwnerResourceId: id,
529
- actionChain: Promise.resolve(),
530
- reconcilingTabs: Promise.resolve(),
531
- initializing: true,
532
- closing: false,
533
- };
534
- const binding = this.createBinding(session, starting);
535
- session.bindings.set(id, binding);
536
- this.sessions.set(sessionId, session);
537
- this.runtimes.set(id, binding);
538
- this.bindSession(session);
539
- try {
540
- const metadata = await runtime.start(resource.url);
541
- const tabs = await runtime.listTabs();
542
- const tab = tabs.find(candidate => candidate.active) || tabs[0];
543
- if (!tab) throw new Error('agent-browser did not report the Browser tab');
544
- binding.tabId = tab.tabId;
545
- if (this.runtimes.get(id) !== binding) {
546
- throw browserError('Browser startup lost runtime ownership', 409, 'BROWSER_START_REPLACED');
547
- }
548
- const running = this.store.update(id, {
549
- status: 'running',
550
- sessionId,
551
- sessionGeneration,
552
- tabId: tab.tabId,
553
- url: metadata.url || resource.url,
554
- title: metadata.title || '',
555
- error: '',
556
- });
557
- session.initializing = false;
558
- this.emitResource(running);
559
- this.broadcastRuntimeState(binding);
560
- return publicResource(running, this.store.revision);
561
- } catch (error) {
562
- session.initializing = false;
563
- let cleanupError = null;
564
- try {
565
- await runtime.close();
566
- } catch (closeError) {
567
- cleanupError = closeError;
568
- }
569
- if (!cleanupError && this.runtimes.get(id) === binding) this.runtimes.delete(id);
570
- if (!cleanupError && this.sessions.get(sessionId) === session) this.sessions.delete(sessionId);
571
- const current = this.store.get(id);
572
- const failureMessage = executable.kind === 'external-cdp'
573
- ? externalBrowserFailure('External Browser connection failed', error).message
574
- : error?.message || 'Failed to start Browser';
575
- const failed = current?.generation === generation
576
- ? this.store.update(id, {
577
- status: 'failed',
578
- error: cleanupError
579
- ? `${failureMessage}; cleanup failed`
580
- : failureMessage,
581
- tabId: '',
582
- ...(!cleanupError ? { processIdentity: null } : {}),
583
- })
584
- : null;
585
- if (failed) this.emitResource(failed);
586
- throw browserError(
587
- failed?.error || error?.message || 'Failed to start Browser',
588
- 500,
589
- 'BROWSER_START_FAILED',
590
- );
591
- }
592
- });
593
- }
594
-
595
- stop(id) {
596
- this.requireEnabled();
597
- return this.enqueue(id, async () => {
598
- const resource = this.requireStored(id);
599
- const binding = this.runtimes.get(id);
600
- if (!binding) {
601
- if (resource.processIdentity) {
602
- await this.recoverInterruptedRuntime(resource);
603
- const recovered = this.requireStored(id);
604
- if (recovered.processIdentity) {
605
- const blockedIdentity = recovered.processIdentity;
606
- throw browserError(
607
- recovered.error || `Previous Browser process ${blockedIdentity.pid} still requires cleanup`,
608
- 500,
609
- 'BROWSER_RECOVERY_CLEANUP_REQUIRED',
610
- );
611
- }
612
- }
613
- const stopped = this.store.update(id, {
614
- status: 'stopped',
615
- error: '',
616
- processIdentity: null,
617
- });
618
- this.emitResource(stopped);
619
- return publicResource(stopped, this.store.revision);
620
- }
621
- const stopping = this.store.update(id, { status: 'stopping', error: '' });
622
- this.emitResource(stopping);
623
- this.broadcastRuntimeState(binding);
624
- const { session } = binding;
625
- session.closing = session.bindings.size === 1;
626
- try {
627
- const closeOperation = (session.actionChain || Promise.resolve())
628
- .catch(() => {})
629
- .then(() => (
630
- session.bindings.size > 1
631
- ? session.runtime.closeTab(binding.tabId)
632
- : session.runtime.close()
633
- ));
634
- session.actionChain = closeOperation;
635
- await closeOperation;
636
- } catch (error) {
637
- session.closing = false;
638
- if (resource.browserKind === 'external-cdp') {
639
- throw externalBrowserFailure('External Browser targets could not be closed', error);
640
- }
641
- throw error;
642
- }
643
- session.bindings.delete(id);
644
- if (this.runtimes.get(id) === binding) this.runtimes.delete(id);
645
- if (session.bindings.size === 0 && this.sessions.get(session.id) === session) {
646
- this.sessions.delete(session.id);
647
- }
648
- session.closing = false;
649
-
650
- if (session.processOwnerResourceId === id && session.bindings.size > 0) {
651
- const nextOwner = session.bindings.values().next().value;
652
- session.processOwnerResourceId = nextOwner.id;
653
- const ownerResource = this.store.update(nextOwner.id, {
654
- processIdentity: resource.processIdentity,
655
- });
656
- this.emitResource(ownerResource);
657
- this.broadcastRuntimeState(nextOwner);
658
- }
659
- const stopped = this.store.update(id, {
660
- status: 'stopped',
661
- error: '',
662
- processIdentity: null,
663
- tabId: '',
664
- });
665
- this.emitResource(stopped);
666
- this.broadcastRuntimeState(binding);
667
- this.releaseViewerState(binding);
668
- return publicResource(stopped, this.store.revision);
669
- });
670
- }
671
-
672
- async delete(id) {
673
- this.requireEnabled();
674
- await this.stop(id);
675
- const resource = this.requireStored(id);
676
- this.store.delete(id);
677
- const sessionId = resource.sessionId || id;
678
- const profileDir = storageLayout.browserProfileDir(this.configDir, sessionId);
679
- const browsersDir = path.resolve(storageLayout.browserResourcesDir(this.configDir));
680
- const resourceDir = path.resolve(profileDir, '..');
681
- const sessionStillReferenced = this.store.list().some(candidate => candidate.sessionId === sessionId);
682
- if (
683
- !sessionStillReferenced
684
- && resourceDir.startsWith(`${browsersDir}${path.sep}`)
685
- && RESOURCE_ID_RE.test(sessionId)
686
- ) {
687
- fs.rmSync(resourceDir, { recursive: true, force: true });
688
- }
689
- this.emit('deleted', { id, collectionRevision: this.store.revision });
690
- return { id, collectionRevision: this.store.revision };
691
- }
692
-
693
- navigate(id, url) {
694
- this.requireEnabled();
695
- const normalized = normalizeUrl(url);
696
- return this.withRuntime(id, async (runtime, binding) => {
697
- const metadata = await runtime.navigate(normalized);
698
- this.updateMetadata(binding, metadata);
699
- return this.get(id);
700
- });
701
- }
702
-
703
- goBack(id) {
704
- return this.withRuntime(id, async (runtime, binding) => {
705
- const metadata = await runtime.goBack();
706
- this.updateMetadata(binding, metadata);
707
- return this.get(id);
708
- });
709
- }
710
-
711
- goForward(id) {
712
- return this.withRuntime(id, async (runtime, binding) => {
713
- const metadata = await runtime.goForward();
714
- this.updateMetadata(binding, metadata);
715
- return this.get(id);
716
- });
717
- }
718
-
719
- reload(id) {
720
- return this.withRuntime(id, async (runtime, binding) => {
721
- const metadata = await runtime.reload();
722
- this.updateMetadata(binding, metadata);
723
- return this.get(id);
724
- });
725
- }
726
-
727
- action(id, input) {
728
- this.requireEnabled();
729
- const kind = String(input?.kind || '').trim();
730
- if (kind === 'snapshot') return this.withRuntime(id, runtime => runtime.snapshot());
731
- if (kind === 'screenshot') return this.withRuntime(id, runtime => runtime.screenshot());
732
- if (kind === 'navigate') return this.navigate(id, input.url);
733
- if (kind === 'back') return this.goBack(id);
734
- if (kind === 'forward') return this.goForward(id);
735
- if (kind === 'reload') return this.reload(id);
736
- if (kind === 'click') return this.withRuntime(id, runtime => runtime.click(input));
737
- if ([
738
- 'dblclick',
739
- 'hover',
740
- 'focus',
741
- 'check',
742
- 'uncheck',
743
- 'scrollintoview',
744
- 'highlight',
745
- ].includes(kind)) {
746
- return this.withRuntime(id, runtime => runtime.elementAction(kind, input));
747
- }
748
- if (kind === 'type') return this.withRuntime(id, runtime => runtime.type(input, false));
749
- if (kind === 'fill') return this.withRuntime(id, runtime => runtime.type(input, true));
750
- if (kind === 'keyboard') return this.withRuntime(id, runtime => runtime.keyboard(input));
751
- if (kind === 'press') return this.withRuntime(id, runtime => runtime.press(input));
752
- if (kind === 'select') return this.withRuntime(id, runtime => runtime.select(input));
753
- if (kind === 'drag') return this.withRuntime(id, runtime => runtime.drag(input));
754
- if (kind === 'wait') return this.withRuntime(id, runtime => runtime.waitFor(input));
755
- if (kind === 'get') return this.withRuntime(id, runtime => runtime.get(input));
756
- if (kind === 'is') return this.withRuntime(id, runtime => runtime.is(input));
757
- if (kind === 'find') return this.withRuntime(id, runtime => runtime.find(input));
758
- if (kind === 'eval') return this.withRuntime(id, runtime => runtime.evaluate(input));
759
- if (kind === 'console' || kind === 'errors') {
760
- return this.withRuntime(id, runtime => runtime.debugLog(kind, input));
761
- }
762
- if (kind === 'network') return this.withRuntime(id, runtime => runtime.network(input));
763
- if (kind === 'cookies') return this.withRuntime(id, runtime => runtime.cookies(input));
764
- if (kind === 'storage') return this.withRuntime(id, runtime => runtime.storage(input));
765
- if (kind === 'frame') return this.withRuntime(id, runtime => runtime.frame(input));
766
- if (kind === 'dialog') return this.withRuntime(id, runtime => runtime.dialog(input));
767
- if (kind === 'upload') {
768
- const resource = this.requireStored(id);
769
- const requestedFiles = Array.isArray(input?.files) ? input.files : [];
770
- if (requestedFiles.length === 0 || requestedFiles.length > MAX_UPLOAD_FILES) {
771
- throw browserError(`Browser upload requires between 1 and ${MAX_UPLOAD_FILES} files`);
772
- }
773
- const files = requestedFiles.map(file => resolveWorkspaceInputFile(resource, file));
774
- return this.withRuntime(id, runtime => runtime.upload({ ...input, files }));
775
- }
776
- if (kind === 'download') {
777
- const resource = this.requireStored(id);
778
- const target = resolveWorkspaceOutputFile(resource, input?.path);
779
- return this.withRuntime(id, async runtime => {
780
- const resourceDir = path.dirname(storageLayout.browserProfileDir(
781
- this.configDir,
782
- resource.sessionId || id,
783
- ));
784
- const downloadDir = path.join(resourceDir, 'downloads');
785
- fs.mkdirSync(downloadDir, { recursive: true, mode: 0o700 });
786
- const temporaryPath = path.join(
787
- downloadDir,
788
- `${crypto.randomUUID()}-${path.basename(target)}`,
789
- );
790
- try {
791
- await runtime.download({ ...input, outputPath: temporaryPath });
792
- const stat = fs.statSync(temporaryPath);
793
- if (!stat.isFile()) throw browserError('Browser download did not produce a regular file');
794
- fs.copyFileSync(temporaryPath, target, fs.constants.COPYFILE_EXCL);
795
- return {
796
- ok: true,
797
- path: path.relative(resource.workspace, target) || path.basename(target),
798
- size: stat.size,
799
- };
800
- } finally {
801
- fs.rmSync(temporaryPath, { force: true });
802
- }
803
- });
804
- }
805
- if (kind === 'scroll') return this.withRuntime(id, async runtime => {
806
- await runtime.wheel(input);
807
- return { ok: true };
808
- });
809
- throw browserError(`Unsupported Browser action: ${kind || '(missing)'}`);
810
- }
811
-
812
- attachViewer(id, ws) {
813
- this.requireEnabled();
814
- const resource = this.requireStored(id);
815
- const binding = this.runtimes.get(id);
816
- ws.send(JSON.stringify({
817
- type: 'browser-state',
818
- resource: publicResource(resource, this.store.revision),
819
- }));
820
- if (!binding || resource.status !== 'running') return () => {};
821
- binding.viewers.add(ws);
822
- if (binding.latestFrame) ws.send(JSON.stringify(binding.latestFrame));
823
- void this.withRuntime(id, () => {}).catch(error => {
824
- if (ws.readyState === 1) {
825
- ws.send(JSON.stringify({ type: 'browser-error', message: error?.message || 'Browser tab failed' }));
826
- }
827
- });
828
- const onMessage = raw => {
829
- let message;
830
- try {
831
- message = JSON.parse(raw.toString());
832
- } catch {
833
- return;
834
- }
835
- const operation = message.type === 'resize'
836
- ? this.scheduleViewerResize(binding, ws, message)
837
- : this.handleViewerMessage(binding, ws, message);
838
- void Promise.resolve(operation).catch(error => {
839
- if (ws.readyState === 1) {
840
- ws.send(JSON.stringify({ type: 'browser-error', message: error?.message || 'Browser input failed' }));
841
- }
842
- });
843
- };
844
- ws.on('message', onMessage);
845
- const detach = () => {
846
- binding.viewers.delete(ws);
847
- binding.viewerGeometries.delete(ws);
848
- if (binding.viewerViewportOwner === ws) {
849
- binding.viewerViewportOwner = binding.viewers.values().next().value || null;
850
- if (binding.viewerViewportOwner) {
851
- const geometry = binding.viewerGeometries.get(binding.viewerViewportOwner);
852
- if (geometry) {
853
- void this.scheduleViewerResize(binding, binding.viewerViewportOwner, geometry).catch(() => {});
854
- }
855
- } else {
856
- this.clearViewerResize(binding);
857
- }
858
- }
859
- ws.off('message', onMessage);
860
- };
861
- ws.once('close', detach);
862
- return detach;
863
- }
864
-
865
- handleViewerMessage(binding, viewer, message) {
866
- const resource = this.requireStored(binding.id);
867
- if (
868
- resource.status !== 'running'
869
- || message.generation !== binding.generation
870
- || this.runtimes.get(binding.id) !== binding
871
- ) {
872
- return Promise.reject(browserError(
873
- 'Browser Viewer input is no longer admitted',
874
- 409,
875
- 'BROWSER_NOT_RUNNING',
876
- ));
877
- }
878
- const { session } = binding;
879
- const next = (session.actionChain || Promise.resolve())
880
- .catch(() => {})
881
- .then(async () => {
882
- await this.activateBinding(binding);
883
- return this.performViewerMessage(binding, viewer, message);
884
- });
885
- session.actionChain = next;
886
- return next;
887
- }
888
-
889
- scheduleViewerResize(binding, viewer, message) {
890
- const resource = this.requireStored(binding.id);
891
- if (
892
- resource.status !== 'running'
893
- || message.generation !== binding.generation
894
- || this.runtimes.get(binding.id) !== binding
895
- ) {
896
- return Promise.reject(browserError(
897
- 'Browser Viewer resize is no longer admitted',
898
- 409,
899
- 'BROWSER_NOT_RUNNING',
900
- ));
901
- }
902
- const width = Math.round(Number(message.width));
903
- const height = Math.round(Number(message.height));
904
- const requestedDeviceScaleFactor = Number(message.deviceScaleFactor);
905
- if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) {
906
- return Promise.reject(browserError('Browser Viewer size is invalid'));
907
- }
908
- const deviceScaleFactor = Number.isFinite(requestedDeviceScaleFactor)
909
- ? Math.max(1, Math.min(2, requestedDeviceScaleFactor))
910
- : 1;
911
- const geometry = {
912
- type: 'resize',
913
- generation: message.generation,
914
- width,
915
- height,
916
- deviceScaleFactor,
917
- };
918
- binding.viewerGeometries.set(viewer, geometry);
919
- if (
920
- message.claim === true
921
- || !binding.viewerViewportOwner
922
- || !binding.viewers.has(binding.viewerViewportOwner)
923
- ) {
924
- binding.viewerViewportOwner = viewer;
925
- }
926
- if (binding.viewerViewportOwner !== viewer) return Promise.resolve();
927
- binding.pendingViewerResize = { viewer, geometry };
928
- if (binding.viewerResizeTimer) this.cancelTimeout(binding.viewerResizeTimer);
929
- binding.viewerResizeTimer = this.scheduleTimeout(() => {
930
- binding.viewerResizeTimer = null;
931
- const pending = binding.pendingViewerResize;
932
- binding.pendingViewerResize = null;
933
- if (!pending || binding.viewerViewportOwner !== pending.viewer) return;
934
- void this.handleViewerMessage(binding, pending.viewer, pending.geometry).catch(error => {
935
- if (pending.viewer.readyState === 1) {
936
- pending.viewer.send(JSON.stringify({
937
- type: 'browser-error',
938
- message: error?.message || 'Browser resize failed',
939
- }));
940
- }
941
- });
942
- }, VIEWER_RESIZE_SETTLE_MS);
943
- binding.viewerResizeTimer.unref?.();
944
- return Promise.resolve();
945
- }
946
-
947
- clearViewerResize(runtime) {
948
- if (runtime.viewerResizeTimer) this.cancelTimeout(runtime.viewerResizeTimer);
949
- runtime.viewerResizeTimer = null;
950
- runtime.pendingViewerResize = null;
951
- }
952
-
953
- releaseViewerState(runtime) {
954
- this.clearViewerResize(runtime);
955
- runtime.viewerGeometries?.clear?.();
956
- runtime.viewerViewportOwner = null;
957
- runtime.viewers?.clear?.();
958
- }
959
-
960
- async performViewerMessage(binding, viewer, message) {
961
- if (message.generation !== binding.generation || this.runtimes.get(binding.id) !== binding) {
962
- throw browserError('Browser Viewer generation is stale', 409, 'BROWSER_STALE_GENERATION');
963
- }
964
- const runtime = binding.session.runtime;
965
- if (message.type === 'resize') {
966
- if (binding.viewerViewportOwner !== viewer) return;
967
- await runtime.resize({
968
- width: message.width,
969
- height: message.height,
970
- deviceScaleFactor: message.deviceScaleFactor,
971
- });
972
- return;
973
- }
974
- if (message.type === 'pointer') {
975
- await runtime.pointer(message);
976
- return;
977
- }
978
- if (message.type === 'wheel') {
979
- await runtime.wheel(message);
980
- return;
981
- }
982
- if (message.type === 'key') {
983
- await runtime.press(message);
984
- return;
985
- }
986
- if (message.type === 'text') {
987
- await runtime.insertText(message.text);
988
- }
989
- }
990
-
991
- async dispose() {
992
- this.disposed = true;
993
- const sessions = [...this.sessions.values()];
994
- const results = await Promise.allSettled(sessions.map(session => session.runtime.close()));
995
- const failures = results
996
- .filter(result => result.status === 'rejected')
997
- .map(result => result.reason?.message || String(result.reason));
998
- if (failures.length > 0) {
999
- throw new Error(`Browser runtime cleanup failed: ${failures.join('; ')}`);
1000
- }
1001
- for (const binding of this.runtimes.values()) this.releaseViewerState(binding);
1002
- this.runtimes.clear();
1003
- this.sessions.clear();
1004
- }
1005
-
1006
- async stopAll() {
1007
- const ids = [...this.runtimes.keys()];
1008
- const results = [];
1009
- for (const id of ids) {
1010
- results.push(await Promise.resolve(this.stop(id))
1011
- .then(value => ({ status: 'fulfilled', value }))
1012
- .catch(reason => ({ status: 'rejected', reason })));
1013
- }
1014
- const failures = results
1015
- .filter(result => result.status === 'rejected')
1016
- .map(result => result.reason?.message || String(result.reason));
1017
- if (failures.length > 0) {
1018
- throw browserError(
1019
- `Browser extension could not stop every running Browser: ${failures.join('; ')}`,
1020
- 500,
1021
- 'BROWSER_DISABLE_FAILED',
1022
- );
1023
- }
1024
- }
1025
-
1026
- requireEnabled() {
1027
- if (this.isEnabled() !== true) {
1028
- throw browserError('Browser extension is disabled', 409, 'BROWSER_EXTENSION_DISABLED');
1029
- }
1030
- }
1031
-
1032
- requireAvailable() {
1033
- this.requireEnabled();
1034
- const executable = this.runtimeCapability;
1035
- if (!executable || executable.error) {
1036
- throw browserError(
1037
- executable?.error || 'Install Farming-managed Chromium, choose a system Chromium browser, or configure a loopback external CDP endpoint',
1038
- 503,
1039
- 'BROWSER_EXECUTABLE_NOT_FOUND',
1040
- );
1041
- }
1042
- }
1043
-
1044
- requireStored(id) {
1045
- if (!RESOURCE_ID_RE.test(String(id || ''))) {
1046
- throw browserError('Invalid Browser resource id');
1047
- }
1048
- const resource = this.store.get(id);
1049
- if (!resource) throw browserError('Browser resource not found', 404, 'BROWSER_NOT_FOUND');
1050
- return resource;
1051
- }
1052
-
1053
- enqueue(id, operation) {
1054
- const previous = this.operations.get(id) || Promise.resolve();
1055
- const next = previous.catch(() => {}).then(operation);
1056
- this.operations.set(id, next);
1057
- return next.finally(() => {
1058
- if (this.operations.get(id) === next) this.operations.delete(id);
1059
- });
1060
- }
1061
-
1062
- createBinding(session, resource) {
1063
- return {
1064
- id: resource.id,
1065
- generation: resource.generation,
1066
- session,
1067
- tabId: resource.tabId || '',
1068
- viewers: new Set(),
1069
- viewerGeometries: new Map(),
1070
- viewerViewportOwner: null,
1071
- viewerResizeTimer: null,
1072
- pendingViewerResize: null,
1073
- latestFrame: null,
1074
- };
1075
- }
1076
-
1077
- async activateBinding(binding) {
1078
- const { session } = binding;
1079
- if (!binding.tabId) throw browserError('Browser tab is unavailable', 409, 'BROWSER_TAB_UNAVAILABLE');
1080
- if (
1081
- session.runtime.activeTabId !== binding.tabId
1082
- || session.runtime.streamTabId !== binding.tabId
1083
- ) {
1084
- await session.runtime.switchTab(binding.tabId);
1085
- }
1086
- session.activeResourceId = binding.id;
1087
- }
1088
-
1089
- withRuntime(id, operation) {
1090
- const binding = this.runtimes.get(id);
1091
- const resource = this.requireStored(id);
1092
- if (!binding || resource.status !== 'running') {
1093
- throw browserError('Browser is not running', 409, 'BROWSER_NOT_RUNNING');
1094
- }
1095
- const { session } = binding;
1096
- const next = (session.actionChain || Promise.resolve())
1097
- .catch(() => {})
1098
- .then(async () => {
1099
- await this.activateBinding(binding);
1100
- return operation(session.runtime, binding);
1101
- });
1102
- session.actionChain = next;
1103
- return next;
1104
- }
1105
-
1106
- bindSession(session) {
1107
- const { runtime } = session;
1108
- runtime.on('process-identity', processIdentity => {
1109
- const owner = this.store.get(session.processOwnerResourceId);
1110
- if (
1111
- this.sessions.get(session.id) !== session
1112
- || !owner
1113
- || owner.sessionId && owner.sessionId !== session.id
1114
- ) return;
1115
- const next = this.store.update(owner.id, { processIdentity });
1116
- this.emitResource(next);
1117
- });
1118
- runtime.on('frame', frame => {
1119
- const binding = [...session.bindings.values()]
1120
- .find(candidate => candidate.tabId === runtime.streamTabId)
1121
- || session.bindings.get(session.activeResourceId);
1122
- if (!binding) return;
1123
- const resourceFrame = {
1124
- ...frame,
1125
- generation: binding.generation,
1126
- };
1127
- binding.latestFrame = resourceFrame;
1128
- for (const viewer of binding.viewers) {
1129
- if (viewer.readyState === 1 && (Number(viewer.bufferedAmount) || 0) <= MAX_VIEWER_BUFFER_BYTES) {
1130
- viewer.send(JSON.stringify(resourceFrame));
1131
- }
1132
- }
1133
- });
1134
- runtime.on('metadata', metadata => {
1135
- const binding = [...session.bindings.values()]
1136
- .find(candidate => candidate.tabId === runtime.activeTabId)
1137
- || session.bindings.get(session.activeResourceId);
1138
- if (binding) this.updateMetadata(binding, metadata);
1139
- });
1140
- runtime.on('tabs', event => {
1141
- if (session.initializing || session.closing) return;
1142
- const next = (session.actionChain || Promise.resolve())
1143
- .catch(() => {})
1144
- .then(() => this.reconcileTabs(session, event));
1145
- session.actionChain = next;
1146
- });
1147
- runtime.on('error', error => {
1148
- for (const binding of session.bindings.values()) {
1149
- for (const viewer of binding.viewers) {
1150
- if (viewer.readyState === 1) {
1151
- viewer.send(JSON.stringify({ type: 'browser-error', message: error?.message || 'Browser runtime failed' }));
1152
- }
1153
- }
1154
- }
1155
- });
1156
- runtime.once('exit', message => {
1157
- void this.handleRuntimeExit(session, message);
1158
- });
1159
- }
1160
-
1161
- async reconcileTabs(session, event) {
1162
- if (this.sessions.get(session.id) !== session || session.closing) return;
1163
- const tabs = Array.isArray(event?.tabs) ? event.tabs.filter(tab => tab.type === 'page') : [];
1164
- const newlyObservedTabIds = new Set(
1165
- Array.isArray(event?.newTabIds) ? event.newTabIds.map(String) : [],
1166
- );
1167
- const byTabId = new Map([...session.bindings.values()].map(binding => [binding.tabId, binding]));
1168
- const opener = session.bindings.get(session.activeResourceId) || null;
1169
- const opened = [];
1170
-
1171
- for (const tab of tabs) {
1172
- let binding = byTabId.get(tab.tabId);
1173
- if (
1174
- !binding
1175
- && newlyObservedTabIds.has(tab.tabId)
1176
- && (!session.runtime.externalCdpUrl || event.popupAdmitted)
1177
- ) {
1178
- session.runtime.ownedTabIds.add(tab.tabId);
1179
- const created = this.store.createRunningTab({
1180
- projectRootId: opener?.session.projectRootId || session.projectRootId,
1181
- workspace: this.store.get(opener?.id)?.workspace
1182
- || this.store.list().find(resource => resource.sessionId === session.id)?.workspace,
1183
- name: tabResourceName(tab),
1184
- url: tab.url,
1185
- title: tab.title,
1186
- browserKind: session.browserKind,
1187
- sessionId: session.id,
1188
- sessionGeneration: session.generation,
1189
- tabId: tab.tabId,
1190
- });
1191
- binding = this.createBinding(session, created);
1192
- session.bindings.set(created.id, binding);
1193
- this.runtimes.set(created.id, binding);
1194
- byTabId.set(tab.tabId, binding);
1195
- this.emitResource(created);
1196
- opened.push(publicResource(created, this.store.revision));
1197
- }
1198
- if (!binding) continue;
1199
- const current = this.store.get(binding.id);
1200
- if (!current || current.status !== 'running') continue;
1201
- if (current.url !== tab.url || current.title !== tab.title) {
1202
- const updated = this.store.update(binding.id, {
1203
- url: tab.url || current.url,
1204
- title: tab.title || '',
1205
- ...(current.autoName ? { name: tabResourceName(tab) } : {}),
1206
- });
1207
- this.emitResource(updated);
1208
- this.broadcastRuntimeState(binding);
1209
- }
1210
- }
1211
-
1212
- const liveTabIds = new Set(tabs.map(tab => tab.tabId));
1213
- for (const binding of [...session.bindings.values()]) {
1214
- if (liveTabIds.has(binding.tabId)) continue;
1215
- const current = this.store.get(binding.id);
1216
- if (!current || current.status === 'stopping') continue;
1217
- session.bindings.delete(binding.id);
1218
- this.runtimes.delete(binding.id);
1219
- if (session.processOwnerResourceId === binding.id && session.bindings.size > 0) {
1220
- const nextOwner = session.bindings.values().next().value;
1221
- session.processOwnerResourceId = nextOwner.id;
1222
- const transferred = this.store.update(nextOwner.id, {
1223
- processIdentity: current.processIdentity,
1224
- });
1225
- this.emitResource(transferred);
1226
- this.broadcastRuntimeState(nextOwner);
1227
- }
1228
- const stopped = this.store.update(binding.id, {
1229
- status: 'stopped',
1230
- tabId: '',
1231
- processIdentity: null,
1232
- error: '',
1233
- });
1234
- this.emitResource(stopped);
1235
- this.broadcastRuntimeState(binding);
1236
- this.releaseViewerState(binding);
1237
- }
1238
-
1239
- const activeTab = tabs.find(tab => tab.active);
1240
- const activeBinding = activeTab ? byTabId.get(activeTab.tabId) : null;
1241
- if (activeBinding) {
1242
- session.activeResourceId = activeBinding.id;
1243
- if (session.runtime.streamTabId !== activeBinding.tabId) {
1244
- await session.runtime.switchTab(activeBinding.tabId);
1245
- }
1246
- }
1247
- if (opened.length > 0 && opener) {
1248
- const message = JSON.stringify({
1249
- type: 'browser-tab-opened',
1250
- resource: opened.at(-1),
1251
- });
1252
- for (const viewer of opener.viewers) {
1253
- if (viewer.readyState === 1) viewer.send(message);
1254
- }
1255
- }
1256
- }
1257
-
1258
- updateMetadata(binding, metadata) {
1259
- const current = this.store.get(binding.id);
1260
- if (!current || current.generation !== binding.generation || !metadata) return;
1261
- const next = this.store.update(binding.id, {
1262
- url: String(metadata.url || current.url),
1263
- title: String(metadata.title || ''),
1264
- });
1265
- this.emitResource(next);
1266
- this.broadcastRuntimeState(binding);
1267
- }
1268
-
1269
- emitResource(resource) {
1270
- this.emit('resource', publicResource(resource, this.store.revision));
1271
- }
1272
-
1273
- broadcastRuntimeState(binding) {
1274
- const resource = this.store.get(binding.id);
1275
- if (!resource) return;
1276
- const message = JSON.stringify({
1277
- type: 'browser-state',
1278
- resource: publicResource(resource, this.store.revision),
1279
- });
1280
- for (const viewer of binding.viewers || []) {
1281
- if (viewer.readyState === 1) viewer.send(message);
1282
- }
1283
- }
1284
-
1285
- async handleRuntimeExit(session, message) {
1286
- if (this.sessions.get(session.id) !== session) return;
1287
- const failedBindings = [...session.bindings.values()];
1288
- for (const binding of failedBindings) {
1289
- const current = this.store.get(binding.id);
1290
- if (!current) continue;
1291
- const failed = this.store.update(binding.id, {
1292
- status: 'failed',
1293
- error: current.browserKind === 'external-cdp'
1294
- ? 'External Browser connection exited'
1295
- : message || 'Browser connection exited',
1296
- });
1297
- this.emitResource(failed);
1298
- this.broadcastRuntimeState(binding);
1299
- }
1300
- try {
1301
- await session.runtime.close();
1302
- this.sessions.delete(session.id);
1303
- for (const binding of failedBindings) {
1304
- this.runtimes.delete(binding.id);
1305
- this.releaseViewerState(binding);
1306
- const cleaned = this.store.update(binding.id, { processIdentity: null });
1307
- if (cleaned) this.emitResource(cleaned);
1308
- }
1309
- } catch (error) {
1310
- for (const binding of failedBindings) {
1311
- const current = this.store.get(binding.id);
1312
- if (!current) continue;
1313
- const cleanupFailed = this.store.update(binding.id, {
1314
- status: 'failed',
1315
- error: current.browserKind === 'external-cdp'
1316
- ? `${current.error}; target cleanup failed`
1317
- : `${current.error}; cleanup failed: ${error?.message || error}`,
1318
- });
1319
- this.emitResource(cleanupFailed);
1320
- this.broadcastRuntimeState(binding);
1321
- }
1322
- }
1323
- }
1324
- }
1325
-
1326
- module.exports = {
1327
- BrowserResourceManager,
1328
- browserError,
1329
- externalBrowserFailure,
1330
- normalizeUrl,
1331
- };