@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,1009 @@
1
+ import { ManagedProxy } from '../network/managedProxy.js';
2
+ import { TASK_COMMAND, redactTaskOutput } from './taskEnvironment.js';
3
+ import { randomUUID, createHash } from 'node:crypto';
4
+ import { join, dirname, posix } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { mkdir, rm } from 'node:fs/promises';
7
+ import { existsSync } from 'node:fs';
8
+ import { z } from 'zod';
9
+ import { HttpError } from '../../server/errors.js';
10
+ import { ProfileComputerSession } from './profileSession.js';
11
+ import { UNCONFIGURED_COMPUTER_IMAGE } from '../../shared/runner.js';
12
+ import { ContainerComputerProvider, ComputerError, COMPUTER_WORKSPACE, CUA_DRIVER, CUA_SOCKET } from '../computers/container.js';
13
+ import { ComputerPool } from '../computers/pool.js';
14
+ import { needsVmLease, softComputerFailure } from '../computers/computerFailures.js';
15
+ import { ComposeComputerProvider } from '../computers/compose.js';
16
+ import { COMPOSE_DESKTOP_IMAGE } from '../../shared/composeDesktops.js';
17
+ import { ComputerControls } from './control.js';
18
+ import { ComputerPublicProxy } from '../network/computerProxy.js';
19
+ import { HermesWorkerProcess } from './process.js';
20
+ import { HOST_TOOLS, hostTool, hostPath } from './hostTools.js';
21
+ import { ProfileSkillSession, SKILL_TOOLS, SKILL_RULES } from './skills.js';
22
+ import { homedir, platform } from 'node:os';
23
+ import { VM_FILE_TRANSFER_SCRIPT } from './fileTransfer.js';
24
+ import { FileTransferFiles } from '../../shared/fileTransferEndpoint.mjs';
25
+ import { copyBetweenEndpoints } from '../../server/fileTransfer.js';
26
+ const object = (properties, required) => ({ type: 'object', properties, required, additionalProperties: false });
27
+ const text = { type: 'string' };
28
+ const TOOLS = [
29
+ { name: 'computer_export', description: '将隔离电脑中的文件作为可下载附件回传当前会话,最大 25 MiB。', inputSchema: object({ path: text, name: text }, ['path']) },
30
+ { name: 'computer_shell', description: '在当前隔离电脑和 Profile 工作目录执行 shell 命令。默认使用 cua 用户;只有安装系统软件或修改系统路径时才选择 root。', inputSchema: object({ command: text, user: { type: 'string', enum: ['cua', 'root'], default: 'cua' } }, ['command']) },
31
+ { name: 'computer_read_file', description: '读取隔离电脑内的 UTF-8 文本文件。', inputSchema: object({ path: text }, ['path']) },
32
+ { name: 'computer_write_file', description: '向隔离电脑写入 UTF-8 文本文件。', inputSchema: object({ path: text, content: text }, ['path', 'content']) },
33
+ { name: 'computer_desktop_state', description: '查看虚拟环境的真实桌面,返回截图和宽高。操作前必须先看。', inputSchema: object({}, []) },
34
+ { name: 'computer_action', description: '操作虚拟环境桌面。必须先查看桌面。kind 为 click、text、key 或 scroll,坐标用截图像素。', inputSchema: object({ kind: { enum: ['click', 'drag', 'text', 'key', 'scroll'] }, x: { type: 'integer' }, y: { type: 'integer' }, fromX: { type: 'integer' }, fromY: { type: 'integer' }, toX: { type: 'integer' }, toY: { type: 'integer' }, button: { enum: ['left', 'right', 'middle'] }, count: { type: 'integer' }, text: text, key: text, modifiers: { type: 'array', items: { enum: ['ctrl', 'alt', 'shift', 'super'] } }, direction: { enum: ['up', 'down', 'left', 'right'] }, amount: { type: 'integer' } }, ['kind']) },
35
+ ];
36
+ const pathField = z.string().min(1).max(4096).refine(value => !value.includes('\0'));
37
+ const desktopAction = z.discriminatedUnion('kind', [
38
+ z.object({ kind: z.literal('click'), x: z.number().int().nonnegative(), y: z.number().int().nonnegative(), button: z.enum(['left', 'right', 'middle']).default('left'), count: z.number().int().min(1).max(2).default(1) }).strict(),
39
+ z.object({ kind: z.literal('drag'), fromX: z.number().int().nonnegative(), fromY: z.number().int().nonnegative(), toX: z.number().int().nonnegative(), toY: z.number().int().nonnegative() }).strict(),
40
+ z.object({ kind: z.literal('text'), text: z.string().max(16000) }).strict(),
41
+ z.object({ kind: z.literal('key'), key: z.string().min(1).max(40).regex(/^[A-Za-z0-9_+ -]+$/), modifiers: z.array(z.enum(['ctrl', 'alt', 'shift', 'super'])).max(4).default([]) }).strict(),
42
+ z.object({ kind: z.literal('scroll'), direction: z.enum(['up', 'down', 'left', 'right']), amount: z.number().int().min(1).max(50).default(3) }).strict(),
43
+ ]);
44
+ const PROFILE_COMPUTER_RULES = '当前使用本机协作模式:沿用基础 Profile 的本机工具、配置和上下文,本地虚拟机是独立的 Linux 电脑。computer_shell/read_file/write_file/desktop_state/action/export 只操作虚拟机;本机文件、终端和程序使用 Profile 已授权的原生工具。computer_copy_file 在两个环境间显式复制文件。调用前明确目标环境,文件路径和浏览器登录互不通用;需要回传虚拟机文件时使用 computer_export。人工接管期间停止操作,交还后先检查当前状态。';
45
+ const HERMES_COMPUTER_RULES = '本轮由 Hermes 管理模型、配置、识图、技能和授权资源。使用 Hermes 原生 skills_list、skill_view 和 skill_manage 发现、读取和维护技能;遵循当前 Profile 的技能规则。技能依赖本机登录态、环境变量或授权文件时,使用 Hermes 原生工具完成相应步骤;适合 Linux 的脚本与输入文件可经 computer_copy_file 传入虚拟机,再用 computer_shell 执行。路径、软件和登录态在本机与虚拟机之间不通用。不要自行复制 Profile 配置或凭据到虚拟机。';
46
+ const ISOLATED_COMPUTER_RULES = '当前环境是虚拟环境,也就是服务端上的隔离虚拟机。先看 computer_desktop_state,再按截图像素用 computer_action 点击、输入、按键或滚动。命令和文件也通过 computer_* 在这台 Linux 电脑内部完成。不要使用服务器或已连接电脑的终端、文件或桌面,也不要在节点离线时改去服务器或电脑。电脑和云虚拟机是另外勾选的环境,不从这台虚拟机里打开。人工接管期间停止操作,交还后先检查当前状态。';
47
+ const ISOLATED_HERMES_RULES = '本轮由 Hermes 管理模型、配置和这次会话。使用 Hermes 原生 skills_list、skill_view 和 skill_manage 发现、读取和维护技能。技能和 computer_* 都留在这台虚拟机里;不要把 Profile 的本机登录、文件或凭据复制进来。';
48
+ export class ComputerRuntime {
49
+ db;
50
+ home;
51
+ hermesTarget;
52
+ proxyPreparedRevision = -1;
53
+ proxyUpdate = Promise.resolve();
54
+ proxyUpdating = false;
55
+ proxySettings;
56
+ updateProxy(value) {
57
+ const next = value ? { ...value } : undefined;
58
+ const update = this.proxyUpdate.then(async () => {
59
+ const revision = next?.revision ?? 0, current = this.proxySettings?.revision ?? 0;
60
+ if (revision < current || revision === current && this.proxyPreparedRevision === revision)
61
+ return;
62
+ this.proxyUpdating = true;
63
+ this.proxyPreparedRevision = -1;
64
+ try {
65
+ // Close with the old specification: cleanup must still address the old
66
+ // container namespace. Concurrent updates and new leases cannot race it.
67
+ const proxies = await Promise.allSettled([...this.proxyShares.values()].map(async (share) => (await share.started.catch(() => undefined))?.close()));
68
+ this.proxyShares.clear();
69
+ const controls = await Promise.allSettled([this.controls.stopAll()]);
70
+ const gateways = await Promise.allSettled([...this.gateways.values()].flatMap(group => [...group].map(gateway => gateway.close())));
71
+ this.proxySettings = next;
72
+ if ([...proxies, ...controls, ...gateways].some(result => result.status === 'rejected'))
73
+ throw new HttpError(409, '旧网络任务未完成清理,请重试代理配置', 'computer_network_cleanup_failed');
74
+ if (next?.enabled)
75
+ await this.provider.verifyNetwork();
76
+ this.proxyPreparedRevision = revision;
77
+ }
78
+ finally {
79
+ this.proxyUpdating = false;
80
+ }
81
+ });
82
+ this.proxyUpdate = update.catch(() => { });
83
+ return update;
84
+ }
85
+ assertNetworkReady() { if (this.proxyUpdating || this.proxySettings && this.proxyPreparedRevision !== this.proxySettings.revision)
86
+ throw new HttpError(409, '虚拟机代理正在更新或尚未就绪,请重试', 'computer_network_unavailable'); }
87
+ get network() { return this.proxySettings?.enabled ? 'managed-proxy' : this.config.network ?? 'none'; }
88
+ retainDesktops = false;
89
+ controls;
90
+ provider;
91
+ pool;
92
+ ready;
93
+ config;
94
+ gateways = new Map();
95
+ workers = new Map();
96
+ script;
97
+ proxyScript;
98
+ proxyShares = new Map();
99
+ constructor(db, config, home, script, relay, hermesTarget) {
100
+ this.db = db;
101
+ this.home = home;
102
+ this.hermesTarget = hermesTarget;
103
+ if (!config.computers)
104
+ throw new HttpError(409, '执行节点尚未配置隔离电脑', 'computer_unavailable');
105
+ this.config = config.computers;
106
+ this.script = script ?? join(dirname(fileURLToPath(import.meta.url)), 'hermes_worker.py');
107
+ this.proxyScript = existsSync(join(dirname(this.script), 'guest_proxy.py')) ? join(dirname(this.script), 'guest_proxy.py') : join(dirname(this.script), '../network/guest_proxy.py');
108
+ if (this.config.managedBy === 'compose') {
109
+ if (!relay)
110
+ throw new HttpError(409, '缺少 Compose 桌面连接', 'compose_desktop_unavailable');
111
+ this.config.imageId = COMPOSE_DESKTOP_IMAGE;
112
+ this.config.network = 'none';
113
+ this.provider = new ComposeComputerProvider(config.runnerId, home, relay);
114
+ }
115
+ else
116
+ this.provider = new ContainerComputerProvider(this.config.runtime, config.runnerId, home);
117
+ this.pool = new ComputerPool(db, this.provider, { concurrent: this.config.maxConcurrent ?? 2, environments: 32, ttlMs: 30000 });
118
+ db.exec('CREATE TABLE IF NOT EXISTS retired_computers(id TEXT PRIMARY KEY,owner_key TEXT NOT NULL,spec TEXT)');
119
+ db.exec('CREATE TABLE IF NOT EXISTS computer_sessions(id TEXT PRIMARY KEY,value TEXT NOT NULL)');
120
+ db.exec('CREATE TABLE IF NOT EXISTS computer_image_bindings(id TEXT PRIMARY KEY,owner_key TEXT NOT NULL,image_id TEXT NOT NULL)');
121
+ this.controls = new ComputerControls(this);
122
+ this.ready = this.pool.recover();
123
+ void this.ready.catch(() => { });
124
+ }
125
+ attachGateway(gateway) { let gateways = this.gateways.get(gateway.meta.environmentId); if (!gateways) {
126
+ gateways = new Set();
127
+ this.gateways.set(gateway.meta.environmentId, gateways);
128
+ } gateways.add(gateway); }
129
+ detachGateway(gateway) { const gateways = this.gateways.get(gateway.meta.environmentId); if (gateways) {
130
+ gateways.delete(gateway);
131
+ if (!gateways.size)
132
+ this.gateways.delete(gateway.meta.environmentId);
133
+ } }
134
+ activeGateways(environmentId) { return [...(this.gateways.get(environmentId) ?? [])].filter(gateway => gateway.active || gateway.paused); }
135
+ /** One guest proxy per environment, shared by every holder; the guest
136
+ * reserves port 3128, so concurrent holders must never start their own. */
137
+ acquireProxy(spec, authorize) {
138
+ this.assertNetworkReady();
139
+ let share = this.proxyShares.get(spec.id);
140
+ if (!share) {
141
+ const forget = () => { if (this.proxyShares.get(spec.id) === share)
142
+ this.proxyShares.delete(spec.id); };
143
+ const started = spec.network === 'managed-proxy' ? ManagedProxy.start(this.provider, spec, this.proxySettings, authorize, forget) : ComputerPublicProxy.start(this.provider, spec, this.proxyScript, authorize, async () => authorize(), forget);
144
+ share = { started, users: 0 };
145
+ this.proxyShares.set(spec.id, share);
146
+ void started.catch(() => { if (this.proxyShares.get(spec.id) === share)
147
+ this.proxyShares.delete(spec.id); });
148
+ }
149
+ return share.started.then(proxy => {
150
+ share.users++;
151
+ let released = false;
152
+ return { proxy, release: async () => {
153
+ if (released)
154
+ return;
155
+ released = true;
156
+ const current = this.proxyShares.get(spec.id);
157
+ if (current === share && --share.users > 0)
158
+ return;
159
+ if (current === share)
160
+ this.proxyShares.delete(spec.id);
161
+ await proxy.close().catch(() => { });
162
+ } };
163
+ });
164
+ }
165
+ assertTarget(meta) { if (this.db.prepare('SELECT id FROM retired_computers WHERE id=?').get(meta.environmentId))
166
+ throw new HttpError(410, '临时电脑已退役', 'computer_retired'); }
167
+ imageFor(meta) {
168
+ const spec = this.pool.definition(meta.ownerKey, meta.environmentId);
169
+ const binding = this.db.prepare('SELECT owner_key,image_id FROM computer_image_bindings WHERE id=?').get(meta.environmentId);
170
+ if (binding && binding.owner_key !== meta.ownerKey)
171
+ throw new HttpError(403, '电脑归属不匹配', 'computer_owner_mismatch');
172
+ return spec?.imageId ?? binding?.image_id ?? this.config.imageId;
173
+ }
174
+ async retire(meta) {
175
+ const old = this.db.prepare('SELECT owner_key,spec FROM retired_computers WHERE id=?').get(meta.environmentId);
176
+ if (old && old.owner_key !== meta.ownerKey)
177
+ throw new HttpError(403, '电脑归属不匹配', 'computer_owner_mismatch');
178
+ this.pool.definition(meta.ownerKey, meta.environmentId);
179
+ this.db.prepare('INSERT OR IGNORE INTO retired_computers VALUES(?,?,NULL)').run(meta.environmentId, meta.ownerKey);
180
+ await Promise.all([...this.workers.values()].filter(worker => worker.environmentId === meta.environmentId && worker.ownerKey === meta.ownerKey).map(worker => worker.process.close()));
181
+ const current = this.pool.status(meta.ownerKey).find(row => row.environmentId === meta.environmentId);
182
+ for (const holderId of current?.holderIds ?? [])
183
+ await this.pool.stopHolder(meta.ownerKey, meta.environmentId, holderId);
184
+ let spec = old?.spec ? JSON.parse(old.spec) : undefined;
185
+ spec ??= this.pool.definition(meta.ownerKey, meta.environmentId);
186
+ if (spec)
187
+ this.db.prepare('UPDATE retired_computers SET spec=? WHERE id=?').run(JSON.stringify(spec), meta.environmentId);
188
+ await this.pool.retire(meta.ownerKey, meta.environmentId);
189
+ if (spec)
190
+ await this.provider.deleteWorkspace(spec);
191
+ const sessions = this.db.prepare('SELECT id,value FROM computer_sessions').all().filter(row => { const session = JSON.parse(row.value); return session.environmentId === meta.environmentId && session.ownerKey === meta.ownerKey; });
192
+ for (const row of sessions) {
193
+ if (!/^[0-9a-f-]{36}$/.test(row.id))
194
+ throw new Error('电脑会话编号无效');
195
+ await rm(join(this.home, 'workers', row.id), { recursive: true, force: true });
196
+ this.db.prepare('DELETE FROM computer_sessions WHERE id=?').run(row.id);
197
+ }
198
+ this.db.prepare('UPDATE retired_computers SET spec=NULL WHERE id=?').run(meta.environmentId);
199
+ }
200
+ save(session) { this.db.prepare('INSERT INTO computer_sessions VALUES(?,?) ON CONFLICT(id) DO UPDATE SET value=excluded.value').run(session.id, JSON.stringify(session)); }
201
+ session(id, meta, profile) {
202
+ const row = this.db.prepare('SELECT value FROM computer_sessions WHERE id=?').get(id);
203
+ const session = row ? JSON.parse(row.value) : undefined;
204
+ if (!session || (session.agentId ?? session.environmentId) !== meta.agentId || session.ownerKey !== meta.ownerKey || session.environmentId !== meta.environmentId || session.profile !== profile)
205
+ throw new HttpError(404, '电脑会话不存在或不属于当前任务', 'computer_session_missing');
206
+ if ((session.vmExecution === 'profile') !== (meta.profileSession === true))
207
+ throw new HttpError(409, '虚拟机执行方式已改变,请使用新会话', 'computer_session_mode_changed');
208
+ return session;
209
+ }
210
+ async resolve(profile, signal) {
211
+ if (this.hermesTarget)
212
+ throw new HttpError(409, '模型配置由 Hermes 会话管理', 'computer_hermes_owned');
213
+ return this.resolveProfile(profile, 'resolve', signal);
214
+ }
215
+ async resolveWorkspace(profile, signal) {
216
+ // VM paths belong to the VM. A Profile's host cwd is resolved by Hermes.
217
+ if (this.hermesTarget)
218
+ return { type: 'resolved', cwd: COMPUTER_WORKSPACE, configuredCwd: '.' };
219
+ return this.resolveProfile(profile, 'resolve-workspace', signal);
220
+ }
221
+ async extractMemory(profile, prompt, signal) {
222
+ if (this.hermesTarget) {
223
+ signal?.throwIfAborted();
224
+ const response = await this.hermesTarget.session.request('/api/plugins/yaoyao-bot-bridge/memory-extract', { method: 'POST', search: new URLSearchParams({ profile }), body: { profile, prompt }, maxResponseBytes: 1024 * 1024 });
225
+ signal?.throwIfAborted();
226
+ let value;
227
+ try {
228
+ value = JSON.parse(response.body.toString());
229
+ }
230
+ catch { }
231
+ if (response.status !== 200 || typeof value?.text !== 'string')
232
+ throw new HttpError(409, 'Hermes 记忆提炼接口不可用,请更新对应 Profile 的夭夭工具桥。', 'memory_extraction_unavailable');
233
+ return value.text;
234
+ }
235
+ const resolved = await this.resolve(profile, signal);
236
+ const directory = join(this.home, 'memory-extraction', randomUUID());
237
+ await mkdir(directory, { recursive: true, mode: 0o700 });
238
+ const worker = new HermesWorkerProcess(this.config.python, this.script, {
239
+ mode: 'run', home: directory, hermesSource: this.config.hermesSource, model: resolved.model,
240
+ contextConfig: resolved.contextConfig, proxyEnv: resolved.proxyEnv, sessionId: randomUUID(), taskId: randomUUID(),
241
+ cwd: directory, network: 'none', tools: [], prompt, history: [],
242
+ });
243
+ const abort = () => { void worker.close(); };
244
+ signal?.addEventListener('abort', abort, { once: true });
245
+ if (signal?.aborted)
246
+ abort();
247
+ try {
248
+ const result = await worker.wait('complete', 90000);
249
+ if (result.completed !== true || result.interrupted)
250
+ throw new HttpError(502, '记忆提炼未完成', 'memory_extraction_failed');
251
+ return String(result.text ?? '');
252
+ }
253
+ finally {
254
+ signal?.removeEventListener('abort', abort);
255
+ await worker.close();
256
+ await rm(directory, { recursive: true, force: true });
257
+ }
258
+ }
259
+ async resolveProfile(profile, mode, signal) {
260
+ const resolver = new HermesWorkerProcess(this.config.python, this.script, { mode, profile, defaultCwd: COMPUTER_WORKSPACE, hermesSource: this.config.hermesSource, hermesHome: this.config.hermesHome });
261
+ const abort = () => { void resolver.close(); };
262
+ signal?.addEventListener('abort', abort, { once: true });
263
+ if (signal?.aborted)
264
+ abort();
265
+ try {
266
+ const result = await resolver.wait('resolved');
267
+ return this.provider.fixedCapacity ? { ...result, cwd: COMPUTER_WORKSPACE } : result;
268
+ }
269
+ finally {
270
+ signal?.removeEventListener('abort', abort);
271
+ await resolver.close();
272
+ }
273
+ }
274
+ async restoreDesktop(meta, authorize) {
275
+ if (this.provider.fixedCapacity)
276
+ return;
277
+ this.assertTarget(meta);
278
+ authorize();
279
+ this.assertNetworkReady();
280
+ const spec = this.pool.definition(meta.ownerKey, meta.environmentId);
281
+ if (spec)
282
+ await this.pool.desktop({ ...spec, network: this.network }, 'restore', authorize);
283
+ }
284
+ async desktop(meta, profile, action, authorize) {
285
+ if (this.provider.fixedCapacity)
286
+ throw new HttpError(409, '桌面由 Compose 创建和管理,不能在界面增删或重建', 'compose_desktop_managed');
287
+ this.assertTarget(meta);
288
+ authorize();
289
+ // Stopping/removing an existing desktop must remain possible even when
290
+ // its Profile or model was removed or is temporarily misconfigured.
291
+ if (action === 'stop' || action === 'remove') {
292
+ const spec = this.pool.definition(meta.ownerKey, meta.environmentId);
293
+ if (spec)
294
+ await this.pool.desktop(spec, action, authorize);
295
+ return;
296
+ }
297
+ this.assertNetworkReady();
298
+ const resolved = await this.resolveWorkspace(profile);
299
+ authorize();
300
+ this.assertNetworkReady();
301
+ await this.pool.desktop({ id: meta.environmentId, ownerKey: meta.ownerKey, imageId: this.imageFor(meta), cwd: meta.environmentId !== meta.agentId ? (this.pool.definition(meta.ownerKey, meta.environmentId)?.cwd ?? COMPUTER_WORKSPACE) : resolved.cwd, network: this.network }, action, authorize);
302
+ }
303
+ }
304
+ export class ComputerGateway {
305
+ runtime;
306
+ meta;
307
+ workId;
308
+ check;
309
+ publish;
310
+ profileTarget;
311
+ onEvent = () => { };
312
+ onDisconnect = () => { };
313
+ live;
314
+ recoverySession;
315
+ closed = false;
316
+ controller = new AbortController();
317
+ timer;
318
+ checking = false;
319
+ hostCwd = homedir();
320
+ profileSession;
321
+ skillSession;
322
+ hostTransfers;
323
+ usedVmTransfers = false;
324
+ transferNamespace(live) { return createHash('sha256').update(`${this.meta.ownerKey}:${this.meta.environmentId}:${this.workId}:${live.session.id}`).digest('hex'); }
325
+ async transferFile(live, action) {
326
+ const cleanup = action.op === 'transfer-abort';
327
+ if (live.paused && !cleanup)
328
+ throw new HttpError(409, '虚拟机正在等待人工操作', 'computer_paused');
329
+ await this.authorized();
330
+ this.guard();
331
+ if (!cleanup && ['pausing', 'human', 'resuming', 'error'].includes((await this.runtime.controls.status(this.meta)).mode))
332
+ throw new HttpError(409, '虚拟机正在等待人工操作', 'computer_paused');
333
+ const input = z.object({ op: z.enum(['transfer-read-open', 'transfer-write-open', 'transfer-read', 'transfer-append', 'transfer-finish', 'transfer-status', 'transfer-abort']), transferId: z.string().uuid(), path: z.string().min(1).max(4096).optional(), maxBytes: z.number().int().min(1024 * 1024).max(100 * 1024 * 1024).optional(), size: z.number().int().min(0).max(100 * 1024 * 1024).optional(), sha256: z.string().regex(/^[a-f0-9]{64}$/).optional(), overwrite: z.boolean().optional(), offset: z.number().int().min(0).max(100 * 1024 * 1024).optional(), data: z.string().max(699052).optional() }).strict().parse(action);
334
+ const lease = await this.ensureLease(live);
335
+ this.usedVmTransfers = true;
336
+ return this.runtime.pool.use(lease, async (context) => {
337
+ if (live.paused && !cleanup)
338
+ throw new HttpError(409, '虚拟机正在等待人工操作', 'computer_paused');
339
+ const result = await this.runtime.provider.execute(this.spec(live.session), ['python3', '-c', VM_FILE_TRANSFER_SCRIPT, this.transferNamespace(live)], { ...context, input: Buffer.from(JSON.stringify(input)) });
340
+ context.authorize();
341
+ this.guard();
342
+ return JSON.parse(result.stdout);
343
+ });
344
+ }
345
+ taskEnvironment;
346
+ get hermesManaged() { return this.meta.hermesRuntime === true; }
347
+ get rules() { const sharing = this.meta.environmentId !== this.meta.agentId ? '多个机器人共用这台虚拟机:命令和文件操作并行执行,桌面操作交替进行;动手前注意其他机器人可能正在使用同一桌面,避免覆盖彼此的工作。' : ''; if (this.meta.profileSession)
348
+ return `${sharing}${PROFILE_COMPUTER_RULES}\n${this.hermesManaged ? HERMES_COMPUTER_RULES : SKILL_RULES}`; return `${sharing}${ISOLATED_COMPUTER_RULES}\n${this.hermesManaged ? ISOLATED_HERMES_RULES : SKILL_RULES}`; }
349
+ team;
350
+ constructor(runtime, meta, workId, check, publish, profileTarget) {
351
+ this.runtime = runtime;
352
+ this.meta = meta;
353
+ this.workId = workId;
354
+ this.check = check;
355
+ this.publish = publish;
356
+ this.profileTarget = profileTarget;
357
+ }
358
+ async connect() { this.runtime.assertTarget(this.meta); await this.runtime.ready; await this.authorized(); if (this.hermesManaged && !this.profileTarget)
359
+ throw new HttpError(409, '缺少 Hermes 会话连接,不能回退到独立 Worker。', 'computer_profile_unavailable'); }
360
+ async authorized() { try {
361
+ await this.check();
362
+ this.guard();
363
+ }
364
+ catch (error) {
365
+ const stopping = this.interrupt().catch(() => { });
366
+ if (!this.profileSession)
367
+ await stopping;
368
+ if (!this.closed)
369
+ this.onDisconnect();
370
+ throw error;
371
+ } }
372
+ guard() { if (this.closed || this.live?.controller.signal.aborted)
373
+ throw new HttpError(410, '电脑任务授权已结束', 'computer_cancelled'); }
374
+ event(type, payload) { if (!this.closed && this.live)
375
+ this.onEvent({ type, session_id: this.live.session.id, payload }); }
376
+ spec(session) { return { id: this.meta.environmentId, ownerKey: this.meta.ownerKey, imageId: this.runtime.imageFor(this.meta), cwd: session.cwd, network: this.runtime.network }; }
377
+ async rpc(method, params) {
378
+ if ((method === 'session.interrupt' || method === 'session.close') && params.session_id === this.live?.session.id) {
379
+ await this.interrupt();
380
+ return { status: 'interrupted' };
381
+ }
382
+ if ((method === 'session.interrupt' || method === 'session.close') && params.session_id === this.recoverySession?.id) {
383
+ await this.runtime.pool.stopHolder(this.meta.ownerKey, this.meta.environmentId, this.workId);
384
+ return { status: 'interrupted' };
385
+ }
386
+ this.guard();
387
+ if (method === 'session.create' || method === 'session.resume') {
388
+ if (this.live)
389
+ throw new HttpError(409, '电脑通道已有会话', 'computer_session_busy');
390
+ await this.authorized();
391
+ if (method === 'session.resume' && params.recoverOnly === true) {
392
+ const session = this.runtime.session(String(params.session_id), this.meta, String(params.profile));
393
+ this.recoverySession = session;
394
+ if (session.profileSessionId) {
395
+ await this.openProfile(session, params);
396
+ await this.profileSession.stop();
397
+ }
398
+ const resource = this.runtime.pool.status(this.meta.ownerKey).find(item => item.environmentId === this.meta.environmentId);
399
+ if (resource?.holderIds.includes(this.workId))
400
+ await this.runtime.pool.stopHolder(this.meta.ownerKey, this.meta.environmentId, this.workId);
401
+ return { session_id: session.id, stored_session_id: session.id, running: false, info: { profile_name: session.profile } };
402
+ }
403
+ const profile = String(params.profile), resolved = this.hermesManaged ? { cwd: this.runtime.pool.definition(this.meta.ownerKey, this.meta.environmentId)?.cwd ?? COMPUTER_WORKSPACE, configuredCwd: '.' } : await (this.meta.profileSession ? this.runtime.resolveWorkspace(profile, this.controller.signal) : this.runtime.resolve(profile, this.controller.signal));
404
+ if (this.meta.hostAccess) {
405
+ const configured = String(resolved.configuredCwd ?? '.');
406
+ this.hostCwd = ['.', 'auto', 'cwd'].includes(configured) ? homedir() : hostPath(homedir(), configured);
407
+ }
408
+ await this.authorized();
409
+ this.guard();
410
+ const session = method === 'session.resume' ? this.runtime.session(String(params.session_id), this.meta, profile) : { id: randomUUID(), agentId: this.meta.agentId, ownerKey: this.meta.ownerKey, environmentId: this.meta.environmentId, profile, cwd: resolved.cwd, configuredCwd: resolved.configuredCwd, history: [] };
411
+ if (this.meta.profileSession)
412
+ session.vmExecution = 'profile';
413
+ if (this.hermesManaged)
414
+ session.hermesRuntime = true;
415
+ session.cwd = this.meta.environmentId !== this.meta.agentId ? (this.runtime.pool.definition(this.meta.ownerKey, this.meta.environmentId)?.cwd ?? COMPUTER_WORKSPACE) : resolved.cwd;
416
+ session.configuredCwd = resolved.configuredCwd;
417
+ // Defer pool.configure/acquire until a computer_* (or skill) tool actually needs the VM.
418
+ const controller = new AbortController();
419
+ this.live = { toolsOnly: params.toolsOnly === true, session, controller, model: ('model' in resolved ? resolved.model : undefined), contextConfig: 'contextConfig' in resolved ? resolved.contextConfig : undefined, proxyEnv: 'proxyEnv' in resolved ? resolved.proxyEnv : undefined, images: [], running: false, received: false, toolCalls: new Set(), journal: new Map() };
420
+ this.runtime.save(session);
421
+ this.runtime.attachGateway(this);
422
+ if (params.toolsOnly === true)
423
+ return { session_id: session.id, stored_session_id: session.id, running: false, info: { profile_name: profile, tools_only: true } };
424
+ if (this.meta.profileSession || this.hermesManaged) {
425
+ try {
426
+ const opened = await this.openProfile(session, params);
427
+ return { ...opened, session_id: session.id, stored_session_id: session.id };
428
+ }
429
+ catch (error) {
430
+ await this.interrupt();
431
+ throw error;
432
+ }
433
+ }
434
+ return { session_id: session.id, stored_session_id: session.id, running: false, info: { profile_name: profile } };
435
+ }
436
+ const live = this.live;
437
+ if (method === 'computer.complete') {
438
+ if (!live?.toolsOnly || params.session_id !== live.session.id)
439
+ throw new HttpError(403, '完成请求不属于当前虚拟机工具会话', 'computer_session_forbidden');
440
+ // Normal Bot completion releases its holder into the idle policy. An
441
+ // unexpected disconnect still takes the interrupt/fencing path.
442
+ live.received = true;
443
+ live.finishing ??= (async () => {
444
+ await Promise.allSettled([...live.toolCalls]);
445
+ await this.authorized();
446
+ await this.release(live, this.runtime.retainDesktops);
447
+ live.session.outcome = 'complete';
448
+ this.runtime.save(live.session);
449
+ })();
450
+ await live.finishing;
451
+ return { status: 'complete' };
452
+ }
453
+ if (live?.toolsOnly && live.received)
454
+ throw new HttpError(410, '本轮虚拟机工具会话已结束', 'computer_cancelled');
455
+ if (method === 'computer.transfer') {
456
+ if (!live || params.session_id !== live.session.id)
457
+ throw new HttpError(403, '文件传输不属于当前电脑会话', 'computer_session_forbidden');
458
+ const call = this.transferFile(live, z.record(z.string(), z.unknown()).parse(params.action));
459
+ live.toolCalls.add(call);
460
+ void call.finally(() => live.toolCalls.delete(call)).catch(() => { });
461
+ return call;
462
+ }
463
+ if (method === 'computer.invoke') {
464
+ if (!live || params.session_id !== live.session.id)
465
+ throw new HttpError(403, '电脑会话不属于当前通道', 'computer_session_forbidden');
466
+ const name = String(params.name ?? '');
467
+ if (!TOOLS.some(tool => tool.name === name))
468
+ throw new HttpError(403, '本轮未授权该工具', 'computer_tool_forbidden');
469
+ const call = this.tool(live, name, params.arguments ?? {}, typeof params.id === 'string' && params.id ? params.id : randomUUID());
470
+ live.toolCalls.add(call);
471
+ void call.finally(() => live.toolCalls.delete(call)).catch(() => { });
472
+ return call;
473
+ }
474
+ if (!live || params.session_id !== live.session.id)
475
+ throw new HttpError(403, '电脑会话不属于当前通道', 'computer_session_forbidden');
476
+ if (method === 'session.interrupt' || method === 'session.close') {
477
+ await this.interrupt();
478
+ return { status: 'interrupted' };
479
+ }
480
+ if (this.profileSession) {
481
+ if (method === 'session.usage')
482
+ return this.profileSession.rpc(method, params);
483
+ if (live.paused)
484
+ throw new HttpError(409, '电脑正在等待人工操作', 'computer_paused');
485
+ await this.authorized();
486
+ if (method === 'prompt.submit') {
487
+ if (live.running || live.received)
488
+ throw new HttpError(409, '电脑会话已经提交过本轮', 'computer_session_busy');
489
+ if (typeof params.workMarker === 'string' && /^\[yaoyao-run:[0-9a-f-]{36}:[0-9a-f-]{36}\]$/.test(params.workMarker))
490
+ live.workMarker = params.workMarker;
491
+ await this.profileSession.bind();
492
+ this.guard();
493
+ live.running = true;
494
+ live.session.outcome = 'uncertain';
495
+ this.runtime.save(live.session);
496
+ return this.profileSession.rpc(method, { ...params, text: `${this.rules}\n${String(params.text ?? '')}` });
497
+ }
498
+ return this.profileSession.rpc(method, params);
499
+ }
500
+ if (method === 'session.usage')
501
+ return {};
502
+ if (method === 'session.cwd.set') {
503
+ if (params.cwd !== live.session.cwd && params.cwd !== live.session.configuredCwd)
504
+ throw new HttpError(403, '工作目录必须采用基础 Profile 的配置', 'computer_cwd_forbidden');
505
+ return { cwd: live.session.cwd };
506
+ }
507
+ if (method === 'file.attach' || method === 'image.attach_bytes') {
508
+ if (live.running)
509
+ throw new HttpError(409, '当前轮次已开始,不能追加附件', 'computer_session_busy');
510
+ await this.authorized();
511
+ const name = String(params.name ?? params.filename ?? 'attachment').replace(/[\/\\\u0000-\u001f]/g, '_').slice(0, 200) || 'attachment';
512
+ const encoded = method === 'image.attach_bytes' ? String(params.content_base64 ?? '') : String(params.data_url ?? '').split(',')[1] ?? '';
513
+ const bytes = Buffer.from(encoded, 'base64');
514
+ if (bytes.length > 25 * 1024 * 1024)
515
+ throw new HttpError(413, '附件超过 25 MiB', 'attachment_too_large');
516
+ const relative = `.yaoyao-inputs/${randomUUID()}/${name}`;
517
+ await this.ensureLease(live);
518
+ await this.runtime.pool.use(live.lease, context => this.runtime.provider.execute(this.spec(live.session), ['python3', '-c', 'import sys,pathlib; p=pathlib.Path(sys.argv[1]); p.parent.mkdir(parents=True,exist_ok=True); p.write_bytes(sys.stdin.buffer.read())', relative], { ...context, input: bytes }));
519
+ if (method === 'image.attach_bytes') {
520
+ const mime = String(params.mime_type ?? 'image/png');
521
+ if (!/^image\/(?:png|jpeg|webp|gif)$/.test(mime))
522
+ throw new HttpError(400, '图片格式无效', 'invalid_image');
523
+ if (JSON.stringify(live.images).length + encoded.length > 64 * 1024 * 1024)
524
+ throw new HttpError(413, '本轮图片总量超过限制', 'image_limit');
525
+ live.images.push({ type: 'image_url', image_url: { url: `data:${mime};base64,${encoded}` } });
526
+ }
527
+ return { ref_text: `[附件 ${name}](${live.session.cwd}/${relative})` };
528
+ }
529
+ if (method === 'prompt.submit') {
530
+ if (live.running || live.received)
531
+ throw new HttpError(409, '电脑会话已经提交过本轮', 'computer_session_busy');
532
+ await this.authorized();
533
+ this.guard();
534
+ if (typeof params.workMarker === 'string' && /^\[yaoyao-run:[0-9a-f-]{36}:[0-9a-f-]{36}\]$/.test(params.workMarker))
535
+ live.workMarker = params.workMarker;
536
+ await this.startModel(live, String(params.text ?? ''), structuredClone(live.session.history));
537
+ return { status: 'streaming' };
538
+ }
539
+ throw new HttpError(409, '当前隔离 Worker 不支持此交互', 'computer_method_unavailable');
540
+ }
541
+ async openProfile(session, params) {
542
+ if (!this.profileTarget)
543
+ throw new HttpError(409, '缺少本机 Profile 连接,请更新执行节点', 'computer_profile_unavailable');
544
+ if (params.session_id && !session.profileSessionId)
545
+ throw new HttpError(409, '本机 Profile 会话尚未建立,请新建会话', 'computer_profile_session_invalid');
546
+ const native = new ProfileComputerSession(this.profileTarget, session.profile, this.workId, () => this.guard(), () => [...TOOLS, ...(this.hermesManaged ? [] : SKILL_TOOLS), ...HOST_TOOLS.filter(tool => tool.name === 'computer_copy_file').map(tool => ({ ...tool, description: tool.description.replace('25 MiB', `${(this.meta.fileTransferMaxBytes ?? 25 * 1024 * 1024) / 1024 / 1024} MiB`) })), ...(this.team?.catalog ?? [])], async (name, args) => {
547
+ const live = this.live;
548
+ if (!live || !this.active || live.paused)
549
+ throw new HttpError(410, '本轮电脑工具已结束或暂停', 'computer_cancelled');
550
+ const call = this.tool(live, name, args, randomUUID());
551
+ live.toolCalls.add(call);
552
+ void call.finally(() => live.toolCalls.delete(call)).catch(() => { });
553
+ return call;
554
+ }, this.hermesManaged ? { mode: this.meta.profileSession ? 'profile' : 'isolated', hostAccess: this.meta.hostAccess === true } : undefined, () => this.team?.workspaceMemory === true);
555
+ this.profileSession = native;
556
+ native.onStoredId = id => { session.profileSessionId = id; this.runtime.save(session); };
557
+ native.onDisconnect = () => { void this.interrupt().finally(() => { if (!this.closed)
558
+ this.onDisconnect(); }).catch(() => { }); };
559
+ native.onEvent = frame => {
560
+ const live = this.live;
561
+ if (!live || this.closed || live.controller.signal.aborted || live.paused || live.received)
562
+ return;
563
+ if (['message.complete', 'run.completed', 'run.failed', 'message.error', 'error'].includes(frame.type)) {
564
+ live.received = true;
565
+ live.finishing = this.finishProfile(live, frame);
566
+ void live.finishing.catch(() => this.lost(live));
567
+ }
568
+ else
569
+ this.event(frame.type, frame.type === 'session.info' ? { ...frame.payload, stored_session_id: session.id, session_key: session.id } : frame.payload ?? {});
570
+ };
571
+ return native.open(session.profileSessionId, params);
572
+ }
573
+ async finishProfile(live, frame) {
574
+ await Promise.allSettled([...live.toolCalls]);
575
+ await this.authorized();
576
+ const payload = frame.payload ?? {}, success = ['message.complete', 'run.completed'].includes(frame.type) && !payload.error && !['interrupted', 'failed', 'error'].includes(String(payload.status));
577
+ live.session.outcome = success ? 'complete' : 'failed';
578
+ this.runtime.save(live.session);
579
+ await this.release(live, this.runtime.retainDesktops && success);
580
+ live.running = false;
581
+ if (this.closed || live.controller.signal.aborted)
582
+ return;
583
+ this.event(frame.type, { ...payload, ...(payload.status === 'error' ? { status: 'failed' } : {}) });
584
+ }
585
+ async startModel(live, prompt, history) {
586
+ if (this.hermesManaged)
587
+ throw new HttpError(409, 'Hermes 托管会话不能启动独立 Worker', 'computer_hermes_owned');
588
+ live.received = false;
589
+ live.running = true;
590
+ live.session.outcome = 'uncertain';
591
+ live.session.history.push({ role: 'user', content: prompt });
592
+ this.runtime.save(live.session);
593
+ const directory = join(this.runtime.home, 'workers', live.session.id, this.workId, String(live.segment = (live.segment ?? 0) + 1));
594
+ await mkdir(directory, { recursive: true, mode: 0o700 });
595
+ const worker = new HermesWorkerProcess(this.runtime.config.python, this.runtime.script, { mode: 'run', home: directory, hermesSource: this.runtime.config.hermesSource, model: live.model, contextConfig: live.contextConfig, proxyEnv: live.proxyEnv, sessionId: live.session.id, taskId: this.workId, cwd: live.session.cwd, ...(this.meta.hostAccess ? { host: { cwd: this.hostCwd, platform: platform() } } : {}), network: this.runtime.network, tools: [...TOOLS, ...SKILL_TOOLS, ...(this.meta.hostAccess ? HOST_TOOLS.map(tool => tool.name === 'computer_copy_file' ? { ...tool, description: tool.description.replace('25 MiB', `${(this.meta.fileTransferMaxBytes ?? 25 * 1024 * 1024) / 1024 / 1024} MiB`) } : tool) : []), ...(this.team?.catalog ?? [])], skillInstructions: SKILL_RULES, prompt: live.images.length ? [{ type: 'text', text: prompt }, ...live.images] : prompt, history });
596
+ live.worker = worker;
597
+ this.runtime.workers.set(this.workId, { environmentId: this.meta.environmentId, ownerKey: this.meta.ownerKey, process: worker });
598
+ void worker.exited.then(() => { if (this.runtime.workers.get(this.workId)?.process === worker)
599
+ this.runtime.workers.delete(this.workId); });
600
+ worker.onTool = (name, args, id, callId) => {
601
+ if (live.worker !== worker || live.received)
602
+ throw new HttpError(410, '本轮 Worker 已结束', 'computer_worker_finished');
603
+ const task = this.tool(live, name, args, id).then(result => { if (callId)
604
+ live.journal.set(callId, { name, result }); return result; }, error => { if (callId)
605
+ live.journal.set(callId, { name, result: { error: '操作未完成或已中断' } }); throw error; });
606
+ live.toolCalls.add(task);
607
+ void task.finally(() => live.toolCalls.delete(task)).catch(() => { });
608
+ return task;
609
+ };
610
+ worker.onEvent = frame => {
611
+ if (this.closed || live.worker !== worker || live.received || live.controller.signal.aborted)
612
+ return;
613
+ if (frame.type === 'checkpoint' && Array.isArray(frame.messages)) {
614
+ live.session.history = frame.messages;
615
+ this.runtime.save(live.session);
616
+ return;
617
+ }
618
+ if (live.paused)
619
+ return;
620
+ if (frame.type === 'delta')
621
+ this.event('message.delta', { text: frame.text });
622
+ if (frame.type === 'reasoning')
623
+ this.event('reasoning.delta', { text: frame.text });
624
+ if (frame.type === 'complete') {
625
+ live.received = true;
626
+ live.finishing = this.finish(live, frame);
627
+ void live.finishing.catch(() => this.lost(live));
628
+ }
629
+ if (frame.type === 'failed')
630
+ void this.lost(live);
631
+ };
632
+ void worker.exited.then(() => { if (!live.paused && !live.received && live.running && !this.closed)
633
+ void this.lost(live); });
634
+ }
635
+ installTeamLease(id, catalog, call, workspaceMemory = false) { this.team = { id, catalog, call, workspaceMemory }; }
636
+ removeTeamLease(id) { if (this.team?.id === id)
637
+ this.team = undefined; }
638
+ ensureLease(live) {
639
+ this.runtime.assertNetworkReady();
640
+ if (live.proxyHandle?.proxy instanceof ManagedProxy && live.proxyHandle.proxy.closed)
641
+ throw new HttpError(409, '虚拟机代理连接已断开,请开始新一轮任务', 'computer_network_disconnected');
642
+ if (live.lease)
643
+ return Promise.resolve(live.lease);
644
+ live.acquiring ??= (async () => {
645
+ if (this.runtime.imageFor(this.meta) === UNCONFIGURED_COMPUTER_IMAGE)
646
+ throw new HttpError(409, '请先在应用设置的本地虚拟机页面完成准备', 'computer_image_required');
647
+ await this.runtime.pool.configure(this.spec(live.session), () => this.guard());
648
+ await this.authorized();
649
+ const lease = await this.runtime.pool.acquire(this.spec(live.session), this.workId, () => { this.guard(); if (live.controller.signal.aborted)
650
+ throw new Error('cancelled'); }, live.controller.signal);
651
+ if (this.closed) {
652
+ await this.runtime.pool.release(lease);
653
+ throw new Error('电脑通道已关闭');
654
+ }
655
+ live.lease = lease;
656
+ if (this.runtime.network !== 'none') {
657
+ try {
658
+ live.proxyHandle = await this.runtime.acquireProxy(this.spec(live.session), () => { if (!this.runtime.pool.hasHolders(this.meta.ownerKey, this.meta.environmentId))
659
+ throw new HttpError(403, '电脑任务授权已失效', 'computer_authorization_revoked'); });
660
+ }
661
+ catch (error) {
662
+ await this.runtime.pool.release(lease).catch(() => { });
663
+ live.lease = undefined;
664
+ throw error;
665
+ }
666
+ }
667
+ this.timer = setInterval(() => { if (this.checking || !this.live?.lease)
668
+ return; this.checking = true; void this.authorized().then(() => this.runtime.pool.renew(this.live.lease)).catch(async () => { await this.interrupt().catch(() => { }); if (!this.closed)
669
+ this.onDisconnect(); }).finally(() => { this.checking = false; }); }, 5000);
670
+ this.timer.unref();
671
+ return lease;
672
+ })().finally(() => { live.acquiring = undefined; });
673
+ return live.acquiring;
674
+ }
675
+ async tool(live, name, args, id) {
676
+ if (live.paused)
677
+ throw new HttpError(409, '电脑正在等待人工操作', 'computer_paused');
678
+ await this.authorized();
679
+ this.guard();
680
+ if (live.paused)
681
+ throw new HttpError(409, '电脑正在等待人工操作', 'computer_paused');
682
+ this.event('tool.started', { tool_id: id, name });
683
+ try {
684
+ const team = this.team?.catalog.find(tool => tool.name === name);
685
+ if (team)
686
+ return await this.team.call(team.id ?? name, z.record(z.string(), z.unknown()).parse(args), id);
687
+ if (name.startsWith('host_') && !this.meta.hostAccess || name === 'computer_copy_file' && !this.meta.hostAccess && !this.hermesManaged)
688
+ throw new HttpError(403, '本轮未授权该工具', 'computer_tool_forbidden');
689
+ if (this.meta.hostAccess && name.startsWith('host_'))
690
+ return await hostTool(name, args, { cwd: this.hostCwd, signal: live.controller.signal, authorize: () => { this.guard(); if (live.paused)
691
+ throw new HttpError(409, '电脑正在等待人工操作', 'computer_paused'); } });
692
+ if ((this.meta.hostAccess || this.hermesManaged) && name === 'computer_copy_file') {
693
+ const body = z.object({ from: z.enum(['host', 'vm']), source: pathField, destination: pathField }).strict().parse(args);
694
+ const limit = this.meta.fileTransferMaxBytes ?? 25 * 1024 * 1024;
695
+ const hostPathValue = body.from === 'host' ? body.source : body.destination;
696
+ this.hostTransfers ??= new FileTransferFiles(this.hostCwd, { confined: false });
697
+ const host = { host: 'server', name: '执行节点本机', path: hostPathValue, chunks: true, call: async (action) => {
698
+ await this.authorized();
699
+ this.guard();
700
+ if (this.hermesManaged)
701
+ return this.profileSession.transfer(body.from === 'host' ? 'read' : 'write', hostPathValue, action);
702
+ const result = await this.hostTransfers.call({ ...action, ...(action.path ? { path: hostPath(this.hostCwd, String(action.path)) } : {}) }, () => { this.guard(); if (live.paused)
703
+ throw new HttpError(409, '电脑正在等待人工操作', 'computer_paused'); });
704
+ return result.path ? { ...result, path: hostPathValue } : result;
705
+ } };
706
+ const vm = { host: 'vm', name: '虚拟机', path: body.from === 'host' ? body.destination : body.source, chunks: true, call: (action) => this.transferFile(live, action) };
707
+ await copyBetweenEndpoints(body.from === 'host' ? host : vm, body.from === 'host' ? vm : host, limit, true, () => { this.guard(); if (live.paused)
708
+ throw new HttpError(409, '电脑正在等待人工操作', 'computer_paused'); });
709
+ return { ok: true };
710
+ }
711
+ if (needsVmLease(name, this.team?.catalog.map(tool => tool.name) ?? [], SKILL_TOOLS.map(tool => tool.name))) {
712
+ try {
713
+ await this.ensureLease(live);
714
+ }
715
+ catch (error) {
716
+ if (softComputerFailure(error)) {
717
+ const message = error instanceof Error && error.message ? error.message : '电脑环境不可用';
718
+ return { error: message, code: error instanceof HttpError || error instanceof ComputerError ? error.code : 'computer_unavailable' };
719
+ }
720
+ throw error;
721
+ }
722
+ }
723
+ const lease = live.lease;
724
+ if (SKILL_TOOLS.some(tool => tool.name === name)) {
725
+ if (!lease)
726
+ throw new HttpError(409, '电脑环境尚未就绪', 'computer_unavailable');
727
+ this.skillSession ??= new ProfileSkillSession({
728
+ python: this.runtime.config.python, script: this.runtime.script, hermesSource: this.runtime.config.hermesSource, hermesHome: this.runtime.config.hermesHome,
729
+ profile: live.session.profile, ownerKey: this.meta.ownerKey, agentId: this.meta.agentId, taskId: this.workId, signal: live.controller.signal,
730
+ authorize: async () => { await this.authorized(); if (live.paused || live.received)
731
+ throw new HttpError(410, '本轮技能工具已结束或暂停', 'computer_cancelled'); this.runtime.pool.authorize(lease); },
732
+ execute: (argv, input) => this.runtime.pool.use(lease, context => this.runtime.provider.execute(this.spec(live.session), argv, { ...context, input })),
733
+ install: (bundle, script) => this.runtime.pool.use(lease, context => this.runtime.provider.installSkill(this.spec(live.session), bundle, script, context)),
734
+ });
735
+ return await this.skillSession.call(name, args);
736
+ }
737
+ if (!lease)
738
+ throw new HttpError(409, '电脑环境尚未就绪', 'computer_unavailable');
739
+ return await this.runtime.pool.use(lease, async (context) => {
740
+ const execute = (argv, input, lane, user) => this.runtime.provider.execute(this.spec(live.session), argv, { ...context, input, ...(lane ? { lane } : {}), ...(user ? { user } : {}) });
741
+ if (name === 'computer_export') {
742
+ const body = z.object({ path: pathField, name: z.string().min(1).max(240).optional() }).strict().parse(args);
743
+ const snapshot = `/tmp/yaoyao-export-${randomUUID()}`;
744
+ try {
745
+ const metadata = JSON.parse((await execute(['python3', '-c', 'import pathlib,sys,shutil,json,hashlib; p=pathlib.Path(sys.argv[1]); assert p.is_file(),"not a file"; assert p.stat().st_size<=25*1024*1024,"file too large"; shutil.copyfile(p,sys.argv[2]); b=pathlib.Path(sys.argv[2]).read_bytes(); assert len(b)<=25*1024*1024,"file too large"; print(json.dumps({"size":len(b),"digest":hashlib.sha256(b).hexdigest()}))', body.path, snapshot])).stdout);
746
+ await this.publish({ phase: 'begin', id, name: body.name ?? posix.basename(body.path), size: metadata.size, digest: metadata.digest });
747
+ for (let offset = 0, index = 0; offset < metadata.size; offset += 524288, index++) {
748
+ context.authorize();
749
+ await this.authorized();
750
+ const data = (await execute(['python3', '-c', 'import sys,base64; f=open(sys.argv[1],"rb"); f.seek(int(sys.argv[2])); print(base64.b64encode(f.read(524288)).decode())', snapshot, String(offset)])).stdout.trim();
751
+ await this.publish({ phase: 'append', id, index, data });
752
+ }
753
+ context.authorize();
754
+ await this.authorized();
755
+ return (await this.publish({ phase: 'finish', id })).result;
756
+ }
757
+ finally {
758
+ await execute(['rm', '-f', '--', snapshot]).catch(() => { });
759
+ }
760
+ }
761
+ if (name === 'computer_shell') {
762
+ const body = z.object({ command: z.string().min(1).max(65536), user: z.enum(['cua', 'root']).default('cua') }).strict().parse(args);
763
+ const environment = await this.taskEnvironment?.();
764
+ try {
765
+ const result = environment ? await execute(['python3', '-c', TASK_COMMAND], Buffer.from(JSON.stringify({ command: body.command, environment })), undefined, body.user) : await execute(['/bin/bash', '-lc', body.command], undefined, undefined, body.user);
766
+ await this.authorized();
767
+ return redactTaskOutput({ exitCode: 0, ...result }, environment);
768
+ }
769
+ catch (error) {
770
+ if (typeof error.code === 'number')
771
+ return redactTaskOutput({ exitCode: error.code, stdout: String(error.stdout ?? ''), stderr: String(error.stderr ?? '') }, environment);
772
+ throw error;
773
+ }
774
+ }
775
+ if (name === 'computer_read_file') {
776
+ const body = z.object({ path: pathField }).strict().parse(args);
777
+ return execute(['python3', '-c', 'import sys; f=open(sys.argv[1],encoding="utf-8"); s=f.read(1000001); assert len(s)<=1000000,"file too large"; print(s,end="")', body.path]);
778
+ }
779
+ if (name === 'computer_write_file') {
780
+ const body = z.object({ path: pathField, content: z.string().max(1000000) }).strict().parse(args);
781
+ await execute(['python3', '-c', 'import pathlib,sys; p=pathlib.Path(sys.argv[1]); p.parent.mkdir(parents=True,exist_ok=True); p.write_bytes(sys.stdin.buffer.read())', body.path], Buffer.from(body.content));
782
+ return { ok: true };
783
+ }
784
+ if (name === 'computer_action') {
785
+ if (!live.desktop)
786
+ throw new HttpError(409, '请先查看虚拟环境桌面', 'computer_frame_stale');
787
+ const frame = live.desktop, action = desktopAction.parse(args), common = { scope: 'desktop', session: `yaoyao-vm-${live.session.id}` };
788
+ let tool, toolArgs, argv;
789
+ if (action.kind === 'click') {
790
+ if (action.x >= frame.width || action.y >= frame.height)
791
+ throw new HttpError(400, '点击位置超出画面', 'computer_point_invalid');
792
+ tool = 'click';
793
+ toolArgs = { ...common, x: action.x, y: action.y, button: action.button, count: action.count };
794
+ }
795
+ else if (action.kind === 'drag') {
796
+ if (action.fromX >= frame.width || action.toX >= frame.width || action.fromY >= frame.height || action.toY >= frame.height)
797
+ throw new HttpError(400, '拖动位置超出画面', 'computer_point_invalid');
798
+ tool = 'drag';
799
+ toolArgs = {};
800
+ argv = ['env', 'DISPLAY=:1', 'xdotool', 'mousemove', '--sync', String(action.fromX), String(action.fromY), 'mousedown', '1', 'mousemove', '--sync', String(action.toX), String(action.toY), 'mouseup', '1'];
801
+ }
802
+ else if (action.kind === 'text') {
803
+ tool = 'type_text';
804
+ toolArgs = { ...common, text: action.text };
805
+ }
806
+ else if (action.kind === 'key') {
807
+ const key = { Return: 'enter', BackSpace: 'backspace', Escape: 'esc' }[action.key] ?? action.key.toLowerCase();
808
+ tool = action.modifiers.length ? 'hotkey' : 'press_key';
809
+ toolArgs = action.modifiers.length ? { ...common, keys: [...action.modifiers, key] } : { ...common, key };
810
+ }
811
+ else {
812
+ tool = 'scroll';
813
+ toolArgs = { ...common, x: Math.floor(frame.width / 2), y: Math.floor(frame.height / 2), by: 'line', direction: action.direction, amount: action.amount };
814
+ }
815
+ live.desktop = undefined;
816
+ const response = await execute(argv ?? [CUA_DRIVER, 'call', tool, JSON.stringify(toolArgs), '--socket', CUA_SOCKET], undefined, 'gui');
817
+ let parsed;
818
+ try {
819
+ parsed = JSON.parse(response.stdout);
820
+ }
821
+ catch { }
822
+ if (parsed?.code || parsed?.error || parsed?.isError)
823
+ throw new HttpError(502, '电脑未接受这次输入,请刷新画面后重试', 'computer_action_failed');
824
+ return { ok: true };
825
+ }
826
+ if (name === 'computer_desktop_state') {
827
+ z.object({}).strict().parse(args);
828
+ const path = `/tmp/yaoyao-frame-${randomUUID()}.png`;
829
+ const state = await execute([CUA_DRIVER, 'call', 'get_desktop_state', '{}', '--socket', CUA_SOCKET, '--screenshot-out-file', path], undefined, 'gui');
830
+ const data = (await execute(['base64', '-w0', path])).stdout.trim();
831
+ const header = Buffer.from(data.slice(0, 32), 'base64'), width = header.length >= 24 ? header.readUInt32BE(16) : 0, height = header.length >= 24 ? header.readUInt32BE(20) : 0;
832
+ if (width < 1 || height < 1)
833
+ throw new HttpError(502, '虚拟环境画面无效', 'computer_frame_failed');
834
+ live.desktop = { width, height };
835
+ return { _multimodal: true, width, height, text_summary: state.stdout, content: [{ type: 'image_url', image_url: { url: `data:image/png;base64,${data}` } }] };
836
+ }
837
+ throw new HttpError(403, '本轮未授权该工具', 'computer_tool_forbidden');
838
+ });
839
+ }
840
+ catch (error) {
841
+ if (softComputerFailure(error)) {
842
+ const message = error instanceof Error && error.message ? error.message : '电脑环境不可用';
843
+ return { error: message, code: error instanceof HttpError || error instanceof ComputerError ? error.code : 'computer_unavailable' };
844
+ }
845
+ throw error;
846
+ }
847
+ finally {
848
+ this.event('tool.completed', { tool_id: id, name });
849
+ }
850
+ }
851
+ async finish(live, frame) {
852
+ if (this.closed || live.paused || live.controller.signal.aborted)
853
+ return;
854
+ await this.authorized();
855
+ if (live.lease)
856
+ this.runtime.pool.renew(live.lease);
857
+ const contextErrors = {
858
+ context_compaction_disabled: '模型上下文已超限,基础 Profile 关闭了自动压缩。请开启压缩、缩短输入或新建对话后继续。',
859
+ context_compaction_failed: '模型上下文压缩未能完成,本轮已结束。请缩短输入、检查模型配置或新建对话后继续。',
860
+ };
861
+ const contextError = frame.completed === false && !frame.interrupted && Object.hasOwn(contextErrors, String(frame.failureCode))
862
+ ? contextErrors[String(frame.failureCode)] : undefined;
863
+ const success = frame.completed !== false && !frame.interrupted;
864
+ // Failed model turns can carry a newly compacted, authoritative history too.
865
+ // A missing history leaves the last durable checkpoint intact.
866
+ if (Array.isArray(frame.messages))
867
+ live.session.history = frame.messages;
868
+ live.session.outcome = success ? 'complete' : 'failed';
869
+ this.runtime.save(live.session);
870
+ const keepRunning = this.runtime.retainDesktops && (success || !!contextError) && !live.toolCalls.size;
871
+ await live.worker?.close();
872
+ await this.release(live, keepRunning);
873
+ live.running = false;
874
+ if (this.closed || live.controller.signal.aborted)
875
+ return;
876
+ const error = contextError ? contextError + (keepRunning ? ' 虚拟机已进入空闲,后续按空闲停止设置处理。' : '') : '隔离 Worker 未完成本轮';
877
+ this.event('message.complete', { text: contextError ? error : String(frame.text ?? ''), status: success ? 'complete' : 'failed', ...(!success ? { error, ...(contextError ? { code: frame.failureCode } : {}) } : {}) });
878
+ }
879
+ release(live, keepRunning = false) {
880
+ clearInterval(this.timer);
881
+ live.releasing ??= (async () => {
882
+ await this.hostTransfers?.close();
883
+ this.hostTransfers = undefined;
884
+ if (!live.lease) {
885
+ await live.proxyHandle?.release().catch(() => { });
886
+ return;
887
+ }
888
+ if (this.usedVmTransfers) {
889
+ // Cleanup remains allowed after cancellation, but can only remove this
890
+ // session's staged files in the same VM generation, never a replacement.
891
+ const lease = live.lease;
892
+ const authorize = () => { const state = this.runtime.pool.status(this.meta.ownerKey).find(item => item.environmentId === lease.environmentId); if (state?.generation !== lease.generation || !state.holderIds.includes(this.workId))
893
+ throw new Error('文件传输所属虚拟机已变化'); };
894
+ await this.runtime.provider.execute(this.spec(live.session), ['python3', '-c', VM_FILE_TRANSFER_SCRIPT, this.transferNamespace(live)], { authorize, signal: AbortSignal.timeout(5000), timeout: 5000, mayFence: () => false, input: Buffer.from(JSON.stringify({ op: 'transfer-cleanup' })) }).catch(() => { });
895
+ this.usedVmTransfers = false;
896
+ }
897
+ try {
898
+ await live.proxyHandle?.release();
899
+ await this.runtime.pool.release(live.lease, keepRunning);
900
+ }
901
+ catch (error) {
902
+ await this.runtime.pool.release(live.lease).catch(() => { });
903
+ throw error;
904
+ }
905
+ })();
906
+ return live.releasing;
907
+ }
908
+ async lost(live) {
909
+ if (!live.running || live.paused || this.closed || live.controller.signal.aborted)
910
+ return;
911
+ live.running = false;
912
+ await this.interrupt().catch(() => { });
913
+ if (!this.closed)
914
+ this.onDisconnect();
915
+ }
916
+ get active() { return !!this.live && (this.live.running || this.live.toolsOnly === true && this.live.toolCalls.size > 0) && !this.live.received && !this.closed; }
917
+ get paused() { return this.live?.paused === true; }
918
+ get lease() { return this.live?.lease; }
919
+ get specification() { return this.live ? this.spec(this.live.session) : undefined; }
920
+ /** Pauses this turn for a human takeover: settles in-flight operations and
921
+ * records pending tool calls so the model can resume coherently. The pool
922
+ * lease stays — the human acquires a holder of the same shared desktop. */
923
+ async takeControl(controlId, authorize) {
924
+ const live = this.live;
925
+ if (!live || !this.active)
926
+ throw new HttpError(409, '机器人已不在执行,请重新打开电脑', 'computer_not_active');
927
+ if (live.pauseJob)
928
+ await live.pauseJob;
929
+ if (!live.paused) {
930
+ live.paused = true;
931
+ this.event('computer.paused', { stage: 'pausing' });
932
+ }
933
+ live.pauseJob = (async () => {
934
+ await this.profileSession?.stop();
935
+ await live.worker?.close();
936
+ await Promise.allSettled([...live.toolCalls]);
937
+ authorize();
938
+ this.guard();
939
+ const history = structuredClone(live.session.history), done = new Set(history.filter(message => message.role === 'tool').map(message => message.tool_call_id));
940
+ for (const message of [...history])
941
+ for (const tool of message.tool_calls ?? [])
942
+ if (!done.has(tool.id)) {
943
+ const entry = live.journal.get(tool.id), value = entry?.result ?? { error: '用户接管时此操作未完成,继续前请检查电脑状态,不要盲目重复' };
944
+ const content = typeof value === 'string' ? value : JSON.stringify(value);
945
+ history.push({ role: 'tool', name: tool.function?.name ?? entry?.name, tool_call_id: tool.id, content });
946
+ done.add(tool.id);
947
+ }
948
+ live.session.history = history;
949
+ this.runtime.save(live.session);
950
+ this.event('computer.paused', { stage: 'human', generation: live.lease?.generation });
951
+ })();
952
+ await live.pauseJob;
953
+ }
954
+ async giveBack(notes) {
955
+ const live = this.live;
956
+ if (!live?.paused)
957
+ throw new HttpError(409, '机器人没有处于接管状态', 'computer_not_paused');
958
+ await live.pauseJob;
959
+ await this.authorized();
960
+ live.paused = false;
961
+ live.pauseJob = undefined;
962
+ live.journal.clear();
963
+ this.event('computer.resumed', { generation: live.lease?.generation, notes });
964
+ if (live.toolsOnly)
965
+ return;
966
+ if (this.profileSession) {
967
+ await this.profileSession.bind();
968
+ this.guard();
969
+ await this.profileSession.rpc('prompt.submit', { text: `${this.rules}\n用户已交还电脑控制权。请先检查当前状态,避免重复已完成的操作。交还说明:${notes || '无额外说明'}\n${live.workMarker ?? ''}` });
970
+ return;
971
+ }
972
+ await this.startModel(live, `用户已完成电脑接管并明确交还控制。请先检查当前电脑状态,再继续原任务;不要重复已完成的副作用。用户说明:${notes || '无额外说明'}\n${live.workMarker ?? ''}`, structuredClone(live.session.history));
973
+ }
974
+ async interrupt() {
975
+ const live = this.live;
976
+ if (!live)
977
+ return;
978
+ if (live.stopping)
979
+ return live.stopping;
980
+ live.stopping = (async () => {
981
+ live.controller.abort();
982
+ clearInterval(this.timer);
983
+ try {
984
+ await this.profileSession?.stop();
985
+ }
986
+ finally {
987
+ await this.profileSession?.close();
988
+ await live.worker?.close();
989
+ try {
990
+ await this.release(live);
991
+ }
992
+ catch (error) {
993
+ if (error.code !== 'computer_lease_stale')
994
+ throw error;
995
+ }
996
+ live.running = false;
997
+ }
998
+ })();
999
+ return live.stopping;
1000
+ }
1001
+ async stopControl() { await this.interrupt(); this.event('message.complete', { text: '电脑控制已结束,本轮已停止', status: 'interrupted' }); }
1002
+ async close() { this.runtime.detachGateway(this); this.closed = true; this.controller.abort(); this.team = undefined; clearInterval(this.timer); try {
1003
+ if (this.live?.running || this.live && !this.live.releasing)
1004
+ await this.interrupt();
1005
+ }
1006
+ finally {
1007
+ await this.profileSession?.close();
1008
+ } }
1009
+ }