@lsamien/yaoyao 0.4.75

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 (320) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +6 -0
  3. package/README.md +103 -0
  4. package/THIRD_PARTY_NOTICES.md +16 -0
  5. package/bin/desktop-service-sync.mjs +43 -0
  6. package/bin/hermes-yaoyao-updater.mjs +315 -0
  7. package/bin/hermes-yaoyao.mjs +246 -0
  8. package/bin/lib/data-home.d.mts +4 -0
  9. package/bin/lib/data-home.mjs +24 -0
  10. package/bin/lib/data-migration.d.mts +2 -0
  11. package/bin/lib/data-migration.mjs +107 -0
  12. package/bin/lib/desktop-activation.d.mts +4 -0
  13. package/bin/lib/desktop-activation.mjs +18 -0
  14. package/bin/lib/managed-data-migration.mjs +45 -0
  15. package/bin/lib/release-source.d.mts +2 -0
  16. package/bin/lib/release-source.mjs +23 -0
  17. package/bin/lib/runtime-release.mjs +78 -0
  18. package/bin/lib/service-data.mjs +57 -0
  19. package/bin/lib/service-update.mjs +372 -0
  20. package/bin/migrate-data-home.mjs +20 -0
  21. package/build-info.json +657 -0
  22. package/desktop/main.mjs +679 -0
  23. package/dist/assets/AboutDialog-BvuJp8Pe.js +2 -0
  24. package/dist/assets/AboutDialog-BvuJp8Pe.js.map +1 -0
  25. package/dist/assets/AboutDialog-DC5YWX39.css +1 -0
  26. package/dist/assets/BotAutomationsView-Ddgs5Hes.js +2 -0
  27. package/dist/assets/BotAutomationsView-Ddgs5Hes.js.map +1 -0
  28. package/dist/assets/BotAutomationsView-DeJ-e3y5.css +1 -0
  29. package/dist/assets/BotPluginsDialog-Db5dTqvg.css +1 -0
  30. package/dist/assets/BotPluginsDialog-xPqUSyHS.js +2 -0
  31. package/dist/assets/BotPluginsDialog-xPqUSyHS.js.map +1 -0
  32. package/dist/assets/BotSettingsDialog-BkjoAZtf.css +1 -0
  33. package/dist/assets/BotSettingsDialog-wLz_KGzX.js +5 -0
  34. package/dist/assets/BotSettingsDialog-wLz_KGzX.js.map +1 -0
  35. package/dist/assets/ChatView-DRPu2nKr.js +2 -0
  36. package/dist/assets/ChatView-DRPu2nKr.js.map +1 -0
  37. package/dist/assets/ChatView-Dx8YlcPr.css +1 -0
  38. package/dist/assets/ChevronForwardOutline-D--GIQK6.js +2 -0
  39. package/dist/assets/ChevronForwardOutline-D--GIQK6.js.map +1 -0
  40. package/dist/assets/ComputerPanel-Byr2_yKj.js +2 -0
  41. package/dist/assets/ComputerPanel-Byr2_yKj.js.map +1 -0
  42. package/dist/assets/ComputerPanel-CQOv4v8E.css +1 -0
  43. package/dist/assets/ComputerViewerView-BBAs4bzi.css +1 -0
  44. package/dist/assets/ComputerViewerView-DJ6hB-5e.js +2 -0
  45. package/dist/assets/ComputerViewerView-DJ6hB-5e.js.map +1 -0
  46. package/dist/assets/ConversationsView-C_VZl5g2.css +1 -0
  47. package/dist/assets/ConversationsView-cu1Yrq68.js +6 -0
  48. package/dist/assets/ConversationsView-cu1Yrq68.js.map +1 -0
  49. package/dist/assets/FilesView-DAIzo9Ps.css +1 -0
  50. package/dist/assets/FilesView-h9oJFmZt.js +2 -0
  51. package/dist/assets/FilesView-h9oJFmZt.js.map +1 -0
  52. package/dist/assets/FloatingResourceSearch-BF2XOLd-.css +1 -0
  53. package/dist/assets/FloatingResourceSearch-TofG1_DV.js +9 -0
  54. package/dist/assets/FloatingResourceSearch-TofG1_DV.js.map +1 -0
  55. package/dist/assets/HistoryView-Bh0SU969.js +2 -0
  56. package/dist/assets/HistoryView-Bh0SU969.js.map +1 -0
  57. package/dist/assets/HistoryView-DvuCAjlo.css +1 -0
  58. package/dist/assets/KanbanView-B-2vG4w7.css +1 -0
  59. package/dist/assets/KanbanView-CcqMOzB7.js +2 -0
  60. package/dist/assets/KanbanView-CcqMOzB7.js.map +1 -0
  61. package/dist/assets/LocalVmSettingsPanel-C8PIgMr3.js +2 -0
  62. package/dist/assets/LocalVmSettingsPanel-C8PIgMr3.js.map +1 -0
  63. package/dist/assets/LocalVmSettingsPanel-Dedfhqlq.css +1 -0
  64. package/dist/assets/RunnerSettingsPanel-CfxxQKpV.css +1 -0
  65. package/dist/assets/RunnerSettingsPanel-CvNnWcdH.js +4 -0
  66. package/dist/assets/RunnerSettingsPanel-CvNnWcdH.js.map +1 -0
  67. package/dist/assets/StandaloneDialog-BbNWY6IJ.js +2 -0
  68. package/dist/assets/StandaloneDialog-BbNWY6IJ.js.map +1 -0
  69. package/dist/assets/StandaloneDialog-Bg5U9bMJ.css +1 -0
  70. package/dist/assets/UpdateCheckDialog-C357uDSE.js +2 -0
  71. package/dist/assets/UpdateCheckDialog-C357uDSE.js.map +1 -0
  72. package/dist/assets/UpdateCheckDialog-CRlyWnE7.css +1 -0
  73. package/dist/assets/WorkspaceKnowledgePanel-B6xMyHdp.css +1 -0
  74. package/dist/assets/WorkspaceKnowledgePanel-CE7qsu2i.js +2 -0
  75. package/dist/assets/WorkspaceKnowledgePanel-CE7qsu2i.js.map +1 -0
  76. package/dist/assets/WorkspaceRoutinesPanel-CLsHmBuH.css +1 -0
  77. package/dist/assets/WorkspaceRoutinesPanel-DybBh6PZ.js +2 -0
  78. package/dist/assets/WorkspaceRoutinesPanel-DybBh6PZ.js.map +1 -0
  79. package/dist/assets/WorkspaceShell-7wn8iTne.css +1 -0
  80. package/dist/assets/WorkspaceShell-kp1ObJTk.js +44 -0
  81. package/dist/assets/WorkspaceShell-kp1ObJTk.js.map +1 -0
  82. package/dist/assets/WorkspaceView-CtNI0_AO.js +2 -0
  83. package/dist/assets/WorkspaceView-CtNI0_AO.js.map +1 -0
  84. package/dist/assets/_plugin-vue_export-helper-CscYwSBt.js +3 -0
  85. package/dist/assets/_plugin-vue_export-helper-CscYwSBt.js.map +1 -0
  86. package/dist/assets/browser-B97PQaMt.js +11 -0
  87. package/dist/assets/browser-B97PQaMt.js.map +1 -0
  88. package/dist/assets/docx-preview-YvkiVUyQ.js +22 -0
  89. package/dist/assets/docx-preview-YvkiVUyQ.js.map +1 -0
  90. package/dist/assets/index-GQxxBKs2.js +17 -0
  91. package/dist/assets/index-GQxxBKs2.js.map +1 -0
  92. package/dist/assets/index-g5POnMkp.css +1 -0
  93. package/dist/assets/localVm-owThjmhy.js +2 -0
  94. package/dist/assets/localVm-owThjmhy.js.map +1 -0
  95. package/dist/assets/pdf-pqGpzpl1.js +55 -0
  96. package/dist/assets/pdf-pqGpzpl1.js.map +1 -0
  97. package/dist/assets/pdf.worker.min-iDqQPrd3.mjs +31 -0
  98. package/dist/assets/sessionOwnership-BTz0Fyp5.css +1 -0
  99. package/dist/assets/sessionOwnership-bedp16q1.js +6 -0
  100. package/dist/assets/sessionOwnership-bedp16q1.js.map +1 -0
  101. package/dist/assets/viewModels-BYFb-v4u.js +38 -0
  102. package/dist/assets/viewModels-BYFb-v4u.js.map +1 -0
  103. package/dist/assets/viewModels-CkZuSvKm.css +1 -0
  104. package/dist/brand/AppIcon-1024.png +0 -0
  105. package/dist/icons/apple-touch-icon.png +0 -0
  106. package/dist/icons/favicon-32.png +0 -0
  107. package/dist/icons/icon-192.png +0 -0
  108. package/dist/icons/icon-512.png +0 -0
  109. package/dist/icons/logo-64.png +0 -0
  110. package/dist/index.html +19 -0
  111. package/dist/manifest.webmanifest +21 -0
  112. package/dist/setting-previews/dark.png +0 -0
  113. package/dist/setting-previews/light.png +0 -0
  114. package/dist/setting-previews/system.png +0 -0
  115. package/dist-server/runner/agent.js +563 -0
  116. package/dist-server/runner/browser/installation.js +180 -0
  117. package/dist-server/runner/browser/publicProxy.js +157 -0
  118. package/dist-server/runner/browser/runtime.js +622 -0
  119. package/dist-server/runner/browser/types.js +8 -0
  120. package/dist-server/runner/computers/commandProcess.js +127 -0
  121. package/dist-server/runner/computers/compose.js +139 -0
  122. package/dist-server/runner/computers/computer-image/Dockerfile +101 -0
  123. package/dist-server/runner/computers/computer-image/Dockerfile.cursor +27 -0
  124. package/dist-server/runner/computers/computer-image/Dockerfile.network +9 -0
  125. package/dist-server/runner/computers/computer-image/compose_bridge.py +329 -0
  126. package/dist-server/runner/computers/computer-image/cursor-browser.sh +6 -0
  127. package/dist-server/runner/computers/computer-image/cursor-desktop.py +86 -0
  128. package/dist-server/runner/computers/computer-image/network_gateway.py +197 -0
  129. package/dist-server/runner/computers/computer-image/prepare-firefox.sh +11 -0
  130. package/dist-server/runner/computers/computer-image/skill_bundle.py +111 -0
  131. package/dist-server/runner/computers/computerFailures.js +30 -0
  132. package/dist-server/runner/computers/container.js +652 -0
  133. package/dist-server/runner/computers/dataSnapshot.js +62 -0
  134. package/dist-server/runner/computers/desktopClose.js +41 -0
  135. package/dist-server/runner/computers/imageCli.js +42 -0
  136. package/dist-server/runner/computers/imageManagement.js +321 -0
  137. package/dist-server/runner/computers/images.js +130 -0
  138. package/dist-server/runner/computers/localVm.js +270 -0
  139. package/dist-server/runner/computers/maintenance.js +96 -0
  140. package/dist-server/runner/computers/maintenanceCli.js +59 -0
  141. package/dist-server/runner/computers/migrateUserData.js +62 -0
  142. package/dist-server/runner/computers/pool.js +407 -0
  143. package/dist-server/runner/computers/third-party/openmausbot/LICENSE +202 -0
  144. package/dist-server/runner/computers/third-party/openmausbot/NOTICE +4 -0
  145. package/dist-server/runner/computers/userData.js +128 -0
  146. package/dist-server/runner/computers/workspaceRecovery.js +120 -0
  147. package/dist-server/runner/config.js +37 -0
  148. package/dist-server/runner/hermes-bots-bridge/README.md +102 -0
  149. package/dist-server/runner/hermes-bots-bridge/__init__.py +59 -0
  150. package/dist-server/runner/hermes-bots-bridge/bootstrap.py +31 -0
  151. package/dist-server/runner/hermes-bots-bridge/bridge_runtime.py +1179 -0
  152. package/dist-server/runner/hermes-bots-bridge/dashboard/bridge.js +2 -0
  153. package/dist-server/runner/hermes-bots-bridge/dashboard/manifest.json +9 -0
  154. package/dist-server/runner/hermes-bots-bridge/dashboard/plugin_api.py +132 -0
  155. package/dist-server/runner/hermes-bots-bridge/file_transfer.py +146 -0
  156. package/dist-server/runner/hermes-bots-bridge/model_settings.py +136 -0
  157. package/dist-server/runner/hermes-bots-bridge/plugin.yaml +4 -0
  158. package/dist-server/runner/hermes-bots-bridge/profile_runtime_repair.py +77 -0
  159. package/dist-server/runner/index.js +75 -0
  160. package/dist-server/runner/install-hermes-bridge.py +192 -0
  161. package/dist-server/runner/managedBrowser.js +266 -0
  162. package/dist-server/runner/network/computerProxy.js +117 -0
  163. package/dist-server/runner/network/managedProxy.js +96 -0
  164. package/dist-server/runner/network/publicDestination.js +47 -0
  165. package/dist-server/runner/network/socketBroker.js +131 -0
  166. package/dist-server/runner/network/upstreamProxy.js +118 -0
  167. package/dist-server/runner/worker/control.js +212 -0
  168. package/dist-server/runner/worker/fileTransfer.js +9 -0
  169. package/dist-server/runner/worker/gateway.js +1009 -0
  170. package/dist-server/runner/worker/guest_proxy.py +116 -0
  171. package/dist-server/runner/worker/hermes_worker.py +310 -0
  172. package/dist-server/runner/worker/hostTools.js +115 -0
  173. package/dist-server/runner/worker/process.js +123 -0
  174. package/dist-server/runner/worker/profileSession.js +144 -0
  175. package/dist-server/runner/worker/profile_skills.py +361 -0
  176. package/dist-server/runner/worker/skill_bundle.py +111 -0
  177. package/dist-server/runner/worker/skills.js +119 -0
  178. package/dist-server/runner/worker/taskEnvironment.js +35 -0
  179. package/dist-server/server/accountPairing.js +72 -0
  180. package/dist-server/server/allowedHostsConfiguration.js +170 -0
  181. package/dist-server/server/apns.js +261 -0
  182. package/dist-server/server/apnsConfiguration.js +298 -0
  183. package/dist-server/server/app.js +639 -0
  184. package/dist-server/server/botModelSettings.js +60 -0
  185. package/dist-server/server/botPlugins/connectedApps.js +213 -0
  186. package/dist-server/server/botPlugins/httpMcp.js +117 -0
  187. package/dist-server/server/botPlugins/stdioMcp.js +263 -0
  188. package/dist-server/server/botPlugins/workspacePlugins.js +353 -0
  189. package/dist-server/server/browserFiles.js +79 -0
  190. package/dist-server/server/buildIdentity.js +18 -0
  191. package/dist-server/server/chatCache.js +1651 -0
  192. package/dist-server/server/chatEventProjection.js +70 -0
  193. package/dist-server/server/chatTranscriptApi.js +145 -0
  194. package/dist-server/server/chatTranscriptStore.js +1021 -0
  195. package/dist-server/server/chatUnread.js +34 -0
  196. package/dist-server/server/codexAuthorization.js +149 -0
  197. package/dist-server/server/composeDesktops.js +69 -0
  198. package/dist-server/server/computerControls.js +122 -0
  199. package/dist-server/server/computerNames.js +41 -0
  200. package/dist-server/server/config.js +176 -0
  201. package/dist-server/server/dashboardController.js +120 -0
  202. package/dist-server/server/dashboardSupervisor.js +176 -0
  203. package/dist-server/server/desktopActivation.js +26 -0
  204. package/dist-server/server/desktopEnvironments.js +600 -0
  205. package/dist-server/server/desktopHostProtocol.js +17 -0
  206. package/dist-server/server/desktopHosts.js +117 -0
  207. package/dist-server/server/errors.js +12 -0
  208. package/dist-server/server/executionSettings.js +171 -0
  209. package/dist-server/server/fcm.js +247 -0
  210. package/dist-server/server/fcmConfiguration.js +270 -0
  211. package/dist-server/server/fileAccess.js +103 -0
  212. package/dist-server/server/fileTransfer.js +98 -0
  213. package/dist-server/server/githubReleases.js +73 -0
  214. package/dist-server/server/grokAuth.js +333 -0
  215. package/dist-server/server/grokCloud.js +458 -0
  216. package/dist-server/server/hermesBotRelay.js +117 -0
  217. package/dist-server/server/hermesBridge.js +245 -0
  218. package/dist-server/server/hostToolSettings.js +60 -0
  219. package/dist-server/server/imageManagement.js +55 -0
  220. package/dist-server/server/index.js +132 -0
  221. package/dist-server/server/leases.js +69 -0
  222. package/dist-server/server/localAuth.js +737 -0
  223. package/dist-server/server/localVm.js +358 -0
  224. package/dist-server/server/loopbackAuthorization.js +58 -0
  225. package/dist-server/server/managedBrowserTools.js +16 -0
  226. package/dist-server/server/managedBrowsers.js +735 -0
  227. package/dist-server/server/notificationText.js +125 -0
  228. package/dist-server/server/openVikingConfiguration.js +222 -0
  229. package/dist-server/server/openVikingMemoryProvider.js +279 -0
  230. package/dist-server/server/openVikingService.js +177 -0
  231. package/dist-server/server/openVikingSessionSync.js +286 -0
  232. package/dist-server/server/pairing.js +342 -0
  233. package/dist-server/server/profileIdentities.js +103 -0
  234. package/dist-server/server/pushCoordinator.js +1422 -0
  235. package/dist-server/server/pushEventAdapter.js +31 -0
  236. package/dist-server/server/pushEvents.js +1218 -0
  237. package/dist-server/server/realtimeApi.js +330 -0
  238. package/dist-server/server/realtimeBroker.js +835 -0
  239. package/dist-server/server/realtimeProtocol.js +353 -0
  240. package/dist-server/server/realtimeReceipts.js +60 -0
  241. package/dist-server/server/releases.js +46 -0
  242. package/dist-server/server/routes.js +2156 -0
  243. package/dist-server/server/runnerHub.js +687 -0
  244. package/dist-server/server/security.js +196 -0
  245. package/dist-server/server/serverIdentity.js +31 -0
  246. package/dist-server/server/serviceInstance.js +178 -0
  247. package/dist-server/server/sessionWorkingDirectory.js +39 -0
  248. package/dist-server/server/sharedComputers.js +221 -0
  249. package/dist-server/server/subaccountAccess.js +28 -0
  250. package/dist-server/server/taskCoordinator.js +580 -0
  251. package/dist-server/server/toolOperationJournal.js +81 -0
  252. package/dist-server/server/updateManager.js +340 -0
  253. package/dist-server/server/uploads.js +265 -0
  254. package/dist-server/server/upstream.js +375 -0
  255. package/dist-server/server/upstreamReadCache.js +133 -0
  256. package/dist-server/server/vmComputer.js +96 -0
  257. package/dist-server/server/websocket.js +753 -0
  258. package/dist-server/server/workspaceAssets.js +192 -0
  259. package/dist-server/server/workspaceCollaboration.js +224 -0
  260. package/dist-server/server/workspaceDiscussion.js +23 -0
  261. package/dist-server/server/workspaceEnvironment.js +43 -0
  262. package/dist-server/server/workspaceGateway.js +509 -0
  263. package/dist-server/server/workspaceInspector.js +47 -0
  264. package/dist-server/server/workspaceKnowledge.js +557 -0
  265. package/dist-server/server/workspaceKnowledgeRoutes.js +78 -0
  266. package/dist-server/server/workspaceKnowledgeTools.js +105 -0
  267. package/dist-server/server/workspaceMemoryContext.js +34 -0
  268. package/dist-server/server/workspaceMemorySynthesis.js +201 -0
  269. package/dist-server/server/workspaceMentions.js +31 -0
  270. package/dist-server/server/workspacePairedNode.js +166 -0
  271. package/dist-server/server/workspacePrompt.js +93 -0
  272. package/dist-server/server/workspaceRelay.js +90 -0
  273. package/dist-server/server/workspaceRemoteAgents.js +191 -0
  274. package/dist-server/server/workspaceRoutes.js +703 -0
  275. package/dist-server/server/workspaceRoutineTools.js +109 -0
  276. package/dist-server/server/workspaceRoutines.js +163 -0
  277. package/dist-server/server/workspaceRuntime.js +1363 -0
  278. package/dist-server/server/workspaceScheduler.js +592 -0
  279. package/dist-server/server/workspaceStore.js +1220 -0
  280. package/dist-server/server/workspaceSync.js +129 -0
  281. package/dist-server/server/workspaceTeamTools.js +312 -0
  282. package/dist-server/server/workspaceToolLease.js +280 -0
  283. package/dist-server/shared/agentIdentity.js +90 -0
  284. package/dist-server/shared/agentTasks.js +1 -0
  285. package/dist-server/shared/botEnvironment.js +28 -0
  286. package/dist-server/shared/botModelSettings.js +3 -0
  287. package/dist-server/shared/chatTools.js +32 -0
  288. package/dist-server/shared/chatTranscript.js +50 -0
  289. package/dist-server/shared/composeDesktops.js +1 -0
  290. package/dist-server/shared/computerControl.js +1 -0
  291. package/dist-server/shared/desktopEnvironment.js +1 -0
  292. package/dist-server/shared/desktopHost.js +1 -0
  293. package/dist-server/shared/executionEnvironment.js +1 -0
  294. package/dist-server/shared/fileTransfer.js +5 -0
  295. package/dist-server/shared/fileTransferEndpoint.mjs +133 -0
  296. package/dist-server/shared/grokAuth.js +1 -0
  297. package/dist-server/shared/hermesBridge.js +1 -0
  298. package/dist-server/shared/hostPaths.mjs +22 -0
  299. package/dist-server/shared/imageManagement.js +1 -0
  300. package/dist-server/shared/index.js +1 -0
  301. package/dist-server/shared/localVm.js +9 -0
  302. package/dist-server/shared/managedBrowser.js +1 -0
  303. package/dist-server/shared/messageFiles.js +90 -0
  304. package/dist-server/shared/openVikingSync.js +1 -0
  305. package/dist-server/shared/runner.js +2 -0
  306. package/dist-server/shared/serverFiles.js +55 -0
  307. package/dist-server/shared/serverIdentity.js +1 -0
  308. package/dist-server/shared/sse.js +47 -0
  309. package/dist-server/shared/types.js +8 -0
  310. package/dist-server/shared/workspace.js +61 -0
  311. package/dist-server/shared/workspaceKnowledge.js +1 -0
  312. package/dist-server/shared/workspaceLifecycle.js +1 -0
  313. package/dist-server/shared/workspaceMessagePatch.js +63 -0
  314. package/dist-server/shared/workspacePanels.js +1 -0
  315. package/dist-server/shared/workspacePlugins.js +1 -0
  316. package/licenses/LaoA-GrokBot/LICENSE +21 -0
  317. package/licenses/OpenMausBot/LICENSE +202 -0
  318. package/licenses/OpenMausBot/NOTICE +6 -0
  319. package/package.json +122 -0
  320. package/release.json +6 -0
@@ -0,0 +1,735 @@
1
+ import { createHash, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
2
+ import Router from '@koa/router';
3
+ import { z } from 'zod';
4
+ import { HttpError } from './errors.js';
5
+ import { readHostTools } from './hostToolSettings.js';
6
+ import { parse } from './workspaceStore.js';
7
+ import { ToolOperationJournal } from './toolOperationJournal.js';
8
+ const digest = (value) => createHash('sha256').update(value).digest('hex');
9
+ const credentials = z.object({ controlId: z.string().uuid(), token: z.string().min(32).max(256) }).passthrough();
10
+ /** Browser grants share Runner authentication, owner/source policy and task lifetime.
11
+ * They do not grant host/VM tools or reactivate the retired Electron browser path. */
12
+ export class ManagedBrowsers {
13
+ store;
14
+ auth;
15
+ nodes;
16
+ hub;
17
+ resources = new Map();
18
+ grants = new Map();
19
+ journal;
20
+ timer;
21
+ closed = false;
22
+ constructor(store, auth, nodes, hub) {
23
+ this.store = store;
24
+ this.auth = auth;
25
+ this.nodes = nodes;
26
+ this.hub = hub;
27
+ this.journal = new ToolOperationJournal(store);
28
+ this.timer = setInterval(() => void this.sweep(), 5000);
29
+ this.timer.unref();
30
+ }
31
+ agent(owner, id) {
32
+ if (this.closed || !readHostTools(this.store.home).managedBrowser)
33
+ throw new HttpError(409, '托管浏览器未启用', 'browser_disabled');
34
+ const agent = this.store.require(owner, 'agent', id);
35
+ if (agent.archived || agent.remoteAgentId)
36
+ throw new HttpError(409, '当前 Bot 没有托管浏览器', 'browser_unavailable');
37
+ this.nodes.requireSource(owner, agent);
38
+ return agent;
39
+ }
40
+ available(owner, agent) { try {
41
+ this.agent(owner, agent.id);
42
+ this.hub.browserRunner(owner, agent);
43
+ return true;
44
+ }
45
+ catch {
46
+ return false;
47
+ } }
48
+ resource(owner, id) {
49
+ const agent = this.agent(owner, id), runner = this.hub.browserRunner(owner, agent), key = owner + ':' + id;
50
+ let resource = this.resources.get(key), resetRequired = false;
51
+ if (resource && (resource.retired || resource.authVersion !== (this.auth.pushAuthorizationVersion(owner) ?? 0) || resource.runnerId !== runner.id || resource.runnerEpoch !== runner.browserEpoch || resource.agent.profile !== agent.profile || resource.agent.nodeId !== agent.nodeId)) {
52
+ // Source changes revoke every old holder. The old Runner observes the
53
+ // revoked grant; the current Runner must confirm a close before reuse.
54
+ this.retire(resource);
55
+ resetRequired = true;
56
+ this.resources.delete(key);
57
+ resource = undefined;
58
+ }
59
+ if (!resource) {
60
+ const scope = { ownerKey: digest(owner), environmentId: agent.id, profile: agent.temporaryGoalId ? 'temporary' : 'persistent' };
61
+ resource = { owner, agent, runnerId: runner.id, runnerEpoch: runner.browserEpoch, authVersion: this.auth.pushAuthorizationVersion(owner) ?? 0, scope, state: { open: false, generation: 1, profile: scope.profile, tabs: [], downloads: [] }, paused: false, resetRequired };
62
+ this.resources.set(key, resource);
63
+ }
64
+ return resource;
65
+ }
66
+ grant(resource, role, authorize, signal, expiresAt = Infinity) {
67
+ const grant = { id: randomUUID(), resource, role, authorize, signal, expiresAt, authVersion: this.auth.pushAuthorizationVersion(resource.owner) ?? 0 };
68
+ this.grants.set(grant.id, grant);
69
+ return grant;
70
+ }
71
+ check(grant) {
72
+ const r = grant.resource;
73
+ if (this.resources.get(r.owner + ':' + r.agent.id) !== r || this.grants.get(grant.id) !== grant || grant.expiresAt <= Date.now() || grant.signal?.aborted || !this.auth.isUserActive(r.owner) || (this.auth.pushAuthorizationVersion(r.owner) ?? 0) !== grant.authVersion)
74
+ throw new HttpError(410, '浏览器操作授权已结束', 'browser_authorization_revoked');
75
+ this.checkResource(r);
76
+ grant.authorize();
77
+ }
78
+ checkResource(r) {
79
+ if (r.retired || this.resources.get(r.owner + ':' + r.agent.id) !== r || !this.auth.isUserActive(r.owner) || (this.auth.pushAuthorizationVersion(r.owner) ?? 0) !== r.authVersion)
80
+ throw new HttpError(410, '浏览器操作授权已结束', 'browser_authorization_revoked');
81
+ const agent = this.agent(r.owner, r.agent.id), runner = this.hub.browserRunner(r.owner, agent);
82
+ if (agent.nodeId !== r.agent.nodeId || agent.profile !== r.agent.profile || runner.id !== r.runnerId || runner.browserEpoch !== r.runnerEpoch)
83
+ throw new HttpError(410, '浏览器执行来源已改变', 'browser_source_changed');
84
+ }
85
+ retire(r) {
86
+ for (const [id, g] of this.grants)
87
+ if (g.resource === r)
88
+ this.grants.delete(id);
89
+ r.retired = true;
90
+ r.task = undefined;
91
+ r.human = undefined;
92
+ r.session = undefined;
93
+ r.preparation = undefined;
94
+ r.paused = false;
95
+ r.notify?.();
96
+ }
97
+ dropSession(r) { if (r.session)
98
+ this.grants.delete(r.session.id); r.session = undefined; r.parked = false; }
99
+ keepSession(r) {
100
+ if (!r.forceClose && r.scope.profile === 'persistent' && this.hub.supportsBrowserRetention(r.owner, r.agent))
101
+ r.session ??= this.grant(r, 'session', () => { });
102
+ }
103
+ transition(r, action) {
104
+ const pending = (r.transition ?? Promise.resolve()).catch(() => { }).then(action);
105
+ r.transition = pending;
106
+ void pending.finally(() => { if (r.transition === pending)
107
+ r.transition = undefined; }).catch(() => { });
108
+ return pending;
109
+ }
110
+ async rest(r, retain) {
111
+ this.checkResource(r);
112
+ r.frame = undefined;
113
+ r.frames?.clear();
114
+ r.paused = false;
115
+ if (retain && !r.forceClose && r.scope.profile === 'persistent' && r.state.open && this.hub.supportsBrowserRetention(r.owner, r.agent)) {
116
+ const session = r.session ??= this.grant(r, 'session', () => { });
117
+ try {
118
+ const state = await this.request(session, 'park');
119
+ if (!state || typeof state.open !== 'boolean' || !Number.isInteger(state.generation))
120
+ throw new HttpError(502, '浏览器未确认页面保留', 'browser_park_unconfirmed');
121
+ if (r.state.open) {
122
+ r.parked = true;
123
+ r.nextStatusAt = Date.now() + 30000;
124
+ }
125
+ else
126
+ this.dropSession(r);
127
+ return;
128
+ }
129
+ catch {
130
+ this.dropSession(r);
131
+ }
132
+ }
133
+ this.dropSession(r);
134
+ try {
135
+ await this.view(r, g => this.request(g, 'close'));
136
+ r.forceClose = false;
137
+ }
138
+ catch (error) {
139
+ r.resetRequired = true;
140
+ throw error;
141
+ }
142
+ }
143
+ async activate(g) {
144
+ while (g.resource.parked) {
145
+ await this.waitForControl(g);
146
+ await this.transition(g.resource, async () => {
147
+ const r = g.resource;
148
+ this.check(g);
149
+ if (r.paused || !r.parked)
150
+ return;
151
+ await this.request(g, 'resume');
152
+ r.parked = false;
153
+ r.frame = undefined;
154
+ r.frames?.clear();
155
+ });
156
+ }
157
+ }
158
+ allowed(runnerId, scope, grantId) {
159
+ if (!scope || typeof scope !== 'object')
160
+ return false;
161
+ const s = scope;
162
+ const matches = (g) => g.resource.runnerId === runnerId && g.resource.scope.ownerKey === s.ownerKey && g.resource.scope.environmentId === s.environmentId && g.resource.scope.profile === s.profile;
163
+ const valid = (g) => { try {
164
+ this.check(g);
165
+ return true;
166
+ }
167
+ catch {
168
+ return false;
169
+ } };
170
+ if (grantId) {
171
+ const g = this.grants.get(grantId);
172
+ return !!g && (g.role !== 'session' || g.parking === true) && matches(g) && valid(g);
173
+ }
174
+ return [...this.grants.values()].some(g => g.role !== 'prepare' && matches(g) && valid(g));
175
+ }
176
+ async request(grant, op, data = {}) {
177
+ this.check(grant);
178
+ if (grant.role === 'session' && op !== 'park')
179
+ throw new HttpError(403, '保留会话不授权浏览器操作', 'browser_tool_forbidden');
180
+ if (grant.role === 'task' && !['status', 'close', 'prepare', 'resume'].includes(op))
181
+ await this.waitForControl(grant);
182
+ const r = grant.resource;
183
+ if (r.resetRequired) {
184
+ r.resetting ??= (async () => {
185
+ const result = await this.hub.browser(r.owner, r.agent, { scope: r.scope, grantId: grant.id, op: 'close' }, () => this.check(grant));
186
+ r.state = result;
187
+ r.resetRequired = false;
188
+ })().finally(() => { r.resetting = undefined; });
189
+ await r.resetting;
190
+ this.check(grant);
191
+ }
192
+ if (grant.role === 'session')
193
+ grant.parking = true;
194
+ try {
195
+ const result = await this.hub.browser(r.owner, r.agent, { scope: r.scope, grantId: grant.id, op, ...data }, () => this.check(grant));
196
+ if (result && typeof result.open === 'boolean' && Number.isInteger(result.generation) && result.generation >= r.state.generation) {
197
+ r.state = result;
198
+ if (!r.state.open)
199
+ this.dropSession(r);
200
+ else if (op === 'open' && (grant.role === 'task' || grant.role === 'human'))
201
+ this.keepSession(r);
202
+ r.notify?.();
203
+ }
204
+ return result;
205
+ }
206
+ finally {
207
+ grant.parking = false;
208
+ }
209
+ }
210
+ async waitForControl(g) {
211
+ while (g.resource.paused) {
212
+ this.check(g);
213
+ await new Promise((resolve, reject) => {
214
+ const stop = () => { clearTimeout(timer); reject(new HttpError(410, '浏览器任务已停止', 'browser_authorization_revoked')); };
215
+ const timer = setTimeout(() => { g.signal?.removeEventListener('abort', stop); resolve(); }, 250);
216
+ g.signal?.addEventListener('abort', stop, { once: true });
217
+ if (g.signal?.aborted) {
218
+ g.signal.removeEventListener('abort', stop);
219
+ stop();
220
+ }
221
+ });
222
+ }
223
+ this.check(g);
224
+ }
225
+ async view(r, action) {
226
+ const grant = this.grant(r, 'view', () => { }, undefined, Date.now() + 30000);
227
+ try {
228
+ return await action(grant);
229
+ }
230
+ finally {
231
+ this.grants.delete(grant.id);
232
+ }
233
+ }
234
+ controlStatus(r) {
235
+ return { backend: 'managed-browser', hostName: '托管浏览器', mode: r.taking ? 'pausing' : r.paused ? (r.human ? 'human' : 'pausing') : r.task ? 'agent' : r.state.open ? 'idle' : 'off', generation: r.state.generation, ...(r.human ? { controlId: r.human.id } : {}), canResume: !!r.task };
236
+ }
237
+ async state(owner, id) {
238
+ const enabled = readHostTools(this.store.home).managedBrowser === true;
239
+ try {
240
+ const r = this.resource(owner, id);
241
+ await this.view(r, g => this.request(g, 'status'));
242
+ this.finishPreparation(r);
243
+ return this.publicState(r);
244
+ }
245
+ catch (error) {
246
+ return { enabled, available: false, reason: error instanceof Error ? error.message : '浏览器不可用', open: false, generation: 0, profile: 'persistent', tabs: [], downloads: [] };
247
+ }
248
+ }
249
+ publicState(r) { return { enabled: true, ...r.state, supportsRetention: this.hub.supportsBrowserRetention(r.owner, r.agent), available: r.state.available ?? true, ...(r.state.available === false ? { reason: r.state.installation?.message ?? '浏览器环境尚未就绪' } : {}) }; }
250
+ finishPreparation(r) {
251
+ if (r.preparation && ['ready', 'failed'].includes(r.state.installation?.status ?? '')) {
252
+ this.grants.delete(r.preparation.id);
253
+ r.preparation = undefined;
254
+ }
255
+ }
256
+ async prepare(owner, id, retry = false) {
257
+ const r = this.resource(owner, id);
258
+ await this.view(r, g => this.request(g, 'status'));
259
+ if (r.state.available !== false) {
260
+ this.finishPreparation(r);
261
+ return this.publicState(r);
262
+ }
263
+ if (r.preparation) {
264
+ try {
265
+ this.check(r.preparation);
266
+ }
267
+ catch {
268
+ this.grants.delete(r.preparation.id);
269
+ r.preparation = undefined;
270
+ }
271
+ }
272
+ const g = r.preparation ??= this.grant(r, 'prepare', () => { }, undefined, Date.now() + 600000);
273
+ try {
274
+ await this.request(g, 'prepare', { retry });
275
+ this.finishPreparation(r);
276
+ return this.publicState(r);
277
+ }
278
+ catch (error) {
279
+ if (r.preparation === g) {
280
+ this.grants.delete(g.id);
281
+ r.preparation = undefined;
282
+ }
283
+ throw error;
284
+ }
285
+ }
286
+ async ensureReady(g) {
287
+ await this.request(g, 'status');
288
+ if (g.resource.state.available !== false)
289
+ return;
290
+ await this.request(g, 'prepare');
291
+ const deadline = Date.now() + 540000;
292
+ while (g.resource.state.available === false) {
293
+ this.check(g);
294
+ const installation = g.resource.state.installation;
295
+ if (installation?.status === 'failed')
296
+ throw new HttpError(409, installation.error || installation.message, 'browser_install_failed');
297
+ if (Date.now() >= deadline)
298
+ throw new HttpError(504, '浏览器环境准备超时,请在卡片中检查状态后重试', 'browser_install_timeout');
299
+ await new Promise((resolve, reject) => {
300
+ const stop = () => { clearTimeout(timer); reject(new HttpError(410, '浏览器任务已停止', 'browser_authorization_revoked')); };
301
+ const timer = setTimeout(() => { g.signal?.removeEventListener('abort', stop); resolve(); }, 750);
302
+ g.signal?.addEventListener('abort', stop, { once: true });
303
+ if (g.signal?.aborted) {
304
+ g.signal.removeEventListener('abort', stop);
305
+ stop();
306
+ }
307
+ });
308
+ await this.request(g, 'status');
309
+ }
310
+ }
311
+ token(owner, id, value) {
312
+ const input = parse(credentials, value), grant = this.grants.get(input.controlId);
313
+ if (!grant || grant.role !== 'human' || grant.resource.owner !== owner || grant.resource.agent.id !== id || !grant.tokenHash || !timingSafeEqual(Buffer.from(grant.tokenHash, 'hex'), Buffer.from(digest(input.token), 'hex')))
314
+ throw new HttpError(403, '需要当前浏览器控制凭据', 'browser_control_forbidden');
315
+ this.check(grant);
316
+ if (grant.resource.human !== grant)
317
+ throw new HttpError(410, '浏览器控制权已改变', 'browser_control_expired');
318
+ return grant;
319
+ }
320
+ async download(grant, id) {
321
+ const parts = [];
322
+ let offset = 0, size, sha256 = '', name = '', mimeType = 'application/octet-stream';
323
+ do {
324
+ const reply = await this.request(grant, 'download', { downloadId: id, offset });
325
+ if (!Number.isSafeInteger(reply.size) || reply.size < 0 || reply.size > 25 * 1024 * 1024 || reply.offset !== offset || typeof reply.data !== 'string' || reply.data.length > 710000 || !/^[a-f0-9]{64}$/.test(reply.sha256))
326
+ throw new HttpError(502, '下载分块无效', 'browser_download_invalid');
327
+ if (size !== undefined && (size !== reply.size || sha256 !== reply.sha256 || name !== reply.name))
328
+ throw new HttpError(502, '下载文件在传输时改变', 'browser_download_changed');
329
+ size = reply.size;
330
+ sha256 = reply.sha256;
331
+ name = reply.name;
332
+ mimeType = reply.mimeType;
333
+ const chunk = Buffer.from(reply.data, 'base64');
334
+ if (chunk.toString('base64') !== reply.data || chunk.length !== Math.min(512 * 1024, size - offset))
335
+ throw new HttpError(502, '下载分块不完整', 'browser_download_invalid');
336
+ parts.push(chunk);
337
+ offset += chunk.length;
338
+ } while (offset < size);
339
+ const buffer = Buffer.concat(parts);
340
+ if (createHash('sha256').update(buffer).digest('hex') !== sha256)
341
+ throw new HttpError(502, '下载校验失败', 'browser_download_invalid');
342
+ return { name, mimeType, buffer };
343
+ }
344
+ openTurn(owner, agent, options) {
345
+ let grant, finished = false, activated = false, closing, failure, lastCard = '', lastTitle, lastUrl, listener;
346
+ const notify = (r) => {
347
+ if (!options.onCard)
348
+ return;
349
+ const tab = r.state.tabs.find(tab => tab.active);
350
+ let url;
351
+ try {
352
+ const parsed = new URL(tab?.url ?? '');
353
+ if (['https:', 'http:'].includes(parsed.protocol)) {
354
+ parsed.username = '';
355
+ parsed.password = '';
356
+ parsed.search = '';
357
+ parsed.hash = '';
358
+ url = parsed.href.slice(0, 2000);
359
+ }
360
+ }
361
+ catch { }
362
+ if (tab) {
363
+ lastTitle = tab.title.slice(0, 240);
364
+ lastUrl = url;
365
+ }
366
+ if ((r.retired || finished && !r.human && !r.session) && r.notify === listener)
367
+ r.notify = undefined;
368
+ const status = r.retired ? 'closed' : failure ? 'failed' : finished && !r.human ? (r.session && r.state.open ? 'idle' : 'closed') : r.state.available === false ? 'preparing' : r.state.open ? 'active' : 'ready';
369
+ const { updatedAt: _updated, ...installation } = r.state.installation ?? { updatedAt: 0 };
370
+ const body = { id: options.workId, agentId: agent.id, agentName: agent.name, status, title: lastTitle, url: lastUrl,
371
+ message: r.retired ? '浏览器执行来源已改变,本轮会话已结束' : failure ?? (status === 'idle' ? '本轮操作已结束,页面已保留' : status === 'closed' ? '本轮浏览器操作已结束' : r.human ? (finished ? (r.session && !r.forceClose ? '人工控制中,交还后保留页面' : '人工控制中,交还后结束本轮会话') : '人工控制中,可交还机器人继续') : r.paused ? '接管已过期,请重新接管后交还机器人' : r.state.installation?.message), installation: r.state.installation };
372
+ const signature = JSON.stringify({ ...body, installation });
373
+ if (signature === lastCard)
374
+ return;
375
+ // Chat persistence is an observer; a deleted history row or storage error
376
+ // must never block control handoff, authorization cleanup, or the sweep.
377
+ try {
378
+ if (options.onCard({ ...body, updatedAt: Date.now() }) !== false)
379
+ lastCard = signature;
380
+ }
381
+ catch { }
382
+ };
383
+ const get = async () => {
384
+ options.authorize();
385
+ options.signal.throwIfAborted();
386
+ if (finished)
387
+ throw new HttpError(410, '浏览器任务已结束', 'browser_authorization_revoked');
388
+ if (!grant) {
389
+ const r = this.resource(owner, agent.id);
390
+ while (r.transition) {
391
+ await r.transition.catch(() => { });
392
+ options.authorize();
393
+ options.signal.throwIfAborted();
394
+ if (finished)
395
+ throw new HttpError(410, '浏览器任务已结束', 'browser_authorization_revoked');
396
+ }
397
+ this.checkResource(r);
398
+ if (r.task)
399
+ throw new HttpError(409, '当前 Bot 浏览器正由另一个任务使用', 'browser_busy');
400
+ r.notify?.();
401
+ if (!r.human)
402
+ r.forceClose = false;
403
+ grant = this.grant(r, 'task', options.authorize, options.signal);
404
+ r.task = grant;
405
+ listener = () => notify(r);
406
+ r.notify = listener;
407
+ }
408
+ this.check(grant);
409
+ return grant;
410
+ };
411
+ const close = (value = {}) => {
412
+ if (finished)
413
+ return closing ?? Promise.resolve();
414
+ finished = true;
415
+ options.signal.removeEventListener('abort', abort);
416
+ if (!grant)
417
+ return Promise.resolve();
418
+ const g = grant, r = g.resource;
419
+ this.grants.delete(g.id);
420
+ if (r.task === g)
421
+ r.task = undefined;
422
+ const retain = value.retain !== false && !options.signal.aborted;
423
+ if (!retain) {
424
+ r.forceClose = true;
425
+ this.dropSession(r);
426
+ }
427
+ closing = this.transition(r, async () => {
428
+ try {
429
+ this.checkResource(r);
430
+ if (r.human) {
431
+ try {
432
+ this.check(r.human);
433
+ return;
434
+ }
435
+ catch {
436
+ this.grants.delete(r.human.id);
437
+ r.human = undefined;
438
+ }
439
+ }
440
+ // A status-only turn must not refresh the retained session's idle deadline.
441
+ if (retain && !activated && r.session && r.parked)
442
+ return;
443
+ await this.rest(r, retain);
444
+ }
445
+ catch { /* Revoked resources are fenced and reclaimed by the Runner. */ }
446
+ finally {
447
+ notify(r);
448
+ }
449
+ }).finally(() => { if (r.closing === closing)
450
+ r.closing = undefined; });
451
+ r.closing = closing;
452
+ return closing;
453
+ };
454
+ const abort = () => { void close({ retain: false }); };
455
+ options.signal.addEventListener('abort', abort, { once: true });
456
+ return { close, call: async (name, raw, callId) => {
457
+ const g = await get(), r = g.resource;
458
+ notify(r);
459
+ try {
460
+ // Hold the current tool call while the user operates this exact session.
461
+ await this.waitForControl(g);
462
+ if (name !== 'managed_browser_state') {
463
+ await this.activate(g);
464
+ activated = true;
465
+ }
466
+ const args = z.record(z.string(), z.unknown()).parse(raw ?? {});
467
+ const result = await this.journal.execute(owner, options.workId, callId, name, args, () => this.check(g), async () => {
468
+ if (name === 'managed_browser_state')
469
+ return this.request(g, 'status');
470
+ if (name === 'managed_browser_open') {
471
+ const body = z.object({ url: z.string().optional() }).strict().parse(args);
472
+ await this.ensureReady(g);
473
+ await this.request(g, 'open');
474
+ if (body.url)
475
+ await this.request(g, 'execute', { operation: { generation: r.state.generation, operationId: callId ?? randomUUID(), action: { kind: 'navigate', url: body.url } } });
476
+ return this.request(g, 'status');
477
+ }
478
+ if (name === 'managed_browser_export' || name === 'managed_browser_to_vm') {
479
+ const body = z.object({ downloadId: z.string().uuid(), path: z.string().optional(), overwrite: z.boolean().default(false) }).strict().parse(args);
480
+ const file = await this.download(g, body.downloadId);
481
+ if (name === 'managed_browser_export')
482
+ return options.publish(file.name, file.buffer);
483
+ if (!options.toVm || !body.path)
484
+ throw new HttpError(403, '本轮未开放虚拟机文件传输', 'browser_vm_unavailable');
485
+ return options.toVm(file, body.path, body.overwrite);
486
+ }
487
+ let action, upload;
488
+ if (name === 'managed_browser_upload' || name === 'managed_browser_upload_vm') {
489
+ const body = z.object({ fileId: z.string().optional(), path: z.string().optional(), snapshotId: z.string().uuid(), ref: z.string() }).strict().parse(args);
490
+ let file;
491
+ if (name === 'managed_browser_upload') {
492
+ if (!body.fileId || body.path)
493
+ throw new HttpError(400, '请选择附件编号', 'browser_upload_invalid');
494
+ file = await options.upload(body.fileId);
495
+ }
496
+ else {
497
+ if (!body.path || body.fileId || !options.fromVm)
498
+ throw new HttpError(403, '本轮未开放虚拟机文件传输', 'browser_vm_unavailable');
499
+ file = await options.fromVm(body.path);
500
+ }
501
+ const id = randomUUID();
502
+ upload = { id, name: file.name, mimeType: file.mimeType, data: file.buffer.toString('base64') };
503
+ action = { kind: 'upload', snapshotId: body.snapshotId, ref: body.ref, fileId: id };
504
+ }
505
+ else if (name === 'managed_browser_snapshot')
506
+ action = { kind: 'snapshot' };
507
+ else if (name === 'managed_browser_action') {
508
+ action = z.object({ action: z.record(z.string(), z.unknown()) }).strict().parse(args).action;
509
+ if (action.kind === 'pointer')
510
+ throw new HttpError(400, '机器人拖动请使用 drag 动作', 'browser_input_unsupported');
511
+ }
512
+ else
513
+ throw new HttpError(403, '本轮未授权此浏览器工具', 'browser_tool_forbidden');
514
+ const value = await this.request(g, 'execute', { operation: { generation: r.state.generation, operationId: callId ?? randomUUID(), action }, ...(upload ? { upload } : {}) });
515
+ if (name === 'managed_browser_action' && !['snapshot', 'screenshot', 'downloads', 'state'].includes(String(action?.kind)))
516
+ await this.request(g, 'status');
517
+ if (value?.mimeType === 'image/png' && typeof value.data === 'string')
518
+ return { content: [{ type: 'image', mimeType: 'image/png', data: value.data }, { type: 'text', text: JSON.stringify({ width: value.width, height: value.height, generation: value.generation }) }] };
519
+ return value;
520
+ });
521
+ failure = undefined;
522
+ notify(r);
523
+ if (r.notes) {
524
+ const notes = r.notes;
525
+ r.notes = undefined;
526
+ return { result, humanNote: notes, instruction: '用户刚交还浏览器;重新读取页面后继续。' };
527
+ }
528
+ return result;
529
+ }
530
+ catch (error) {
531
+ failure = error instanceof Error ? error.message : '浏览器操作失败';
532
+ notify(r);
533
+ throw error;
534
+ }
535
+ } };
536
+ }
537
+ router() {
538
+ const router = new Router(), matches = (ctx) => ctx.query.backend === 'managed-browser';
539
+ router.get('/api/app/agents/:id/managed-browser', async (ctx) => { const owner = this.auth.require(ctx).id; this.store.require(owner, 'agent', ctx.params.id); ctx.set('Cache-Control', 'no-store'); ctx.body = await this.state(owner, ctx.params.id); });
540
+ router.post('/api/app/agents/:id/managed-browser/prepare', async (ctx) => { const owner = this.auth.require(ctx).id, body = parse(z.object({ retry: z.boolean().default(false) }).strict(), ctx.request.body ?? {}); ctx.body = await this.prepare(owner, ctx.params.id, body.retry); });
541
+ router.get('/api/app/agents/:id/computer', async (ctx, next) => { if (!matches(ctx))
542
+ return next(); const r = this.resource(this.auth.require(ctx).id, ctx.params.id); await this.view(r, g => this.request(g, 'status')); ctx.body = this.controlStatus(r); });
543
+ router.get('/api/app/agents/:id/computer/frame', async (ctx, next) => { if (!matches(ctx))
544
+ return next(); const r = this.resource(this.auth.require(ctx).id, ctx.params.id); const shot = await this.view(r, g => this.request(g, 'execute', { operation: { generation: r.state.generation, operationId: randomUUID(), action: { kind: 'screenshot' } } })); r.frame = { id: shot.frameId, generation: shot.generation, data: shot.data, width: shot.width, height: shot.height, capturedAt: shot.createdAt }; r.frames ??= new Map(); const { data: _data, ...metadata } = r.frame; r.frames.set(metadata.id, metadata); for (const [id, frame] of r.frames)
545
+ if (frame.capturedAt < Date.now() - 30000 || r.frames.size > 32)
546
+ r.frames.delete(id); ctx.set('Cache-Control', 'no-store'); ctx.body = r.frame; });
547
+ router.post('/api/app/agents/:id/computer/take', async (ctx, next) => {
548
+ if (!matches(ctx))
549
+ return next();
550
+ const r = this.resource(this.auth.require(ctx).id, ctx.params.id), body = parse(z.object({ requestId: z.string().uuid() }).strict(), ctx.request.body);
551
+ ctx.body = await this.transition(r, async () => {
552
+ await this.view(r, g => this.request(g, 'status'));
553
+ if (r.state.available === false)
554
+ throw new HttpError(409, '浏览器环境尚未就绪,请先等待自动准备完成', 'browser_preparing');
555
+ if (r.human && r.human.expiresAt > Date.now()) {
556
+ this.check(r.human);
557
+ if (r.human.requestId !== body.requestId)
558
+ throw new HttpError(409, '浏览器已由另一页面接管', 'browser_control_busy');
559
+ if (r.taking)
560
+ await r.taking;
561
+ if (!r.human)
562
+ throw new HttpError(409, '接管未完成,请重新接管', 'browser_control_expired');
563
+ return { ...this.controlStatus(r), controlId: r.human.id, token: this.nodes.open(r.human.sealedToken), expiresAt: r.human.expiresAt };
564
+ }
565
+ if (r.human)
566
+ this.grants.delete(r.human.id);
567
+ const token = randomBytes(32).toString('base64url'), g = this.grant(r, 'human', () => { }, undefined, Date.now() + 30000);
568
+ Object.assign(g, { requestId: body.requestId, tokenHash: digest(token), sealedToken: this.nodes.seal(token) });
569
+ r.human = g;
570
+ r.paused = true;
571
+ r.taking = (async () => { await this.request(g, 'pause'); await this.request(g, 'open'); r.frame = undefined; r.frames?.clear(); r.notify?.(); })();
572
+ try {
573
+ await r.taking;
574
+ r.parked = false;
575
+ r.taking = undefined;
576
+ return { ...this.controlStatus(r), controlId: g.id, token, expiresAt: g.expiresAt };
577
+ }
578
+ catch (error) {
579
+ this.grants.delete(g.id);
580
+ if (r.human === g)
581
+ r.human = undefined;
582
+ r.notify?.();
583
+ throw error;
584
+ }
585
+ finally {
586
+ r.taking = undefined;
587
+ }
588
+ });
589
+ });
590
+ router.post('/api/app/agents/:id/computer/renew', (ctx, next) => { if (!matches(ctx))
591
+ return next(); const g = this.token(this.auth.require(ctx).id, ctx.params.id, ctx.request.body); g.expiresAt = Date.now() + 30000; ctx.body = { expiresAt: g.expiresAt }; });
592
+ const input = async (owner, id, raw, navigation) => {
593
+ const body = parse(credentials.extend({ requestId: z.string().uuid(), generation: z.number().int().positive(), frameId: z.string().uuid().optional(), action: z.record(z.string(), z.unknown()) }).strict(), raw), g = this.token(owner, id, body), r = g.resource;
594
+ return this.journal.execute(owner, g.id, body.requestId, 'managed_browser_human_input', { generation: body.generation, frameId: body.frameId, action: body.action, navigation }, () => { this.token(owner, id, body); }, async () => {
595
+ if (r.taking || r.transition)
596
+ throw new HttpError(409, '请等待当前操作结束后接管', 'browser_control_pending');
597
+ if (body.generation !== r.state.generation)
598
+ throw new HttpError(409, '控制代次已改变,请刷新', 'browser_generation_expired');
599
+ let action = body.action;
600
+ if (navigation && action.kind === 'pointer')
601
+ throw new HttpError(400, '连续拖动需要画面与人工控制凭据', 'browser_input_unsupported');
602
+ if (!navigation) {
603
+ const frame = r.frames?.get(body.frameId ?? '');
604
+ const cancelling = action.kind === 'pointer' && action.phase === 'cancel';
605
+ if (!cancelling && (!frame || frame.generation !== body.generation || frame.capturedAt < Date.now() - 30000))
606
+ throw new HttpError(409, '画面已改变,请刷新后操作', 'browser_frame_stale');
607
+ const a = body.action;
608
+ const x = z.number().finite().min(0).max(Math.min(1279, (frame?.width ?? 1280) - 1)), y = z.number().finite().min(0).max(Math.min(799, (frame?.height ?? 800) - 1));
609
+ if (a.kind === 'click')
610
+ action = { kind: 'coordinate', x: a.x, y: a.y, ...(a.button ? { button: a.button } : {}), ...(a.count ? { clickCount: a.count } : {}) };
611
+ else if (a.kind === 'drag')
612
+ action = parse(z.object({ kind: z.literal('drag'), fromX: x, fromY: y, toX: x, toY: y }).strict(), a);
613
+ else if (a.kind === 'pointer')
614
+ action = parse(z.object({ kind: z.literal('pointer'), gestureId: z.string().uuid(), phase: z.enum(['start', 'move', 'end', 'cancel']), x, y }).strict(), a);
615
+ else if (a.kind === 'key') {
616
+ const names = { Return: 'Enter', BackSpace: 'Backspace', Up: 'ArrowUp', Down: 'ArrowDown', Left: 'ArrowLeft', Right: 'ArrowRight', space: 'Space' };
617
+ const modifiers = z.array(z.enum(['ctrl', 'alt', 'shift', 'super'])).max(4).parse(a.modifiers ?? []), key = z.string().max(40).parse(a.key);
618
+ action = { kind: 'key', key: [...modifiers.map(m => ({ ctrl: 'Control', alt: 'Alt', shift: 'Shift', super: 'Meta' })[m]), names[key] ?? key].join('+') };
619
+ }
620
+ else if (a.kind === 'scroll') {
621
+ const direction = z.enum(['up', 'down', 'left', 'right']).parse(a.direction), amount = z.number().int().min(1).max(50).parse(a.amount ?? 3) * 80;
622
+ action = { kind: 'scroll', deltaX: direction === 'left' ? -amount : direction === 'right' ? amount : 0, deltaY: direction === 'up' ? -amount : direction === 'down' ? amount : 0 };
623
+ }
624
+ else if (a.kind !== 'text')
625
+ throw new HttpError(422, '托管浏览器暂不支持此输入', 'browser_input_unsupported');
626
+ }
627
+ const value = await this.request(g, 'execute', { operation: { generation: body.generation, operationId: body.requestId, action } });
628
+ // Recent frames remain usable between phases of the same held gesture.
629
+ if (action.kind !== 'pointer' || !['start', 'move'].includes(String(action.phase))) {
630
+ r.frame = undefined;
631
+ r.frames?.clear();
632
+ }
633
+ return value;
634
+ });
635
+ };
636
+ router.post('/api/app/agents/:id/computer/input', async (ctx, next) => { if (!matches(ctx))
637
+ return next(); ctx.body = await input(this.auth.require(ctx).id, ctx.params.id, ctx.request.body, false); });
638
+ router.post('/api/app/agents/:id/managed-browser/action', async (ctx) => { ctx.body = await input(this.auth.require(ctx).id, ctx.params.id, ctx.request.body, true); });
639
+ router.post('/api/app/agents/:id/computer/giveback', async (ctx, next) => {
640
+ if (!matches(ctx))
641
+ return next();
642
+ const owner = this.auth.require(ctx).id, body = parse(credentials.extend({ notes: z.string().max(4000).default('') }).strict(), ctx.request.body), g = this.token(owner, ctx.params.id, body), r = g.resource;
643
+ ctx.body = await this.transition(r, async () => {
644
+ this.token(owner, ctx.params.id, body);
645
+ // Keep the manual grant alive until the runner confirms the generation handoff.
646
+ if (r.task)
647
+ await this.request(r.task, 'resume');
648
+ else
649
+ await this.rest(r, true);
650
+ r.notes = body.notes;
651
+ r.human = undefined;
652
+ r.paused = false;
653
+ r.frame = undefined;
654
+ r.frames?.clear();
655
+ this.grants.delete(g.id);
656
+ r.notify?.();
657
+ return this.controlStatus(r);
658
+ });
659
+ });
660
+ router.post('/api/app/agents/:id/managed-browser/close', async (ctx) => {
661
+ const owner = this.auth.require(ctx).id, body = parse(credentials, ctx.request.body), g = this.token(owner, ctx.params.id, body), r = g.resource;
662
+ ctx.body = await this.transition(r, async () => {
663
+ this.token(owner, ctx.params.id, body);
664
+ if (r.task)
665
+ throw new HttpError(409, '机器人任务仍在使用浏览器,请先停止任务', 'browser_busy');
666
+ await this.rest(r, false);
667
+ this.grants.delete(g.id);
668
+ r.human = undefined;
669
+ r.paused = false;
670
+ r.notes = undefined;
671
+ r.notify?.();
672
+ return this.controlStatus(r);
673
+ });
674
+ });
675
+ return router;
676
+ }
677
+ async sweep() {
678
+ for (const r of this.resources.values()) {
679
+ try {
680
+ this.checkResource(r);
681
+ }
682
+ catch {
683
+ this.retire(r);
684
+ continue;
685
+ }
686
+ if (r.task) {
687
+ try {
688
+ this.check(r.task);
689
+ }
690
+ catch {
691
+ this.grants.delete(r.task.id);
692
+ r.task = undefined;
693
+ r.forceClose = true;
694
+ this.dropSession(r);
695
+ }
696
+ }
697
+ if (r.human) {
698
+ let valid = true;
699
+ try {
700
+ this.check(r.human);
701
+ }
702
+ catch {
703
+ valid = false;
704
+ }
705
+ if (!valid) {
706
+ this.grants.delete(r.human.id);
707
+ r.human = undefined;
708
+ r.paused = !!r.task;
709
+ r.frame = undefined;
710
+ r.frames?.clear();
711
+ if (!r.task)
712
+ await this.transition(r, async () => { if (!r.task && !r.human)
713
+ await this.rest(r, true); }).catch(() => { });
714
+ }
715
+ }
716
+ if (r.preparation) {
717
+ try {
718
+ this.check(r.preparation);
719
+ }
720
+ catch {
721
+ this.grants.delete(r.preparation.id);
722
+ r.preparation = undefined;
723
+ }
724
+ }
725
+ if (r.session && !r.task && !r.human && !r.transition && !r.refreshing && Date.now() >= (r.nextStatusAt ?? 0)) {
726
+ r.nextStatusAt = Date.now() + 30000;
727
+ r.refreshing = this.transition(r, async () => { if (!r.task && !r.human && r.session)
728
+ await this.view(r, g => this.request(g, 'status')); })
729
+ .then(() => { }, () => this.retire(r)).finally(() => { r.refreshing = undefined; });
730
+ }
731
+ r.notify?.();
732
+ }
733
+ }
734
+ close() { this.closed = true; clearInterval(this.timer); this.grants.clear(); this.resources.clear(); }
735
+ }