@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,1363 @@
1
+ import { isLocalAuthorizationTarget } from './loopbackAuthorization.js';
2
+ import {} from './managedBrowsers.js';
3
+ import { ToolOperationJournal } from './toolOperationJournal.js';
4
+ import { browserOwnedFile, browserVmFile } from './browserFiles.js';
5
+ import {} from './desktopEnvironments.js';
6
+ import {} from './grokCloud.js';
7
+ import { VmToolSession } from './vmComputer.js';
8
+ import { randomUUID } from 'node:crypto';
9
+ import { setTimeout as delay } from 'node:timers/promises';
10
+ import { readFileSync } from 'node:fs';
11
+ import { z } from 'zod';
12
+ import { WorkspaceStore, parse } from './workspaceStore.js';
13
+ import { WorkspaceNodes, WorkspaceGateway } from './workspaceGateway.js';
14
+ import { HttpError } from './errors.js';
15
+ import { applyWorkingDirectory, configuredWorkingDirectory } from './sessionWorkingDirectory.js';
16
+ import {} from './workspaceAssets.js';
17
+ import { UploadStore } from './uploads.js';
18
+ import { buildWorkspacePrompt } from './workspacePrompt.js';
19
+ import { buildWorkspaceEnvironment, workspaceEnvironmentTools } from './workspaceEnvironment.js';
20
+ import { readHostTools } from './hostToolSettings.js';
21
+ import { resolveBotModelSettings, applyBotModelSettings, botModelTarget, BotModelConfirmationError } from './botModelSettings.js';
22
+ function globalComputers(home) {
23
+ try {
24
+ return readHostTools(home);
25
+ }
26
+ catch {
27
+ return { denyServerTools: false, approvalPolicy: 'ask', scriptMachine: false, serverComputer: false, vm: false, cloud: false, fileTransferMaxMiB: 25 };
28
+ }
29
+ }
30
+ function estimateTokens(text) {
31
+ let units = 0;
32
+ for (const ch of text)
33
+ units += (ch.codePointAt(0) ?? 0) > 0xff ? 1 : 0.25;
34
+ return Math.ceil(units);
35
+ }
36
+ import { WorkspaceScheduler, NO_REPLY, HOST_FALLBACK, WORKSPACE_CONCURRENCY_LIMIT, RESOURCE_WAIT_CODES } from './workspaceScheduler.js';
37
+ import { mentionedAgents } from './workspaceMentions.js';
38
+ import { WorkspaceTeamTools, TEAM_TOOL_RULES } from './workspaceTeamTools.js';
39
+ import { WorkspaceRoutineTools, ROUTINE_TOOL_RULES } from './workspaceRoutineTools.js';
40
+ import { createWorkspaceToolLease } from './workspaceToolLease.js';
41
+ import { WorkspaceTaskCoordinator } from './taskCoordinator.js';
42
+ import { isDiscussion, discussionRounds } from './workspaceDiscussion.js';
43
+ import { WorkspaceKnowledge } from './workspaceKnowledge.js';
44
+ import { emptyMemoryContext, memoryResetReason, memoryDelta, acknowledgeMemory } from './workspaceMemoryContext.js';
45
+ import { WorkspaceCollaboration } from './workspaceCollaboration.js';
46
+ import { WorkspaceKnowledgeTools, BOT_KNOWLEDGE_RULES } from './workspaceKnowledgeTools.js';
47
+ export { mentionedAgents } from './workspaceMentions.js';
48
+ const deviceHostId = z.union([
49
+ z.literal('local'),
50
+ z.string().uuid(),
51
+ ]);
52
+ export const sendInput = z
53
+ .object({
54
+ requestId: z.string().uuid(),
55
+ content: z.string().max(65_536).default(''),
56
+ taskId: z.string().uuid().optional(),
57
+ mode: z.enum(['chat', 'goal']).optional(),
58
+ rounds: z.number().int().min(1).max(12).optional(),
59
+ coordinatorId: z.string().uuid().optional(),
60
+ projectId: z.string().min(1).max(100).nullable().optional(),
61
+ mentionIds: z.array(z.string().uuid()).max(8).default([]),
62
+ fileIds: z.array(z.string().uuid()).max(8).default([]),
63
+ /** Computer the client is messaging from: 'local' or paired computer uuid. */
64
+ deviceHost: deviceHostId.nullish(),
65
+ })
66
+ .strict()
67
+ .refine((b) => b.content.trim() || b.fileIds.length, '请输入消息或添加附件');
68
+ export class WorkspaceRuntime extends WorkspaceScheduler {
69
+ nodes;
70
+ uploads;
71
+ authorizationVersion;
72
+ knowledge;
73
+ openViking;
74
+ collaboration;
75
+ knowledgeTools;
76
+ onMemoryCandidate = () => { };
77
+ executionTurns = new Map();
78
+ activeExecutionTurns() { return [...this.executionTurns.values()]; }
79
+ executionSettings;
80
+ plugins;
81
+ managedBrowsers;
82
+ operationJournal;
83
+ assertCanSubmit = () => { };
84
+ get idleForUpdate() {
85
+ return this.live.size === 0 && this.executing.size === 0 && !this.store.db.prepare("SELECT 1 FROM workspace_entities WHERE kind IN ('run','turn') AND COALESCE(json_extract(data,'$.status'),'unknown') NOT IN ('complete','failed','interrupted') LIMIT 1").get();
86
+ }
87
+ desktopEnvironments;
88
+ cloud;
89
+ /** Wired to the runner hub: false degrades envs VM turns to profile sessions. */
90
+ computerAvailable;
91
+ inspector;
92
+ live = new Map();
93
+ teamTools;
94
+ routineTools;
95
+ tasks;
96
+ retireHelper = async () => { throw new Error('电脑清理服务未连接'); };
97
+ publishArtifact = () => { throw new Error('产物服务未初始化'); };
98
+ onTeamCreated = () => { };
99
+ constructor(store, nodes, uploads, userActive = () => true, authorizationVersion = () => 0, openViking) {
100
+ super(store, userActive);
101
+ this.nodes = nodes;
102
+ this.uploads = uploads;
103
+ this.authorizationVersion = authorizationVersion;
104
+ this.operationJournal = new ToolOperationJournal(store);
105
+ this.openViking = openViking;
106
+ this.teamTools = new WorkspaceTeamTools(store, nodes, this);
107
+ this.tasks = new WorkspaceTaskCoordinator(store, this);
108
+ this.knowledge = new WorkspaceKnowledge(store.home, store, openViking);
109
+ this.collaboration = new WorkspaceCollaboration(store, this);
110
+ this.knowledgeTools = new WorkspaceKnowledgeTools(this);
111
+ this.onRunSettled = (owner, run) => {
112
+ this.collaboration.settled(owner, run);
113
+ if (run.status === 'complete' && (!run.triggerKind || run.triggerKind === 'peer'))
114
+ queueMicrotask(() => { if (!this.closing)
115
+ this.onMemoryCandidate(owner, run); });
116
+ };
117
+ }
118
+ async bindNewAgent(owner, id) {
119
+ if (!this.openViking?.enabled)
120
+ return;
121
+ await this.openViking.ensureUser(owner, { id, temporaryGoalId: undefined });
122
+ }
123
+ async cleanupAgent(owner, id) {
124
+ if (!this.openViking)
125
+ return;
126
+ await this.openViking.removeUser(owner, { id, temporaryGoalId: undefined });
127
+ }
128
+ send(owner, conversationId, input) {
129
+ return this.submit(owner, conversationId, input);
130
+ }
131
+ async botCapabilities(owner, agent, target = this.nodes.target(owner, agent.nodeId)) {
132
+ try {
133
+ const response = await target.session.request('/api/plugins/yaoyao-bot-bridge/capabilities', { search: new URLSearchParams({ profile: agent.profile }) });
134
+ const value = JSON.parse(response.body.toString());
135
+ const tools = response.status === 200 && value.ready === true && value.native_tools === true && value.in_process === true;
136
+ return { tools, memory: tools && value.memory_isolation === true, extraction: value.memory_extraction === true };
137
+ }
138
+ catch (error) {
139
+ if (error instanceof HttpError && RESOURCE_WAIT_CODES.has(error.code ?? ''))
140
+ throw error;
141
+ return { tools: false, memory: false, extraction: false };
142
+ }
143
+ }
144
+ async stopPeerRun(owner, id) { await super.stop(owner, id); }
145
+ async preemptPeerWork(owner, agentId, exceptRunId) {
146
+ const ids = [...new Set(this.store.list(owner, 'turn').filter(w => w.agentId === agentId && w.runId !== exceptRunId && ['running', 'waiting'].includes(w.status)).map(w => w.runId))];
147
+ for (const id of ids)
148
+ if (this.store.get(owner, 'run', id)?.triggerKind)
149
+ await super.stop(owner, id).catch(() => { });
150
+ }
151
+ async stop(owner, id) {
152
+ const root = this.store.require(owner, 'run', id);
153
+ await this.collaboration.stopFor(owner, chain => chain.rootRunId === id || chain.id === root.collaborationChainId);
154
+ await super.stop(owner, id);
155
+ }
156
+ /** Server-owned provenance. This is never exposed as a model-supplied identity. */
157
+ dispatch(owner, conversationId, input, source) {
158
+ this.nodes.requireSource(owner, this.store.require(owner, 'agent', source.agentId));
159
+ return this.submit(owner, conversationId, input, source);
160
+ }
161
+ files(owner, ids) { return ids.map(id => { const file = this.store.get(owner, 'file', id); if (file) {
162
+ if (file.sourceNodeId && file.profile)
163
+ this.nodes.requireSource(owner, { nodeId: file.sourceNodeId, profile: file.profile });
164
+ return file;
165
+ } return { ...this.uploads.records([id], owner)[0], sender: 'user' }; }); }
166
+ submit(owner, conversationId, input, source) {
167
+ if (!this.userActive(owner))
168
+ throw new HttpError(403, '账号授权已失效', 'account_inactive');
169
+ this.assertCanSubmit();
170
+ const body = parse(sendInput, input);
171
+ for (const id of this.store.require(owner, 'conversation', conversationId).memberIds)
172
+ this.nodes.requireSource(owner, this.store.require(owner, 'agent', id));
173
+ const result = this.store.command(owner, body.requestId, { conversationId, ...body, ...(source ? { source } : {}) }, () => {
174
+ const c = this.store.require(owner, 'conversation', conversationId);
175
+ if (c.archived)
176
+ throw new HttpError(409, '聊天已归档', 'conversation_archived');
177
+ const projectId = source?.kind === 'peer' ? source.projectId : c.kind === 'group' ? c.projectId : body.projectId ?? undefined;
178
+ if (projectId)
179
+ for (const id of source?.targetAgentId ? [source.targetAgentId] : c.memberIds)
180
+ this.knowledge.requireProjectMember(owner, projectId, id);
181
+ const conversationTask = this.store.resolveTask(owner, conversationId, body.taskId), conversationTaskId = conversationTask?.id;
182
+ if (conversationTaskId) {
183
+ const alreadyActive = this.store.list(owner, 'run').some(run => run.conversationTaskId === conversationTaskId && !['complete', 'failed', 'interrupted'].includes(run.status));
184
+ if (!alreadyActive && this.store.activeTaskCount(owner, conversationId) >= WORKSPACE_CONCURRENCY_LIMIT)
185
+ throw new HttpError(409, `最多同时运行 ${WORKSPACE_CONCURRENCY_LIMIT} 个任务`, 'workspace_task_concurrency_limit');
186
+ }
187
+ if (body.mentionIds.some((a) => !this.store.taskMemberIds(owner, c, conversationTaskId).includes(a)))
188
+ throw new HttpError(400, '只能 @ 群内成员', 'invalid_mentions');
189
+ const records = this.files(owner, body.fileIds);
190
+ const now = Date.now(), runId = randomUUID(), agents = this.store.taskMemberIds(owner, c, conversationTaskId).map((id) => this.store.require(owner, 'agent', id));
191
+ let goal = conversationTaskId ? this.store.get(owner, 'goal', conversationTaskId) : undefined;
192
+ if (body.mode === 'goal') {
193
+ if (source || c.kind !== 'group' || !conversationTask || !body.content.trim())
194
+ throw new HttpError(400, '请在群聊中说明需要交付的结果', 'goal_request_invalid');
195
+ if (goal)
196
+ throw new HttpError(409, '当前话题已有目标,请继续原目标或新建话题', 'goal_exists');
197
+ if (body.coordinatorId) {
198
+ if (!c.memberIds.includes(body.coordinatorId))
199
+ throw new HttpError(400, '负责人需要是群成员', 'invalid_members');
200
+ c.administratorId = body.coordinatorId;
201
+ }
202
+ const coordinator = this.store.require(owner, 'agent', c.administratorId);
203
+ if (coordinator.temporaryGoalId || coordinator.archived || coordinator.remoteAgentId)
204
+ throw new HttpError(403, '负责人需要是本机上未归档的 Bot', 'goal_forbidden');
205
+ if (body.coordinatorId)
206
+ this.store.put(owner, 'conversation', c.id, c);
207
+ if (this.store.list(owner, 'run').some(r => r.conversationTaskId === conversationTaskId && !['complete', 'failed', 'interrupted'].includes(r.status)))
208
+ throw new HttpError(409, '请等待当前回复结束后再启动目标', 'goal_busy');
209
+ goal = this.tasks.begin(owner, conversationTask, coordinator, body.content.trim(), { conversationId, conversationTaskId, runId, agentId: coordinator.id });
210
+ }
211
+ const mentions = [
212
+ ...new Set([...body.mentionIds, ...mentionedAgents(body.content, agents)]),
213
+ ];
214
+ const message = {
215
+ id: randomUUID(),
216
+ conversationId,
217
+ conversationTaskId,
218
+ seq: 0,
219
+ role: source ? 'system' : 'user',
220
+ peerMessageId: source?.peerMessageId,
221
+ ...(source?.taskReference ? { taskReference: source.taskReference } : {}),
222
+ ...(source ? { agentId: source.agentId, agentName: this.store.require(owner, 'agent', source.agentId).name } : {}),
223
+ ...((source ? source.deviceHost : body.deviceHost) ? { deviceHost: (source ? source.deviceHost : body.deviceHost) } : {}),
224
+ content: body.content.trim(),
225
+ reasoning: '',
226
+ runId,
227
+ status: 'complete',
228
+ attachments: records.map((f) => ({
229
+ id: f.id,
230
+ name: f.name,
231
+ mimeType: f.mimeType,
232
+ size: f.size,
233
+ sender: f.sender,
234
+ createdAt: now,
235
+ })),
236
+ tools: [],
237
+ createdAt: now,
238
+ };
239
+ this.store.saveMessage(owner, message);
240
+ for (const file of records) {
241
+ const existing = this.store.get(owner, 'file', file.id);
242
+ if (existing && !existing.messageId)
243
+ this.store.put(owner, 'file', file.id, {
244
+ ...existing,
245
+ conversationId,
246
+ messageId: message.id,
247
+ });
248
+ }
249
+ const run = {
250
+ id: runId,
251
+ conversationId,
252
+ conversationTaskId,
253
+ messageId: message.id,
254
+ ...((source ? source.deviceHost : body.deviceHost) ? { deviceHost: (source ? source.deviceHost : body.deviceHost) } : {}),
255
+ mentionIds: mentions,
256
+ activeAgentId: c.administratorId,
257
+ status: 'queued',
258
+ round: 0,
259
+ createdAt: now,
260
+ updatedAt: now,
261
+ authorizationVersion: this.authorizationVersion(owner),
262
+ projectId,
263
+ peerMessageId: source?.peerMessageId,
264
+ collaborationChainId: source?.collaborationChainId,
265
+ priority: source?.priority,
266
+ ...(source ? { assignmentId: source.assignmentId, targetAgentId: source.targetAgentId, triggerKind: source.kind, internalInstruction: source.instruction } : {}),
267
+ ...(source?.kind !== 'peer' && goal && ['running', 'review', 'waiting'].includes(goal.status) ? { goalId: goal.id, targetAgentId: source?.targetAgentId ?? goal.coordinatorId } : {}),
268
+ };
269
+ if (isDiscussion(c) && !run.goalId && !run.assignmentId && !source?.targetAgentId)
270
+ run.discussion = { memberIds: mentions.length ? mentions : [...c.memberIds], rounds: discussionRounds(body.content, body.rounds) };
271
+ this.admit(owner, run, c, message);
272
+ this.uploads.markReferenced(body.fileIds, owner);
273
+ return run;
274
+ });
275
+ this.wake();
276
+ return this.store.require(owner, 'run', result.id);
277
+ }
278
+ async performTurn(owner, c, agent, run, recovering = false) {
279
+ this.requireAuthorization(owner, run.runId);
280
+ this.store.requireAgentTask(owner, agent, c.id, run.conversationTaskId);
281
+ this.nodes.requireSource(owner, agent);
282
+ if (agent.remoteAgentId)
283
+ throw new HttpError(410, '远程机器人已停用', 'remote_agent_removed');
284
+ const key = this.bindingKey(c.id, run.conversationTaskId, agent.id), chatExecution = 'profile', target = this.nodes.target(owner, agent.nodeId);
285
+ const execution = this.executionSettings?.selection();
286
+ const systemTurn = this.executionSettings?.openTurn(owner, agent.id);
287
+ let vmTools;
288
+ let browserTurn;
289
+ const gateway = new WorkspaceGateway(target, { workId: run.id, publishArtifact: async (name, bytes) => {
290
+ this.requireAuthorization(owner, run.runId);
291
+ this.nodes.requireSource(owner, agent);
292
+ const file = this.publishArtifact(owner, resultMessage, agent, name, bytes);
293
+ if (!resultMessage.attachments.some(item => item.id === file.id))
294
+ resultMessage.attachments.push(file);
295
+ this.store.saveMessage(owner, resultMessage);
296
+ return { ...file, url: `/api/app/files/${file.id}/download` };
297
+ }, authorize: () => {
298
+ this.requireAuthorization(owner, run.runId);
299
+ this.nodes.requireSource(owner, agent);
300
+ const current = this.getWork(owner, run.id), latest = this.store.require(owner, 'agent', agent.id), conversation = this.store.require(owner, 'conversation', c.id);
301
+ if (this.closing || conversation.archived || !this.store.taskMemberIds(owner, conversation, run.conversationTaskId).includes(agent.id) || this.store.require(owner, 'run', run.runId).stopRequested || current.cancelRequested || ['interrupted', 'complete', 'failed'].includes(current.status) || latest.archived || latest.computerEnvironmentId !== agent.computerEnvironmentId || (latest.vmExecution ?? 'worker') !== (agent.vmExecution ?? 'worker') || (latest.allowHostEnvironment === true) !== (agent.allowHostEnvironment === true) || (latest.execution ?? 'profile') !== (agent.execution ?? 'profile') || latest.teamAuthorizationVersion !== agent.teamAuthorizationVersion)
302
+ throw new HttpError(403, '本轮机器人或任务授权已结束', 'run_authorization_revoked');
303
+ } });
304
+ gateway.onTrace = entry => this.inspector?.record(owner, c.id, { ...entry, agentId: agent.id, runId: run.runId, taskId: run.conversationTaskId });
305
+ const botCapabilities = await this.botCapabilities(owner, agent, target);
306
+ const root = this.store.require(owner, 'run', run.runId);
307
+ if (root.peerMessageId && !recovering) {
308
+ const peer = this.store.require(owner, 'peer-message', root.peerMessageId);
309
+ const sender = this.store.require(owner, 'agent', peer.fromAgentId);
310
+ if (sender.archived || peer.status === 'stopped')
311
+ throw new HttpError(403, 'Bot 协作权限已撤销', 'collaboration_forbidden');
312
+ this.nodes.requireSource(owner, sender);
313
+ }
314
+ const memory = botCapabilities.memory && !recovering ? await this.knowledge.context(owner, agent.id, root.projectId) : emptyMemoryContext('unsupported');
315
+ const memoryStatus = botCapabilities.memory ? 'ready' : 'upgrade_required';
316
+ if (agent.memoryStatus !== memoryStatus) {
317
+ agent = { ...agent, memoryStatus };
318
+ this.store.put(owner, 'agent', agent.id, agent);
319
+ this.store.event(owner, 'agent.changed', this.store.agentSummary(agent));
320
+ }
321
+ let binding = this.store.get(owner, 'binding', key);
322
+ const memoryReset = !recovering && binding
323
+ ? binding.memoryPending ? 'memory_admission_uncertain' : memoryResetReason(memory, binding.memoryState, binding.memoryVersion)
324
+ : undefined;
325
+ const sourceReset = !!this.store.get(owner, 'binding-reset', key);
326
+ const movedRunner = sourceReset || !!binding && (binding.runnerId !== target.runner?.id || (binding.execution ?? 'profile') !== chatExecution || !!binding.hermesComputer !== !!target.runner?.hermesComputer);
327
+ // Rebuild old exclusive-environment sessions once: their Hermes Agent may
328
+ // still retain restricted native context even after a new tool binding.
329
+ const resetReason = (execution && (binding?.executionRevision !== execution.revision || binding?.executionPolicyVersion !== 2) ? 'execution_environment_changed' : undefined) ?? memoryReset ?? (sourceReset ? 'source_changed' : movedRunner ? 'runner_changed' : undefined);
330
+ if (resetReason) {
331
+ if (recovering)
332
+ throw new HttpError(409, '执行节点已变化,不能在另一节点重放原执行', 'runner_target_changed');
333
+ this.inspector?.record(owner, c.id, { method: 'bot.session-reset', direction: 'event', agentId: agent.id, runId: run.runId, taskId: run.conversationTaskId,
334
+ data: { reason: resetReason } });
335
+ binding = undefined;
336
+ }
337
+ let message = run.currentMessageId
338
+ ? this.store.require(owner, 'message', run.currentMessageId)
339
+ : undefined;
340
+ if (!message) {
341
+ message = {
342
+ id: randomUUID(),
343
+ conversationId: c.id,
344
+ conversationTaskId: run.conversationTaskId,
345
+ seq: 0,
346
+ role: 'assistant',
347
+ execution: chatExecution,
348
+ agentId: agent.id,
349
+ agentName: agent.name,
350
+ content: '',
351
+ reasoning: '',
352
+ status: 'streaming',
353
+ runId: run.runId,
354
+ taskId: run.id,
355
+ visible: run.replyMode !== 'automatic' || run.requiredReply,
356
+ tools: [],
357
+ attachments: [],
358
+ createdAt: Date.now(),
359
+ };
360
+ run.currentMessageId = message.id;
361
+ this.store.atomic(() => {
362
+ this.store.saveMessage(owner, message);
363
+ this.saveWork(owner, run);
364
+ });
365
+ }
366
+ if (!recovering && message.status === 'queued') {
367
+ message.status = 'streaming';
368
+ message.error = undefined;
369
+ message.visible = run.replyMode !== 'automatic' || run.requiredReply;
370
+ }
371
+ const resultMessage = message;
372
+ let submitted = recovering, settled = false, completedEvidence = false, completing = false, runtimeId = '', lastFlush = 0;
373
+ let flushTimer;
374
+ let usageCompletion;
375
+ let submittedText = '';
376
+ let reconnecting;
377
+ const toolController = new AbortController();
378
+ let toolLease;
379
+ let pluginLease;
380
+ let resolveTurn, rejectTurn;
381
+ const completion = new Promise((resolve, reject) => {
382
+ resolveTurn = resolve;
383
+ rejectTurn = reject;
384
+ });
385
+ // Register rejection immediately; setup RPCs can still be awaiting a reply.
386
+ void completion.catch(() => { });
387
+ const finish = async (error) => {
388
+ if (settled)
389
+ return;
390
+ settled = true;
391
+ // End browser task authority before aborting the shared tool lease. A
392
+ // successful turn parks its Bot's page; cancellation still interrupts I/O.
393
+ let retainBrowser = false;
394
+ try {
395
+ retainBrowser = !error && !this.getWork(owner, run.id).cancelRequested && !this.store.require(owner, 'run', run.runId).stopRequested;
396
+ }
397
+ catch { /* Missing/revoked work must not retain a browser. */ }
398
+ void browserTurn?.close({ retain: retainBrowser }).catch(() => { });
399
+ toolController.abort();
400
+ void toolLease?.dispose();
401
+ void pluginLease?.dispose();
402
+ clearTimeout(flushTimer);
403
+ flushTimer = undefined;
404
+ this.live.delete(key);
405
+ this.executionTurns.delete(run.id);
406
+ try {
407
+ // Retention requires the still-active work grant. Complete the VM
408
+ // channel before persisting terminal status or ending system resources.
409
+ if (!error && vmTools)
410
+ try {
411
+ await vmTools.complete();
412
+ }
413
+ catch (failure) {
414
+ resultMessage.serviceWarnings ??= [];
415
+ resultMessage.serviceWarnings.push({ service: '虚拟机', code: 'computer_completion_failed', message: `虚拟机未能保留运行:${failure instanceof Error ? failure.message : '执行节点收尾失败'}`.slice(0, 1000) });
416
+ }
417
+ const current = this.getWork(owner, run.id);
418
+ if (current.cancelRequested && current.status === 'interrupted') {
419
+ resultMessage.status = 'interrupted';
420
+ resultMessage.error = '已停止';
421
+ this.store.atomic(() => {
422
+ this.store.saveMessage(owner, resultMessage);
423
+ this.saveWork(owner, current);
424
+ this.resolveInteractions(owner, current.id);
425
+ });
426
+ if (error)
427
+ rejectTurn(error);
428
+ else
429
+ resolveTurn(resultMessage);
430
+ return;
431
+ }
432
+ if (error && !submitted && current.status !== 'interrupted' && error instanceof HttpError && RESOURCE_WAIT_CODES.has(error.code ?? '')) {
433
+ current.status = 'queued';
434
+ current.resourceWait = true;
435
+ current.error = '等待执行节点或电脑资源';
436
+ resultMessage.status = 'queued';
437
+ resultMessage.visible = false;
438
+ resultMessage.error = undefined;
439
+ }
440
+ else if (error) {
441
+ current.status = current.status === 'interrupted' ? 'interrupted' : submitted ? 'uncertain' : 'failed';
442
+ current.error = error.message.slice(0, 1000);
443
+ resultMessage.status = current.status;
444
+ resultMessage.error = current.error;
445
+ const optionalUnpublished = current.replyMode === 'automatic' && !current.requiredReply && resultMessage.visible === false;
446
+ resultMessage.visible = !optionalUnpublished && (submitted || current.status !== 'interrupted');
447
+ if (!resultMessage.content.trim() && current.status === 'failed')
448
+ resultMessage.content = `执行失败:${current.error}`;
449
+ }
450
+ else {
451
+ if (root.discussion && /^(?:\(?pass\)?\.?|\[\[YAOYAO_NO_REPLY_V1\]\])$/i.test(resultMessage.content.trim()))
452
+ resultMessage.content = '';
453
+ const silent = (resultMessage.content.trim() === NO_REPLY || !resultMessage.content.trim()) && current.replyMode === 'automatic' && (!current.requiredReply || current.hadInteraction) && !resultMessage.tools.length && !resultMessage.attachments.length && !resultMessage.browserCard && !resultMessage.serviceWarnings?.length;
454
+ current.silent = silent;
455
+ if (current.replyMode === 'automatic') {
456
+ resultMessage.content = resultMessage.content.replace(/\[\[YAOYAO_[A-Z0-9_]*(?:\]\])?/g, '').trim();
457
+ resultMessage.reasoning = resultMessage.reasoning.replace(/\[\[YAOYAO_[A-Z0-9_]*(?:\]\])?/g, '');
458
+ }
459
+ if (current.requiredReply && !silent && !resultMessage.content && !resultMessage.browserCard)
460
+ resultMessage.content = HOST_FALLBACK;
461
+ if (!silent && !resultMessage.content && !resultMessage.attachments.length && !resultMessage.tools.length && !resultMessage.browserCard && !resultMessage.serviceWarnings?.length) {
462
+ current.status = 'failed';
463
+ current.error = '未返回有效回复';
464
+ resultMessage.content = '执行失败:未返回有效回复';
465
+ }
466
+ else {
467
+ current.status = 'complete';
468
+ current.error = undefined;
469
+ }
470
+ resultMessage.visible = !silent;
471
+ if (silent)
472
+ resultMessage.reasoning = '';
473
+ resultMessage.status = current.status;
474
+ resultMessage.error = current.error;
475
+ }
476
+ if (current.status !== 'uncertain') {
477
+ for (const tool of resultMessage.tools) {
478
+ if (!/complete|error|failed/.test(String(tool.status)))
479
+ tool.status = current.status === 'complete' ? 'tool.complete' : 'tool.error';
480
+ }
481
+ }
482
+ this.store.atomic(() => {
483
+ this.store.saveMessage(owner, resultMessage);
484
+ this.saveWork(owner, current);
485
+ if (current.status !== 'uncertain')
486
+ this.resolveInteractions(owner, current.id);
487
+ });
488
+ if (error)
489
+ rejectTurn(error);
490
+ else
491
+ resolveTurn(resultMessage);
492
+ }
493
+ catch (failure) {
494
+ rejectTurn(failure instanceof Error ? failure : new Error('无法保存执行状态'));
495
+ }
496
+ finally {
497
+ vmTools?.close();
498
+ if (usageCompletion)
499
+ void usageCompletion.finally(() => gateway.close());
500
+ else
501
+ gateway.close();
502
+ }
503
+ };
504
+ const restoreCompleted = async () => {
505
+ const marker = `[yaoyao-run:${run.runId}:${resultMessage.id}]`;
506
+ let answer;
507
+ let found = false, seenLastEvent = false;
508
+ for (let page = 0; page < 20 && !found; page++) {
509
+ const response = await target.session.request(`/api/sessions/${encodeURIComponent(binding.storedId)}/messages`, {
510
+ search: new URLSearchParams({ profile: agent.profile, limit: '500', offset: String(page * 500), order: 'latest', include_compacted: 'true' }),
511
+ maxResponseBytes: 8 * 1024 * 1024,
512
+ });
513
+ if (settled)
514
+ return;
515
+ gateway.scope?.authorize();
516
+ if (response.status !== 200)
517
+ throw new Error('无法核对历史');
518
+ const history = JSON.parse(response.body.toString()).messages;
519
+ if (!Array.isArray(history))
520
+ throw new Error('历史响应无效');
521
+ for (const item of [...history].reverse()) {
522
+ if (item.role === 'user') {
523
+ if (String(item.content ?? item.text).includes(marker)) {
524
+ found = true;
525
+ break;
526
+ }
527
+ answer = undefined;
528
+ seenLastEvent = false;
529
+ }
530
+ else if (!seenLastEvent && ['assistant', 'tool'].includes(item.role)) {
531
+ seenLastEvent = true;
532
+ const calls = item.tool_calls;
533
+ const hasCalls = Array.isArray(calls) ? calls.length > 0 : !!calls && calls !== '[]';
534
+ if (item.role === 'assistant' && !hasCalls && !item.function_call && item.finish_reason !== 'tool_calls' && (item.content || item.text))
535
+ answer = item;
536
+ }
537
+ }
538
+ if (history.length < 500)
539
+ break;
540
+ }
541
+ if (!found || !answer)
542
+ throw new Error('无法确认本轮的最终回复,正在核对原执行;不会重复提交');
543
+ resultMessage.content = String(answer.content ?? answer.text);
544
+ binding.contextSeq = Math.max(binding.contextSeq ?? 0, run.contextThroughSeq ?? 0);
545
+ this.store.put(owner, 'binding', key, binding);
546
+ finish();
547
+ };
548
+ const lostTools = () => new HttpError(409, '原执行仍在运行,但本轮工具授权已丢失,无法完整恢复;请停止后重新发起。', 'workspace_tool_lease_lost');
549
+ const recoverTransport = async () => {
550
+ let attempt = 0;
551
+ while (!settled) {
552
+ try {
553
+ gateway.scope?.authorize();
554
+ await delay(Math.min(30_000, 500 * 2 ** Math.min(attempt++, 6)), undefined, { signal: toolController.signal });
555
+ gateway.scope?.authorize();
556
+ if (!gateway.connected)
557
+ await gateway.connect();
558
+ if (settled)
559
+ return;
560
+ gateway.scope?.authorize();
561
+ const opened = await gateway.rpc('session.resume', { profile: agent.profile, session_id: binding.storedId, omit_messages: true, close_on_disconnect: false });
562
+ if (settled)
563
+ return;
564
+ gateway.scope?.authorize();
565
+ if (!opened.session_id || (opened.info?.profile_name && opened.info.profile_name !== agent.profile))
566
+ throw new Error('Hermes 会话身份不匹配');
567
+ runtimeId = String(opened.session_id);
568
+ const previousStoredId = binding.storedId;
569
+ const storedId = String(opened.stored_session_id ?? opened.session_key ?? opened.resumed ?? previousStoredId);
570
+ if (!storedId)
571
+ throw new Error('Hermes 会话身份不匹配');
572
+ binding.storedId = storedId;
573
+ binding.aliases = [...new Set([...binding.aliases, previousStoredId, storedId])];
574
+ binding.runtimeId = runtimeId;
575
+ this.store.put(owner, 'binding', key, binding);
576
+ const live = this.live.get(key);
577
+ if (live?.taskId === run.id)
578
+ live.runtimeId = runtimeId;
579
+ if (!opened.running) {
580
+ try {
581
+ await restoreCompleted();
582
+ }
583
+ catch (error) {
584
+ finish(error instanceof Error ? error : new Error('无法核对原执行'));
585
+ }
586
+ return;
587
+ }
588
+ if (binding.toolsBound && !toolLease)
589
+ throw lostTools();
590
+ if (toolLease) {
591
+ try {
592
+ await toolLease.bind();
593
+ }
594
+ catch (error) {
595
+ if (error instanceof HttpError && (error.code === 'team_tools_bind_failed' || error.code === 'hermes_bridge_session_busy'))
596
+ throw lostTools();
597
+ throw error;
598
+ }
599
+ }
600
+ if (settled)
601
+ return;
602
+ gateway.scope?.authorize();
603
+ if (!gateway.connected)
604
+ continue;
605
+ const current = this.getWork(owner, run.id);
606
+ current.error = undefined;
607
+ if (current.status === 'uncertain')
608
+ current.status = 'running';
609
+ resultMessage.status = 'streaming';
610
+ resultMessage.error = undefined;
611
+ this.store.atomic(() => { this.saveWork(owner, current); this.store.saveMessage(owner, resultMessage); });
612
+ return;
613
+ }
614
+ catch (error) {
615
+ if (settled)
616
+ return;
617
+ try {
618
+ gateway.scope?.authorize();
619
+ }
620
+ catch (revoked) {
621
+ finish(revoked instanceof Error ? revoked : new Error('本轮授权已结束'));
622
+ return;
623
+ }
624
+ if (error instanceof HttpError && error.code === 'workspace_tool_lease_lost') {
625
+ finish(error);
626
+ return;
627
+ }
628
+ // No new prompt is admitted while the original outcome is unknown.
629
+ const current = this.getWork(owner, run.id);
630
+ current.error = error instanceof Error ? error.message : '正在恢复 Hermes 连接';
631
+ this.saveWork(owner, current);
632
+ }
633
+ }
634
+ };
635
+ gateway.onDisconnect = () => {
636
+ if (settled || reconnecting)
637
+ return;
638
+ if (completedEvidence || !submitted || !binding?.storedId || !runtimeId) {
639
+ finish(completedEvidence ? undefined : new Error('Hermes 连接断开'));
640
+ return;
641
+ }
642
+ const current = this.getWork(owner, run.id);
643
+ current.error = 'Hermes 连接断开,正在恢复原执行';
644
+ this.saveWork(owner, current);
645
+ reconnecting = recoverTransport().finally(() => { reconnecting = undefined; });
646
+ void reconnecting.catch(error => finish(error instanceof Error ? error : new Error('无法恢复 Hermes 连接')));
647
+ };
648
+ gateway.onEvent = (frame) => {
649
+ if (settled || !runtimeId || frame.session_id !== runtimeId)
650
+ return;
651
+ const currentTurn = this.getWork(owner, run.id);
652
+ if (currentTurn.cancelRequested || currentTurn.status === 'interrupted')
653
+ return;
654
+ this.inspector?.record(owner, c.id, { direction: 'event', method: frame.type, data: frame.payload, agentId: agent.id, runId: run.runId, taskId: run.conversationTaskId });
655
+ const p = frame.payload ?? {}, type = frame.type;
656
+ const firstContent = type === 'message.delta' && !resultMessage.content.trim();
657
+ if (type === 'computer.paused' || type === 'computer.resumed') {
658
+ const current = this.getWork(owner, run.id);
659
+ current.status = type === 'computer.paused' ? 'waiting' : 'running';
660
+ this.saveWork(owner, current);
661
+ return;
662
+ }
663
+ if (type === 'message.delta') {
664
+ resultMessage.content += String(p.text ?? p.delta ?? '');
665
+ if (resultMessage.content.trim() && !NO_REPLY.startsWith(resultMessage.content.trim()) && !resultMessage.content.trim().startsWith('[[YAOYAO_'))
666
+ resultMessage.visible = true;
667
+ }
668
+ else if (type === 'reasoning.delta')
669
+ resultMessage.reasoning += String(p.text ?? p.delta ?? '');
670
+ else if (type === 'message.interim') {
671
+ resultMessage.content += '\n\n';
672
+ }
673
+ else if (type.startsWith('tool.')) {
674
+ resultMessage.visible = true;
675
+ const id = String(p.tool_id ?? p.id ?? ''), index = resultMessage.tools.findIndex((t) => t.id === id);
676
+ const value = { ...p, id, status: type };
677
+ if (index >= 0)
678
+ resultMessage.tools[index] = { ...resultMessage.tools[index], ...value };
679
+ else
680
+ resultMessage.tools.push(value);
681
+ }
682
+ else if (['approval.request', 'approval.requested', 'clarify.request', 'clarify.requested'].includes(type)) {
683
+ const upstreamId = String(p.request_id ?? p.requestId ?? p.id ?? '');
684
+ const previous = this.store.list(owner, 'interaction').find(i => {
685
+ const b = this.store.get(owner, 'interaction-binding', i.id);
686
+ return b?.taskId === run.id && b.upstreamId === upstreamId;
687
+ });
688
+ if (previous?.resolved)
689
+ return;
690
+ const interaction = previous ?? {
691
+ id: randomUUID(),
692
+ conversationId: c.id,
693
+ conversationTaskId: run.conversationTaskId,
694
+ runId: run.runId,
695
+ agentId: agent.id,
696
+ kind: type.startsWith('approval') ? 'approval' : 'clarification',
697
+ message: String(p.question ?? p.message ?? p.prompt ?? '需要确认'),
698
+ choices: Array.isArray(p.choices) ? p.choices.map(String) : [],
699
+ resolved: false,
700
+ };
701
+ this.store.put(owner, 'interaction', interaction.id, interaction);
702
+ this.store.put(owner, 'interaction-binding', interaction.id, { key, upstreamId, taskId: run.id, conversationTaskId: run.conversationTaskId });
703
+ this.store.event(owner, 'interaction.changed', interaction, c.id);
704
+ const current = this.getWork(owner, run.id);
705
+ current.hadInteraction = true;
706
+ current.status = 'waiting';
707
+ this.saveWork(owner, current);
708
+ const policy = globalComputers(this.store.home).approvalPolicy;
709
+ if (interaction.kind === 'approval' && policy !== 'ask' && !previous) {
710
+ // Use the same ownership, authorization and response deduplication as
711
+ // a manual answer. Never grant session-wide or permanent approval.
712
+ void this.respond(owner, interaction.id, policy === 'allow' ? 'once' : 'deny').catch(() => {
713
+ const latest = this.store.get(owner, 'interaction', interaction.id);
714
+ if (latest && !latest.resolved)
715
+ this.notify(owner, c, this.store.require(owner, 'run', run.runId), undefined, latest);
716
+ });
717
+ }
718
+ else if (!previous)
719
+ this.notify(owner, c, this.store.require(owner, 'run', run.runId), undefined, interaction);
720
+ }
721
+ else if (type === 'interaction.cancelled') {
722
+ const upstreamId = String(p.request_id ?? '');
723
+ for (const interaction of this.store.list(owner, 'interaction')) {
724
+ const binding = this.store.get(owner, 'interaction-binding', interaction.id);
725
+ if (!interaction.resolved && binding?.taskId === run.id && binding.upstreamId === upstreamId) {
726
+ interaction.resolved = true;
727
+ this.store.put(owner, 'interaction', interaction.id, interaction);
728
+ this.store.event(owner, 'interaction.changed', interaction, c.id);
729
+ }
730
+ }
731
+ const current = this.getWork(owner, run.id);
732
+ if (current.status === 'waiting' && !this.store.list(owner, 'interaction').some(i => i.runId === run.runId && i.agentId === agent.id && !i.resolved)) {
733
+ current.status = 'running';
734
+ this.saveWork(owner, current);
735
+ }
736
+ }
737
+ else if (['message.complete', 'run.completed'].includes(type)) {
738
+ if (typeof p.text === 'string')
739
+ resultMessage.content = p.text;
740
+ if (typeof p.reasoning === 'string')
741
+ resultMessage.reasoning = p.reasoning;
742
+ if (p.status === 'interrupted') {
743
+ const current = this.getWork(owner, run.id);
744
+ current.status = 'interrupted';
745
+ this.saveWork(owner, current);
746
+ finish(new Error('已停止'));
747
+ }
748
+ else if (p.error || p.status === 'failed') {
749
+ submitted = false;
750
+ finish(new HttpError(502, String(p.error ?? '运行失败'), 'run_failed'));
751
+ }
752
+ else if (!completing) {
753
+ completedEvidence = true;
754
+ completing = true;
755
+ const outputText = [resultMessage.content, resultMessage.reasoning, resultMessage.tools.length ? JSON.stringify(resultMessage.tools) : ''].filter(Boolean).join('\n');
756
+ this.recordTurnTokens(owner, agent.id, estimateTokens(submittedText), estimateTokens(outputText));
757
+ finish();
758
+ }
759
+ return;
760
+ }
761
+ else if (['error', 'message.error', 'run.failed'].includes(type)) {
762
+ submitted = false;
763
+ finish(new HttpError(502, String(p.message ?? p.error ?? '运行失败'), 'run_failed'));
764
+ return;
765
+ }
766
+ else if (['session.usage', 'usage.update', 'context.update'].includes(type)) {
767
+ if (type !== 'context.update')
768
+ this.recordAgentUsage(owner, key, agent.id, p);
769
+ const context = { ...p, conversationTaskId: run.conversationTaskId };
770
+ this.store.put(owner, 'context', run.conversationTaskId ?? c.id, context);
771
+ this.store.event(owner, 'context.changed', context, c.id);
772
+ }
773
+ else if (type === 'session.info' && binding) {
774
+ const storedId = p.stored_session_id ?? p.session_key;
775
+ if (typeof storedId === 'string' && storedId && storedId !== binding.storedId) {
776
+ binding.aliases = [...new Set([...binding.aliases, binding.storedId, storedId])];
777
+ binding.storedId = storedId;
778
+ this.store.put(owner, 'binding', key, binding);
779
+ }
780
+ }
781
+ const flush = () => {
782
+ clearTimeout(flushTimer);
783
+ flushTimer = undefined;
784
+ if (settled || this.closing)
785
+ return;
786
+ try {
787
+ this.store.saveMessage(owner, resultMessage);
788
+ lastFlush = Date.now();
789
+ }
790
+ catch (error) {
791
+ finish(error instanceof Error ? error : new Error('无法保存流式消息'));
792
+ }
793
+ };
794
+ const remaining = (this.store.messagePatchesEnabled ? 33 : 100) - (Date.now() - lastFlush);
795
+ if (firstContent || !['message.delta', 'reasoning.delta', 'message.interim'].includes(type) || remaining <= 0)
796
+ flush();
797
+ // A stream may pause after any chunk. Publish the latest text even when
798
+ // no subsequent event arrives to trigger the next leading-edge flush.
799
+ else if (flushTimer === undefined)
800
+ flushTimer = setTimeout(flush, remaining);
801
+ };
802
+ try {
803
+ await gateway.connect();
804
+ this.requireAuthorization(owner, run.runId);
805
+ this.nodes.requireSource(owner, agent);
806
+ // Paired Web nodes enforce their own profile config at the destination.
807
+ const cwd = recovering || target.pairedToken ? undefined
808
+ : await configuredWorkingDirectory((path, options) => target.session.request(path, options), agent.profile);
809
+ this.nodes.requireSource(owner, agent);
810
+ // Hermes rejects disabled_toolsets on session.create. Host-tool denial
811
+ // stays a YaoYao policy; it is not a session-create parameter.
812
+ const createSession = () => gateway.rpc('session.create', {
813
+ profile: agent.profile,
814
+ title: `Yaoyao ${c.id}${run.conversationTaskId ? ` / ${run.conversationTaskId}` : ''}`,
815
+ source: 'yaoyao_workspace',
816
+ ...(cwd ? { cwd } : {}),
817
+ hidden: true,
818
+ room_plumbing: true,
819
+ close_on_disconnect: false,
820
+ });
821
+ let opened;
822
+ if (binding?.storedId) {
823
+ try {
824
+ opened = await gateway.rpc('session.resume', {
825
+ profile: agent.profile,
826
+ session_id: binding.storedId,
827
+ omit_messages: true,
828
+ ...(recovering && target.runner?.computer ? { recoverOnly: true } : {}),
829
+ close_on_disconnect: false,
830
+ });
831
+ }
832
+ catch (error) {
833
+ const code = error instanceof HttpError ? error.code : '';
834
+ const message = error instanceof Error ? error.message : '';
835
+ if (recovering || (code !== 'computer_session_mode_changed' && !message.includes('执行方式已改变')))
836
+ throw error;
837
+ binding = undefined;
838
+ opened = await createSession();
839
+ }
840
+ }
841
+ else
842
+ opened = await createSession();
843
+ runtimeId = String(opened.session_id ?? '');
844
+ const storedId = String(opened.stored_session_id ?? opened.session_key ?? opened.resumed ?? binding?.storedId ?? '');
845
+ if (!runtimeId ||
846
+ !storedId ||
847
+ (opened.info?.profile_name && opened.info.profile_name !== agent.profile))
848
+ throw new Error('Hermes 会话身份不匹配');
849
+ binding = {
850
+ toolsBound: recovering ? binding?.toolsBound : undefined,
851
+ memoryVersion: binding?.memoryVersion,
852
+ memoryState: binding?.memoryState,
853
+ memoryPending: binding?.memoryPending,
854
+ runnerId: target.runner?.id,
855
+ execution: chatExecution,
856
+ vmExecution: undefined,
857
+ hermesComputer: target.runner?.hermesComputer,
858
+ computerEnvironmentId: agent.computerEnvironmentId,
859
+ id: key,
860
+ nodeId: agent.nodeId,
861
+ remoteAgentId: agent.remoteAgentId,
862
+ profile: agent.profile,
863
+ storedId,
864
+ runtimeId,
865
+ aliases: [
866
+ ...new Set([
867
+ ...(binding?.aliases ?? []),
868
+ ...(binding ? [binding.storedId] : []),
869
+ storedId,
870
+ ]),
871
+ ],
872
+ runId: run.runId,
873
+ conversationTaskId: run.conversationTaskId,
874
+ taskId: run.id,
875
+ executionRevision: execution?.revision,
876
+ executionPolicyVersion: execution ? 2 : undefined,
877
+ contextSeq: binding?.contextSeq ?? 0,
878
+ messageId: resultMessage.id,
879
+ };
880
+ this.store.put(owner, 'binding', key, binding);
881
+ if (execution)
882
+ this.executionTurns.set(run.id, { agentId: agent.id, mode: execution.mode, revision: execution.revision });
883
+ this.live.set(key, { gateway, runtimeId, runId: run.runId, conversationTaskId: run.conversationTaskId, taskId: run.id, agentId: agent.id, done: finish });
884
+ if (this.closing || this.getWork(owner, run.id).cancelRequested || this.getWork(owner, run.id).status === 'interrupted')
885
+ throw new Error('运行已停止');
886
+ if (recovering) {
887
+ if (opened.running) {
888
+ if (binding.toolsBound)
889
+ throw lostTools();
890
+ const current = this.getWork(owner, run.id);
891
+ current.status = 'running';
892
+ this.saveWork(owner, current);
893
+ }
894
+ else {
895
+ await restoreCompleted();
896
+ }
897
+ }
898
+ else {
899
+ if (opened.running)
900
+ throw new HttpError(409, '上游会话仍在运行', 'session_busy');
901
+ this.nodes.requireSource(owner, agent);
902
+ const team = botCapabilities.tools && !agent.temporaryGoalId && !agent.remoteAgentId && !this.store.require(owner, 'run', run.runId).assignmentId;
903
+ const globals = globalComputers(this.store.home);
904
+ const desktopSnapshot = this.desktopEnvironments?.snapshot(owner, agent, root.deviceHost, { script: globals.scriptMachine, server: globals.serverComputer, maxMiB: globals.fileTransferMaxMiB })
905
+ ?? { capturedAt: Date.now(), sourceHost: root.deviceHost, hosts: [] };
906
+ const environment = buildWorkspaceEnvironment({ agent, globals, execution, serverDesktop: agent.nodeId === 'local' && isLocalAuthorizationTarget(target.url), desktop: desktopSnapshot, bridge: botCapabilities.tools, cloud: !!this.cloud?.selected(owner, agent), plugins: !!this.plugins?.selected(owner, agent), managedBrowser: this.managedBrowsers?.available(owner, agent) });
907
+ const { cloud, plugins, vm: dispatchedVm } = environment.tools;
908
+ const desktop = environment.tools.desktopView || environment.tools.desktopFile;
909
+ const desktopEpochs = Object.fromEntries(environment.desktop.hosts.map(host => [host.id, host.epoch ?? '']));
910
+ const environmentCatalog = workspaceEnvironmentTools(environment);
911
+ const knowledge = botCapabilities.tools && !agent.remoteAgentId;
912
+ const routines = botCapabilities.tools && !agent.temporaryGoalId && !agent.remoteAgentId && !!this.routineTools;
913
+ const vmHolder = {};
914
+ const requireVm = () => { if (!globalComputers(this.store.home).vm)
915
+ throw new HttpError(403, '全局设置未开放虚拟机。', 'computer_disabled'); };
916
+ const callVm = async (name, args, callId) => {
917
+ requireVm();
918
+ if (!vmHolder.session) {
919
+ const vmTarget = this.nodes.targetForAgent(owner, { ...agent, execution: 'computer' });
920
+ vmHolder.session = new VmToolSession(vmTarget, agent.profile, run.id, () => {
921
+ systemTurn?.check();
922
+ requireVm();
923
+ this.requireAuthorization(owner, run.runId);
924
+ this.nodes.requireSource(owner, agent);
925
+ const current = this.getWork(owner, run.id), latest = this.store.require(owner, 'agent', agent.id), conversation = this.store.require(owner, 'conversation', c.id);
926
+ if (this.closing || conversation.archived || !this.store.taskMemberIds(owner, conversation, run.conversationTaskId).includes(agent.id) || this.store.require(owner, 'run', run.runId).stopRequested || current.cancelRequested || ['interrupted', 'complete', 'failed'].includes(current.status) || latest.archived || latest.computerEnvironmentId !== agent.computerEnvironmentId)
927
+ throw new HttpError(403, '本轮机器人或任务授权已结束', 'run_authorization_revoked');
928
+ }, async (name, bytes) => {
929
+ this.requireAuthorization(owner, run.runId);
930
+ const file = this.publishArtifact(owner, resultMessage, agent, name, bytes);
931
+ if (!resultMessage.attachments.some(item => item.id === file.id))
932
+ resultMessage.attachments.push(file);
933
+ this.store.saveMessage(owner, resultMessage);
934
+ return { ...file, url: `/api/app/files/${file.id}/download` };
935
+ }, systemTurn ? () => systemTurn.vmTaskEnvironment() : undefined);
936
+ vmTools = vmHolder.session;
937
+ }
938
+ return name === '__file_transfer' ? vmHolder.session.transfer(args) : vmHolder.session.call(name, args, callId);
939
+ };
940
+ if (team || cloud || desktop || plugins || knowledge || routines || dispatchedVm || environment.tools.managedBrowser || (execution && botCapabilities.tools)) {
941
+ if (team) {
942
+ const granted = this.getWork(owner, run.id);
943
+ granted.teamManagementRevision = agent.revision;
944
+ this.saveWork(owner, granted);
945
+ }
946
+ if (desktop)
947
+ await this.desktopEnvironments.requireAvailable(owner, agent, target);
948
+ if (cloud)
949
+ await this.cloud.requireAvailable(owner, agent, target);
950
+ const assertActive = () => {
951
+ if (settled || this.closing || toolController.signal.aborted)
952
+ throw new HttpError(410, '本轮运行已结束,请发起新一轮对话后重试。', 'run_finished');
953
+ systemTurn?.check();
954
+ this.requireAuthorization(owner, run.runId);
955
+ this.nodes.requireSource(owner, this.store.require(owner, 'agent', agent.id));
956
+ if (team)
957
+ this.teamTools.assertTurn(owner, run.id);
958
+ if (plugins) {
959
+ const current = this.getWork(owner, run.id), latest = this.store.require(owner, 'agent', agent.id);
960
+ if (current.cancelRequested || this.store.require(owner, 'run', run.runId).stopRequested || latest.archived || !['running', 'waiting'].includes(current.status))
961
+ throw new HttpError(403, '本轮插件授权已结束', 'plugin_grant_revoked');
962
+ }
963
+ };
964
+ if (plugins) {
965
+ pluginLease = await this.plugins.open(owner, agent, target, toolController.signal, assertActive);
966
+ const warnings = pluginLease.warnings().map(({ name, code, message }) => ({ service: name, code, message }));
967
+ if (warnings.length) {
968
+ resultMessage.serviceWarnings = warnings;
969
+ resultMessage.visible = true;
970
+ this.store.saveMessage(owner, resultMessage);
971
+ }
972
+ }
973
+ toolLease = await createWorkspaceToolLease({
974
+ target, profile: agent.profile, workId: run.id, signal: toolController.signal,
975
+ workspaceMemory: botCapabilities.memory,
976
+ // Native tools retain the Profile's permissions independently of
977
+ // the preferred target. Each dispatched environment checks its grants.
978
+ ...(execution ? { computerPolicy: { mode: 'profile', hostAccess: true } } : {}),
979
+ session: () => ({ runtimeId, storedId: binding.storedId }), assertActive,
980
+ catalog: () => [...(team ? this.teamTools.catalog(owner, run.id) : []), ...(routines ? this.routineTools.catalog(owner, run.id) : []), ...(knowledge ? this.knowledgeTools.catalog(owner, run.id, botCapabilities.memory) : []), ...environmentCatalog, ...(systemTurn?.catalog() ?? []), ...(pluginLease?.catalog() ?? [])],
981
+ call: async (toolId, args, callId) => {
982
+ assertActive();
983
+ if (toolId === 'yaoyao_service_request' && systemTurn)
984
+ return systemTurn.call(args, toolController.signal);
985
+ if (this.routineTools?.handles(toolId))
986
+ return this.routineTools.call(owner, run.id, toolId, args);
987
+ if (toolId.startsWith('managed_browser_') && environment.tools.managedBrowser && this.managedBrowsers) {
988
+ browserTurn ??= this.managedBrowsers.openTurn(owner, agent, { workId: run.id, signal: toolController.signal, authorize: assertActive,
989
+ onCard: card => {
990
+ try {
991
+ // Human control can outlive this turn and its deleted history.
992
+ const saved = this.store.get(owner, 'message', resultMessage.id);
993
+ if (!saved)
994
+ return;
995
+ resultMessage.browserCard = card;
996
+ resultMessage.visible = true;
997
+ this.store.saveMessage(owner, settled ? { ...saved, browserCard: card, visible: true } : resultMessage);
998
+ }
999
+ catch {
1000
+ return false; /* Card persistence must not interrupt browser cleanup. */
1001
+ }
1002
+ },
1003
+ publish: async (name, bytes) => { assertActive(); const file = this.publishArtifact(owner, resultMessage, agent, name, bytes); if (!resultMessage.attachments.some(item => item.id === file.id))
1004
+ resultMessage.attachments.push(file); this.store.saveMessage(owner, resultMessage); return { ...file, url: `/api/app/files/${file.id}/download` }; },
1005
+ upload: fileId => browserOwnedFile(this.store, this.nodes, this.uploads, owner, fileId),
1006
+ ...(dispatchedVm ? { toVm: (file, path, overwrite) => browserVmFile(action => callVm('__file_transfer', action), path, assertActive, file, overwrite, Math.min(25, globals.fileTransferMaxMiB) * 1024 * 1024), fromVm: async (path) => await browserVmFile(action => callVm('__file_transfer', action), path, assertActive, undefined, false, Math.min(25, globals.fileTransferMaxMiB) * 1024 * 1024) } : {}) });
1007
+ return browserTurn.call(toolId, args, callId);
1008
+ }
1009
+ return knowledge && this.knowledgeTools.handles(toolId) ? this.knowledgeTools.call(owner, run.id, toolId, args, botCapabilities.memory) : toolId.startsWith('plugin_') && pluginLease ? pluginLease.call(toolId, args) : toolId.startsWith('desktop_') ? this.desktopEnvironments.call(owner, agent.id, toolId, args, toolController.signal, assertActive, 'local', desktopEpochs, root.deviceHost, dispatchedVm ? action => callVm('__file_transfer', action) : undefined) : toolId.startsWith('cloud_computer_') ? this.cloud.call(owner, agent.id, toolId, args, toolController.signal) : toolId.startsWith('computer_') && dispatchedVm ? this.operationJournal.execute(owner, run.id, callId, toolId, args, assertActive, () => callVm(toolId, args, callId)) : this.teamTools.call(owner, run.id, toolId, args);
1010
+ },
1011
+ onFailure: error => { if (!settled)
1012
+ void gateway.rpc('session.interrupt', { session_id: runtimeId }).catch(() => { }).finally(() => finish(error)); },
1013
+ });
1014
+ await toolLease.bind();
1015
+ if (settled)
1016
+ return await completion;
1017
+ binding.toolsBound = true;
1018
+ this.store.put(owner, 'binding', key, binding);
1019
+ }
1020
+ const workingDirectory = await applyWorkingDirectory((method, params) => gateway.rpc(method, params), runtimeId, cwd, undefined, opened.info?.cwd);
1021
+ environment.cwd = workingDirectory?.resolved;
1022
+ // Binding initializes cold Hermes sessions; its persisted runtime can overwrite
1023
+ // pre-build config acknowledgements. Apply Bot settings only after that boundary.
1024
+ if (agent.modelSettings !== undefined) {
1025
+ const entry = { method: 'bot.model-settings', agentId: agent.id, runId: run.runId, taskId: run.conversationTaskId };
1026
+ const snapshot = { revision: agent.revision, settings: agent.modelSettings };
1027
+ this.inspector?.record(owner, c.id, { ...entry, direction: 'request', data: snapshot });
1028
+ try {
1029
+ const resolution = await resolveBotModelSettings(target, agent.profile, agent.modelSettings);
1030
+ const confirmed = agent.modelSettingsConfirmation === botModelTarget(resolution.effective);
1031
+ if (resolution.confirmationMessage && !confirmed)
1032
+ throw new HttpError(409, '此模型需要确认,请打开 Bot 个人资料保存模型设置。', 'model_confirmation_required');
1033
+ await applyBotModelSettings((method, params) => gateway.rpc(method, params), runtimeId, resolution.effective, confirmed);
1034
+ this.inspector?.record(owner, c.id, { ...entry, direction: 'response', data: { ...snapshot, applied: true, effective: resolution.effective } });
1035
+ }
1036
+ catch (error) {
1037
+ // Context-dependent native warnings cannot be known from the model
1038
+ // catalogue. Bring them back to the profile's existing save flow.
1039
+ if (error instanceof BotModelConfirmationError) {
1040
+ const latest = this.store.require(owner, 'agent', agent.id);
1041
+ if (latest.revision === agent.revision)
1042
+ this.store.put(owner, 'agent', latest.id, { ...latest,
1043
+ modelSettingsPendingConfirmation: { target: error.target, message: error.confirmationMessage } });
1044
+ }
1045
+ this.inspector?.record(owner, c.id, { ...entry, direction: 'response', data: { ...snapshot, applied: false, error: error instanceof Error ? error.message : '模型设置应用失败' } });
1046
+ throw error;
1047
+ }
1048
+ }
1049
+ const trigger = this.store.require(owner, 'message', run.messageId);
1050
+ const attachmentRefs = [];
1051
+ for (const file of trigger.attachments) {
1052
+ this.requireAuthorization(owner, run.runId);
1053
+ const record = this.files(owner, [file.id])[0];
1054
+ const bytes = readFileSync(record.path).toString('base64');
1055
+ const attached = record.mimeType.startsWith('image/')
1056
+ ? await gateway.rpc('image.attach_bytes', {
1057
+ session_id: runtimeId,
1058
+ filename: record.name,
1059
+ content_base64: bytes,
1060
+ })
1061
+ : await gateway.rpc('file.attach', {
1062
+ session_id: runtimeId,
1063
+ name: record.name,
1064
+ data_url: `data:${record.mimeType};base64,${bytes}`,
1065
+ });
1066
+ if (attached.ref_text)
1067
+ attachmentRefs.push(String(attached.ref_text));
1068
+ }
1069
+ const members = run.turnConfiguration.members;
1070
+ const goal = run.conversationTaskId ? this.store.get(owner, 'goal', run.conversationTaskId) : undefined;
1071
+ const text = c.kind === 'group' ? this.contextText(owner, c, agent, run, binding.contextSeq ?? 0, !!resetReason)
1072
+ : resetReason ? `${movedRunner ? '执行节点已切换' : '记忆或授权范围已变化,会话已重新建立'}。以下是原会话的近期记录,旧路径和执行状态需要在当前节点重新核实;不要重新执行已完成的操作。\n\n${this.contextText(owner, c, agent, run, 0, true)}` : trigger.content;
1073
+ const admission = this.getWork(owner, run.id);
1074
+ if (!this.store.taskMemberIds(owner, this.store.require(owner, 'conversation', c.id), run.conversationTaskId).includes(agent.id)) {
1075
+ admission.status = 'interrupted';
1076
+ admission.error = '执行前成员已移除';
1077
+ this.saveWork(owner, admission);
1078
+ throw new Error('执行前成员已移除');
1079
+ }
1080
+ this.nodes.requireSource(owner, agent);
1081
+ this.requireAuthorization(owner, run.runId);
1082
+ if (admission.cancelRequested || admission.status === 'interrupted')
1083
+ throw new Error('运行已停止');
1084
+ admission.contextThroughSeq = run.contextThroughSeq ?? run.triggerSeq;
1085
+ admission.submitted = true;
1086
+ this.saveWork(owner, admission);
1087
+ submitted = true;
1088
+ try {
1089
+ const pluginServices = pluginLease?.services() ?? [];
1090
+ submittedText = buildWorkspacePrompt({
1091
+ agent, conversation: c, members, work: run,
1092
+ run: this.store.require(owner, 'run', run.runId), goal,
1093
+ environment, pluginServices, pluginWarnings: resultMessage.serviceWarnings,
1094
+ teamRules: team ? TEAM_TOOL_RULES : undefined,
1095
+ routineRules: routines ? ROUTINE_TOOL_RULES : undefined,
1096
+ knowledgeRules: knowledge ? BOT_KNOWLEDGE_RULES : undefined,
1097
+ memory: memoryDelta(memory, binding.memoryState), noReply: NO_REPLY,
1098
+ marker: `[yaoyao-run:${run.runId}:${resultMessage.id}]`,
1099
+ content: text + (systemTurn?.description.length ? '\n[本轮系统服务目录,仅含元数据]\n' + JSON.stringify(systemTurn.description) : ''), contentKind: c.kind === 'group' || !!resetReason ? 'history' : 'user', attachmentRefs,
1100
+ });
1101
+ this.inspector?.record(owner, c.id, { method: 'bot.environment', direction: 'request', agentId: agent.id, runId: run.runId, taskId: run.conversationTaskId,
1102
+ data: { snapshot: environment, computerToolIds: environmentCatalog.map(tool => tool.id), pluginServices, pluginWarnings: resultMessage.serviceWarnings } });
1103
+ binding.memoryPending = true;
1104
+ this.store.put(owner, 'binding', key, binding);
1105
+ await gateway.rpc('prompt.submit', {
1106
+ session_id: runtimeId,
1107
+ ...(target.runner?.computer ? { workMarker: `[yaoyao-run:${run.runId}:${resultMessage.id}]` } : {}),
1108
+ text: submittedText,
1109
+ });
1110
+ this.store.remove(owner, 'binding-reset', key);
1111
+ // Only an admitted prompt may advance the durable injection baseline.
1112
+ // A rejected/lost receipt must not make the next turn omit new facts.
1113
+ binding.memoryVersion = memory.version;
1114
+ binding.memoryState = acknowledgeMemory(memory, binding.memoryState);
1115
+ binding.memoryPending = undefined;
1116
+ binding.contextSeq = Math.max(binding.contextSeq ?? 0, admission.contextThroughSeq);
1117
+ this.store.put(owner, 'binding', key, binding);
1118
+ }
1119
+ catch (error) {
1120
+ // A JSON-RPC error is a definitive rejection, not a lost receipt.
1121
+ if (error instanceof HttpError && ['gateway_rejected', 'runner_command_not_admitted'].includes(error.code ?? '')) {
1122
+ submitted = false;
1123
+ const current = this.getWork(owner, run.id);
1124
+ current.submitted = false;
1125
+ this.saveWork(owner, current);
1126
+ binding.memoryPending = undefined;
1127
+ this.store.put(owner, 'binding', key, binding);
1128
+ }
1129
+ throw error;
1130
+ }
1131
+ }
1132
+ return await completion;
1133
+ }
1134
+ catch (error) {
1135
+ if (reconnecting && submitted && !settled)
1136
+ return await completion;
1137
+ finish(error instanceof Error ? error : new Error('执行失败'));
1138
+ return await completion;
1139
+ }
1140
+ }
1141
+ requireAuthorization(owner, runId) {
1142
+ const run = this.store.require(owner, 'run', runId);
1143
+ if (!this.userActive(owner) || (run.authorizationVersion !== undefined && run.authorizationVersion !== this.authorizationVersion(owner)))
1144
+ throw new HttpError(403, '本轮账号授权已失效', 'run_authorization_revoked');
1145
+ }
1146
+ contextText(owner, c, agent, work, after, includeOwn = false) {
1147
+ const rootTrigger = this.store.require(owner, 'message', work.messageId);
1148
+ const roots = new Map(this.store.list(owner, 'run').filter(r => r.conversationId === c.id && r.conversationTaskId === work.conversationTaskId).map(r => [r.id, this.store.get(owner, 'message', r.messageId)?.seq ?? 0]));
1149
+ const history = this.store.messages(owner, c.id, Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER, true, work.conversationTaskId);
1150
+ const unfinished = history.find(m => m.seq > after && m.seq <= work.triggerSeq && (['queued', 'streaming', 'uncertain'].includes(m.status) || (m.runId && (roots.get(m.runId) ?? 0) > rootTrigger.seq)));
1151
+ work.contextThroughSeq = unfinished ? unfinished.seq - 1 : work.triggerSeq;
1152
+ const eligible = history
1153
+ .filter(m => m.seq > after && m.seq <= work.triggerSeq && m.visible !== false && ['complete', 'failed', 'interrupted'].includes(m.status)
1154
+ && (includeOwn || !(m.role === 'assistant' && m.agentId === agent.id)) && (!m.runId || (roots.get(m.runId) ?? 0) <= rootTrigger.seq));
1155
+ const selected = [];
1156
+ let size = 0, omitted = 0;
1157
+ for (const message of [...eligible].reverse()) {
1158
+ const files = message.attachments.map(f => `[附件 ${f.name}](${f.sourcePath || `/api/app/files/${f.id}/download`})`).join('\n');
1159
+ const content = message.content.length > 24_000 ? message.content.slice(0, 12_000) + '\n[内容过长,保留首尾片段]\n' + message.content.slice(-12_000) : message.content;
1160
+ const reasoning = message.reasoning ? `\n思考摘要:${message.reasoning.slice(0, 2000)}` : '';
1161
+ const tools = [...new Set(message.tools.map(t => String(t.name ?? t.tool_name ?? '')).filter(name => /^[A-Za-z0-9][A-Za-z0-9_.-]{0,119}$/.test(name)))].slice(0, 16);
1162
+ const row = `${message.role === 'user' ? '用户' : message.agentName ?? '系统'}(${message.status}):${content}${reasoning}${tools.length ? `\n使用工具:${tools.join('、')}` : ''}${message.error ? `\n错误:${message.error}` : ''}${files ? '\n' + files : ''}`;
1163
+ if (selected.length >= 50 || size + row.length > 30_000) {
1164
+ omitted++;
1165
+ continue;
1166
+ }
1167
+ selected.unshift(row);
1168
+ size += row.length;
1169
+ }
1170
+ // Preserve a large trigger as a bounded excerpt rather than silently losing it.
1171
+ if (!selected.length && eligible.length)
1172
+ selected.push(eligible.at(-1).content.slice(-30_000));
1173
+ const batch = work.reviewOf ? this.works(owner, work.runId).filter(t => t.batchId === work.reviewOf).map(t => `${this.store.get(owner, 'agent', t.agentId)?.name ?? t.agentId}:${t.status}${t.error ? `;${t.error}` : ''}`).join('\n') : '';
1174
+ const request = this.store.require(owner, 'run', work.runId).discussion ? `本次用户原始要求:\n${rootTrigger.content.slice(0, 16000)}\n\n` : '';
1175
+ return `${request}${batch ? `本批次执行结果:\n${batch}\n\n` : ''}${omitted ? `较早上下文有 ${omitted} 条因长度限制省略,请勿假定已完整读取。\n\n` : ''}${selected.join('\n\n')}`;
1176
+ }
1177
+ async respond(owner, id, answer) {
1178
+ const interaction = this.store.require(owner, 'interaction', id);
1179
+ this.requireAuthorization(owner, interaction.runId);
1180
+ this.nodes.requireSource(owner, this.store.require(owner, 'agent', interaction.agentId));
1181
+ if (interaction.resolved) {
1182
+ if (interaction.answer && interaction.answer !== answer)
1183
+ throw new HttpError(409, '该请求已使用其他答复完成', 'interaction_answer_conflict');
1184
+ return;
1185
+ }
1186
+ if (interaction.responseState === 'sending' || interaction.responseState === 'uncertain')
1187
+ throw new HttpError(409, '答复状态待确认,请核对原请求', 'interaction_uncertain');
1188
+ const binding = this.store.require(owner, 'interaction-binding', id);
1189
+ const live = this.live.get(binding.key);
1190
+ if (!live || live.taskId !== binding.taskId || live.runId !== interaction.runId)
1191
+ throw new HttpError(409, '请先恢复此轮连接', 'interaction_offline');
1192
+ if (interaction.kind === 'approval' && !['once', 'session', 'always', 'deny', 'allow', 'approve', 'auto'].includes(answer))
1193
+ throw new HttpError(400, '审批选项无效', 'invalid_approval');
1194
+ const automatic = interaction.kind === 'approval' && answer === 'auto';
1195
+ interaction.answer = answer;
1196
+ interaction.responseState = 'sending';
1197
+ this.store.atomic(() => {
1198
+ // Approval replies never change the global policy.
1199
+ // Legacy auto replies approve this operation only. Global policy is admin-owned.
1200
+ this.store.put(owner, 'interaction', id, interaction);
1201
+ });
1202
+ try {
1203
+ await live.gateway.rpc(interaction.kind === 'approval' ? 'approval.respond' : 'clarify.respond', {
1204
+ session_id: live.runtimeId, request_id: binding.upstreamId,
1205
+ ...(interaction.kind === 'approval' ? { choice: automatic ? 'once' : answer } : { answer }),
1206
+ });
1207
+ }
1208
+ catch (error) {
1209
+ const latest = this.store.require(owner, 'interaction', id);
1210
+ if (!latest.resolved) {
1211
+ latest.responseState = error instanceof HttpError && error.code === 'gateway_rejected' ? undefined : 'uncertain';
1212
+ this.store.put(owner, 'interaction', id, latest);
1213
+ }
1214
+ if (automatic)
1215
+ throw new HttpError(409, '本次答复未确认,请检查当前任务状态;全局审批策略未改变。', 'approval_auto_response_failed');
1216
+ throw error;
1217
+ }
1218
+ interaction.resolved = true;
1219
+ interaction.responseState = 'sent';
1220
+ this.store.put(owner, 'interaction', id, interaction);
1221
+ this.store.event(owner, 'interaction.changed', interaction, interaction.conversationId);
1222
+ const current = this.getWork(owner, binding.taskId);
1223
+ if (current.status === 'waiting') {
1224
+ current.status = 'running';
1225
+ this.saveWork(owner, current);
1226
+ }
1227
+ }
1228
+ async interruptTurn(owner, work) {
1229
+ const key = this.bindingKey(work.conversationId, work.conversationTaskId, work.agentId);
1230
+ const live = this.live.get(key);
1231
+ if (live?.taskId === work.id) {
1232
+ try {
1233
+ await live.gateway.rpc('session.interrupt', { session_id: live.runtimeId });
1234
+ }
1235
+ catch (error) {
1236
+ if (!live.gateway.connected)
1237
+ live.done(new Error('已停止'));
1238
+ throw error;
1239
+ }
1240
+ const current = this.getWork(owner, work.id);
1241
+ if (['complete', 'failed', 'interrupted'].includes(current.status)) {
1242
+ live.done(new Error('已停止'));
1243
+ return;
1244
+ }
1245
+ current.status = 'interrupted';
1246
+ current.error = '已停止';
1247
+ this.saveWork(owner, current);
1248
+ if (current.currentMessageId) {
1249
+ const message = this.store.require(owner, 'message', current.currentMessageId);
1250
+ message.status = 'interrupted';
1251
+ message.error = '已停止';
1252
+ this.store.saveMessage(owner, message);
1253
+ }
1254
+ live.done(new Error('已停止'));
1255
+ }
1256
+ else {
1257
+ const binding = this.store.get(owner, 'binding', key);
1258
+ if (work.submitted) {
1259
+ if (!binding || binding.taskId !== work.id)
1260
+ throw new Error('无法确认待停止成员的会话身份');
1261
+ const target = binding.remoteAgentId || binding.execution === 'computer' ? this.nodes.targetForAgent(owner, { ...binding, id: work.agentId }) : this.nodes.target(owner, binding.nodeId);
1262
+ if (binding.runnerId !== target.runner?.id)
1263
+ throw new Error('执行节点已变化,无法确认原任务已停止');
1264
+ const gateway = new WorkspaceGateway(target, { workId: work.id, cleanupOnly: true, sessionId: binding.storedId, authorize: () => { const current = this.store.get(owner, 'binding', key); if (current?.taskId !== work.id || current.storedId !== binding.storedId)
1265
+ throw new Error('原会话绑定已改变'); } });
1266
+ try {
1267
+ await gateway.connect();
1268
+ const opened = await gateway.rpc('session.resume', { profile: binding.profile, session_id: binding.storedId, omit_messages: true, close_on_disconnect: false, ...(binding.execution === 'computer' ? { recoverOnly: true } : {}) });
1269
+ if (opened.running)
1270
+ await gateway.rpc('session.interrupt', { session_id: opened.session_id });
1271
+ }
1272
+ finally {
1273
+ gateway.close();
1274
+ }
1275
+ }
1276
+ const current = this.getWork(owner, work.id);
1277
+ current.status = 'interrupted';
1278
+ current.error = '已停止';
1279
+ this.saveWork(owner, current);
1280
+ if (current.currentMessageId) {
1281
+ const message = this.store.require(owner, 'message', current.currentMessageId);
1282
+ message.status = 'interrupted';
1283
+ this.store.saveMessage(owner, message);
1284
+ }
1285
+ }
1286
+ this.resolveInteractions(owner, work.id);
1287
+ }
1288
+ async stopTask(owner, conversationId, taskId, visited = new Set()) {
1289
+ const key = `${owner}:${taskId}`;
1290
+ if (visited.has(key))
1291
+ return;
1292
+ visited.add(key);
1293
+ await this.collaboration.stopFor(owner, chain => chain.originConversationId === conversationId && chain.originTaskId === taskId);
1294
+ this.tasks.cancel(owner, taskId);
1295
+ await Promise.all([super.stopTask(owner, conversationId, taskId), this.tasks.cancelOrigin(owner, conversationId, taskId, visited)]);
1296
+ }
1297
+ async stopConversation(owner, conversationId) {
1298
+ await this.collaboration.stopFor(owner, chain => chain.originConversationId === conversationId);
1299
+ for (const task of this.store.list(owner, 'conversation-task'))
1300
+ if (task.conversationId === conversationId)
1301
+ this.tasks.cancel(owner, task.id);
1302
+ await Promise.all([super.stopConversation(owner, conversationId), this.tasks.cancelOrigin(owner, conversationId)]);
1303
+ }
1304
+ recordTurnTokens(owner, agentId, input, output) {
1305
+ if (!input && !output)
1306
+ return;
1307
+ this.store.atomic(() => {
1308
+ const now = new Date(), date = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`, id = `${agentId}:${date}`;
1309
+ const day = this.store.get(owner, 'agent-token-day', id)
1310
+ ?? { agentId, date, input: 0, output: 0, total: 0, updatedAt: 0 };
1311
+ day.input += input;
1312
+ day.output += output;
1313
+ day.total += input + output;
1314
+ day.updatedAt = now.getTime();
1315
+ this.store.put(owner, 'agent-token-day', id, day);
1316
+ });
1317
+ }
1318
+ /**
1319
+ * Hermes reports cumulative per-session token counters (input/output/total) alongside
1320
+ * context occupancy. Attribute the growth since the last snapshot to the agent's daily
1321
+ * usage bucket; a session reset (counters dropping) only re-baselines.
1322
+ */
1323
+ recordAgentUsage(owner, key, agentId, usage) {
1324
+ if (!usage || typeof usage !== 'object')
1325
+ return;
1326
+ const value = usage;
1327
+ const counter = (...names) => {
1328
+ for (const name of names) {
1329
+ const raw = value[name];
1330
+ if (typeof raw === 'number' && Number.isFinite(raw) && raw >= 0)
1331
+ return Math.round(raw);
1332
+ }
1333
+ return undefined;
1334
+ };
1335
+ const input = counter('input', 'prompt', 'input_tokens'), output = counter('output', 'completion', 'output_tokens'), total = counter('total', 'total_tokens') ?? (input === undefined && output === undefined ? undefined : (input ?? 0) + (output ?? 0));
1336
+ if (total === undefined)
1337
+ return;
1338
+ this.store.atomic(() => {
1339
+ const baseline = this.store.get(owner, 'usage-baseline', key) ?? {};
1340
+ const grew = (current, previous) => (current === undefined ? 0 : Math.max(0, current - (previous ?? 0)));
1341
+ const inputDelta = grew(input, baseline.input), outputDelta = grew(output, baseline.output), totalDelta = grew(total, baseline.total);
1342
+ this.store.put(owner, 'usage-baseline', key, { input, output, total });
1343
+ if (!inputDelta && !outputDelta && !totalDelta)
1344
+ return;
1345
+ const now = new Date(), date = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`, id = `${agentId}:${date}`;
1346
+ const day = this.store.get(owner, 'agent-token-day', id)
1347
+ ?? { agentId, date, input: 0, output: 0, total: 0, updatedAt: 0 };
1348
+ day.input += inputDelta;
1349
+ day.output += outputDelta;
1350
+ day.total += Math.max(totalDelta, inputDelta + outputDelta);
1351
+ day.updatedAt = now.getTime();
1352
+ this.store.put(owner, 'agent-token-day', id, day);
1353
+ });
1354
+ }
1355
+ close() {
1356
+ this.collaboration.close();
1357
+ this.tasks.close();
1358
+ this.closeScheduler();
1359
+ for (const live of [...this.live.values()])
1360
+ live.done(new Error('服务关闭'));
1361
+ this.live.clear();
1362
+ }
1363
+ }