@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.
- package/LICENSE +202 -0
- package/NOTICE +6 -0
- package/README.md +103 -0
- package/THIRD_PARTY_NOTICES.md +16 -0
- package/bin/desktop-service-sync.mjs +43 -0
- package/bin/hermes-yaoyao-updater.mjs +315 -0
- package/bin/hermes-yaoyao.mjs +246 -0
- package/bin/lib/data-home.d.mts +4 -0
- package/bin/lib/data-home.mjs +24 -0
- package/bin/lib/data-migration.d.mts +2 -0
- package/bin/lib/data-migration.mjs +107 -0
- package/bin/lib/desktop-activation.d.mts +4 -0
- package/bin/lib/desktop-activation.mjs +18 -0
- package/bin/lib/managed-data-migration.mjs +45 -0
- package/bin/lib/release-source.d.mts +2 -0
- package/bin/lib/release-source.mjs +23 -0
- package/bin/lib/runtime-release.mjs +78 -0
- package/bin/lib/service-data.mjs +57 -0
- package/bin/lib/service-update.mjs +372 -0
- package/bin/migrate-data-home.mjs +20 -0
- package/build-info.json +657 -0
- package/desktop/main.mjs +679 -0
- package/dist/assets/AboutDialog-BvuJp8Pe.js +2 -0
- package/dist/assets/AboutDialog-BvuJp8Pe.js.map +1 -0
- package/dist/assets/AboutDialog-DC5YWX39.css +1 -0
- package/dist/assets/BotAutomationsView-Ddgs5Hes.js +2 -0
- package/dist/assets/BotAutomationsView-Ddgs5Hes.js.map +1 -0
- package/dist/assets/BotAutomationsView-DeJ-e3y5.css +1 -0
- package/dist/assets/BotPluginsDialog-Db5dTqvg.css +1 -0
- package/dist/assets/BotPluginsDialog-xPqUSyHS.js +2 -0
- package/dist/assets/BotPluginsDialog-xPqUSyHS.js.map +1 -0
- package/dist/assets/BotSettingsDialog-BkjoAZtf.css +1 -0
- package/dist/assets/BotSettingsDialog-wLz_KGzX.js +5 -0
- package/dist/assets/BotSettingsDialog-wLz_KGzX.js.map +1 -0
- package/dist/assets/ChatView-DRPu2nKr.js +2 -0
- package/dist/assets/ChatView-DRPu2nKr.js.map +1 -0
- package/dist/assets/ChatView-Dx8YlcPr.css +1 -0
- package/dist/assets/ChevronForwardOutline-D--GIQK6.js +2 -0
- package/dist/assets/ChevronForwardOutline-D--GIQK6.js.map +1 -0
- package/dist/assets/ComputerPanel-Byr2_yKj.js +2 -0
- package/dist/assets/ComputerPanel-Byr2_yKj.js.map +1 -0
- package/dist/assets/ComputerPanel-CQOv4v8E.css +1 -0
- package/dist/assets/ComputerViewerView-BBAs4bzi.css +1 -0
- package/dist/assets/ComputerViewerView-DJ6hB-5e.js +2 -0
- package/dist/assets/ComputerViewerView-DJ6hB-5e.js.map +1 -0
- package/dist/assets/ConversationsView-C_VZl5g2.css +1 -0
- package/dist/assets/ConversationsView-cu1Yrq68.js +6 -0
- package/dist/assets/ConversationsView-cu1Yrq68.js.map +1 -0
- package/dist/assets/FilesView-DAIzo9Ps.css +1 -0
- package/dist/assets/FilesView-h9oJFmZt.js +2 -0
- package/dist/assets/FilesView-h9oJFmZt.js.map +1 -0
- package/dist/assets/FloatingResourceSearch-BF2XOLd-.css +1 -0
- package/dist/assets/FloatingResourceSearch-TofG1_DV.js +9 -0
- package/dist/assets/FloatingResourceSearch-TofG1_DV.js.map +1 -0
- package/dist/assets/HistoryView-Bh0SU969.js +2 -0
- package/dist/assets/HistoryView-Bh0SU969.js.map +1 -0
- package/dist/assets/HistoryView-DvuCAjlo.css +1 -0
- package/dist/assets/KanbanView-B-2vG4w7.css +1 -0
- package/dist/assets/KanbanView-CcqMOzB7.js +2 -0
- package/dist/assets/KanbanView-CcqMOzB7.js.map +1 -0
- package/dist/assets/LocalVmSettingsPanel-C8PIgMr3.js +2 -0
- package/dist/assets/LocalVmSettingsPanel-C8PIgMr3.js.map +1 -0
- package/dist/assets/LocalVmSettingsPanel-Dedfhqlq.css +1 -0
- package/dist/assets/RunnerSettingsPanel-CfxxQKpV.css +1 -0
- package/dist/assets/RunnerSettingsPanel-CvNnWcdH.js +4 -0
- package/dist/assets/RunnerSettingsPanel-CvNnWcdH.js.map +1 -0
- package/dist/assets/StandaloneDialog-BbNWY6IJ.js +2 -0
- package/dist/assets/StandaloneDialog-BbNWY6IJ.js.map +1 -0
- package/dist/assets/StandaloneDialog-Bg5U9bMJ.css +1 -0
- package/dist/assets/UpdateCheckDialog-C357uDSE.js +2 -0
- package/dist/assets/UpdateCheckDialog-C357uDSE.js.map +1 -0
- package/dist/assets/UpdateCheckDialog-CRlyWnE7.css +1 -0
- package/dist/assets/WorkspaceKnowledgePanel-B6xMyHdp.css +1 -0
- package/dist/assets/WorkspaceKnowledgePanel-CE7qsu2i.js +2 -0
- package/dist/assets/WorkspaceKnowledgePanel-CE7qsu2i.js.map +1 -0
- package/dist/assets/WorkspaceRoutinesPanel-CLsHmBuH.css +1 -0
- package/dist/assets/WorkspaceRoutinesPanel-DybBh6PZ.js +2 -0
- package/dist/assets/WorkspaceRoutinesPanel-DybBh6PZ.js.map +1 -0
- package/dist/assets/WorkspaceShell-7wn8iTne.css +1 -0
- package/dist/assets/WorkspaceShell-kp1ObJTk.js +44 -0
- package/dist/assets/WorkspaceShell-kp1ObJTk.js.map +1 -0
- package/dist/assets/WorkspaceView-CtNI0_AO.js +2 -0
- package/dist/assets/WorkspaceView-CtNI0_AO.js.map +1 -0
- package/dist/assets/_plugin-vue_export-helper-CscYwSBt.js +3 -0
- package/dist/assets/_plugin-vue_export-helper-CscYwSBt.js.map +1 -0
- package/dist/assets/browser-B97PQaMt.js +11 -0
- package/dist/assets/browser-B97PQaMt.js.map +1 -0
- package/dist/assets/docx-preview-YvkiVUyQ.js +22 -0
- package/dist/assets/docx-preview-YvkiVUyQ.js.map +1 -0
- package/dist/assets/index-GQxxBKs2.js +17 -0
- package/dist/assets/index-GQxxBKs2.js.map +1 -0
- package/dist/assets/index-g5POnMkp.css +1 -0
- package/dist/assets/localVm-owThjmhy.js +2 -0
- package/dist/assets/localVm-owThjmhy.js.map +1 -0
- package/dist/assets/pdf-pqGpzpl1.js +55 -0
- package/dist/assets/pdf-pqGpzpl1.js.map +1 -0
- package/dist/assets/pdf.worker.min-iDqQPrd3.mjs +31 -0
- package/dist/assets/sessionOwnership-BTz0Fyp5.css +1 -0
- package/dist/assets/sessionOwnership-bedp16q1.js +6 -0
- package/dist/assets/sessionOwnership-bedp16q1.js.map +1 -0
- package/dist/assets/viewModels-BYFb-v4u.js +38 -0
- package/dist/assets/viewModels-BYFb-v4u.js.map +1 -0
- package/dist/assets/viewModels-CkZuSvKm.css +1 -0
- package/dist/brand/AppIcon-1024.png +0 -0
- package/dist/icons/apple-touch-icon.png +0 -0
- package/dist/icons/favicon-32.png +0 -0
- package/dist/icons/icon-192.png +0 -0
- package/dist/icons/icon-512.png +0 -0
- package/dist/icons/logo-64.png +0 -0
- package/dist/index.html +19 -0
- package/dist/manifest.webmanifest +21 -0
- package/dist/setting-previews/dark.png +0 -0
- package/dist/setting-previews/light.png +0 -0
- package/dist/setting-previews/system.png +0 -0
- package/dist-server/runner/agent.js +563 -0
- package/dist-server/runner/browser/installation.js +180 -0
- package/dist-server/runner/browser/publicProxy.js +157 -0
- package/dist-server/runner/browser/runtime.js +622 -0
- package/dist-server/runner/browser/types.js +8 -0
- package/dist-server/runner/computers/commandProcess.js +127 -0
- package/dist-server/runner/computers/compose.js +139 -0
- package/dist-server/runner/computers/computer-image/Dockerfile +101 -0
- package/dist-server/runner/computers/computer-image/Dockerfile.cursor +27 -0
- package/dist-server/runner/computers/computer-image/Dockerfile.network +9 -0
- package/dist-server/runner/computers/computer-image/compose_bridge.py +329 -0
- package/dist-server/runner/computers/computer-image/cursor-browser.sh +6 -0
- package/dist-server/runner/computers/computer-image/cursor-desktop.py +86 -0
- package/dist-server/runner/computers/computer-image/network_gateway.py +197 -0
- package/dist-server/runner/computers/computer-image/prepare-firefox.sh +11 -0
- package/dist-server/runner/computers/computer-image/skill_bundle.py +111 -0
- package/dist-server/runner/computers/computerFailures.js +30 -0
- package/dist-server/runner/computers/container.js +652 -0
- package/dist-server/runner/computers/dataSnapshot.js +62 -0
- package/dist-server/runner/computers/desktopClose.js +41 -0
- package/dist-server/runner/computers/imageCli.js +42 -0
- package/dist-server/runner/computers/imageManagement.js +321 -0
- package/dist-server/runner/computers/images.js +130 -0
- package/dist-server/runner/computers/localVm.js +270 -0
- package/dist-server/runner/computers/maintenance.js +96 -0
- package/dist-server/runner/computers/maintenanceCli.js +59 -0
- package/dist-server/runner/computers/migrateUserData.js +62 -0
- package/dist-server/runner/computers/pool.js +407 -0
- package/dist-server/runner/computers/third-party/openmausbot/LICENSE +202 -0
- package/dist-server/runner/computers/third-party/openmausbot/NOTICE +4 -0
- package/dist-server/runner/computers/userData.js +128 -0
- package/dist-server/runner/computers/workspaceRecovery.js +120 -0
- package/dist-server/runner/config.js +37 -0
- package/dist-server/runner/hermes-bots-bridge/README.md +102 -0
- package/dist-server/runner/hermes-bots-bridge/__init__.py +59 -0
- package/dist-server/runner/hermes-bots-bridge/bootstrap.py +31 -0
- package/dist-server/runner/hermes-bots-bridge/bridge_runtime.py +1179 -0
- package/dist-server/runner/hermes-bots-bridge/dashboard/bridge.js +2 -0
- package/dist-server/runner/hermes-bots-bridge/dashboard/manifest.json +9 -0
- package/dist-server/runner/hermes-bots-bridge/dashboard/plugin_api.py +132 -0
- package/dist-server/runner/hermes-bots-bridge/file_transfer.py +146 -0
- package/dist-server/runner/hermes-bots-bridge/model_settings.py +136 -0
- package/dist-server/runner/hermes-bots-bridge/plugin.yaml +4 -0
- package/dist-server/runner/hermes-bots-bridge/profile_runtime_repair.py +77 -0
- package/dist-server/runner/index.js +75 -0
- package/dist-server/runner/install-hermes-bridge.py +192 -0
- package/dist-server/runner/managedBrowser.js +266 -0
- package/dist-server/runner/network/computerProxy.js +117 -0
- package/dist-server/runner/network/managedProxy.js +96 -0
- package/dist-server/runner/network/publicDestination.js +47 -0
- package/dist-server/runner/network/socketBroker.js +131 -0
- package/dist-server/runner/network/upstreamProxy.js +118 -0
- package/dist-server/runner/worker/control.js +212 -0
- package/dist-server/runner/worker/fileTransfer.js +9 -0
- package/dist-server/runner/worker/gateway.js +1009 -0
- package/dist-server/runner/worker/guest_proxy.py +116 -0
- package/dist-server/runner/worker/hermes_worker.py +310 -0
- package/dist-server/runner/worker/hostTools.js +115 -0
- package/dist-server/runner/worker/process.js +123 -0
- package/dist-server/runner/worker/profileSession.js +144 -0
- package/dist-server/runner/worker/profile_skills.py +361 -0
- package/dist-server/runner/worker/skill_bundle.py +111 -0
- package/dist-server/runner/worker/skills.js +119 -0
- package/dist-server/runner/worker/taskEnvironment.js +35 -0
- package/dist-server/server/accountPairing.js +72 -0
- package/dist-server/server/allowedHostsConfiguration.js +170 -0
- package/dist-server/server/apns.js +261 -0
- package/dist-server/server/apnsConfiguration.js +298 -0
- package/dist-server/server/app.js +639 -0
- package/dist-server/server/botModelSettings.js +60 -0
- package/dist-server/server/botPlugins/connectedApps.js +213 -0
- package/dist-server/server/botPlugins/httpMcp.js +117 -0
- package/dist-server/server/botPlugins/stdioMcp.js +263 -0
- package/dist-server/server/botPlugins/workspacePlugins.js +353 -0
- package/dist-server/server/browserFiles.js +79 -0
- package/dist-server/server/buildIdentity.js +18 -0
- package/dist-server/server/chatCache.js +1651 -0
- package/dist-server/server/chatEventProjection.js +70 -0
- package/dist-server/server/chatTranscriptApi.js +145 -0
- package/dist-server/server/chatTranscriptStore.js +1021 -0
- package/dist-server/server/chatUnread.js +34 -0
- package/dist-server/server/codexAuthorization.js +149 -0
- package/dist-server/server/composeDesktops.js +69 -0
- package/dist-server/server/computerControls.js +122 -0
- package/dist-server/server/computerNames.js +41 -0
- package/dist-server/server/config.js +176 -0
- package/dist-server/server/dashboardController.js +120 -0
- package/dist-server/server/dashboardSupervisor.js +176 -0
- package/dist-server/server/desktopActivation.js +26 -0
- package/dist-server/server/desktopEnvironments.js +600 -0
- package/dist-server/server/desktopHostProtocol.js +17 -0
- package/dist-server/server/desktopHosts.js +117 -0
- package/dist-server/server/errors.js +12 -0
- package/dist-server/server/executionSettings.js +171 -0
- package/dist-server/server/fcm.js +247 -0
- package/dist-server/server/fcmConfiguration.js +270 -0
- package/dist-server/server/fileAccess.js +103 -0
- package/dist-server/server/fileTransfer.js +98 -0
- package/dist-server/server/githubReleases.js +73 -0
- package/dist-server/server/grokAuth.js +333 -0
- package/dist-server/server/grokCloud.js +458 -0
- package/dist-server/server/hermesBotRelay.js +117 -0
- package/dist-server/server/hermesBridge.js +245 -0
- package/dist-server/server/hostToolSettings.js +60 -0
- package/dist-server/server/imageManagement.js +55 -0
- package/dist-server/server/index.js +132 -0
- package/dist-server/server/leases.js +69 -0
- package/dist-server/server/localAuth.js +737 -0
- package/dist-server/server/localVm.js +358 -0
- package/dist-server/server/loopbackAuthorization.js +58 -0
- package/dist-server/server/managedBrowserTools.js +16 -0
- package/dist-server/server/managedBrowsers.js +735 -0
- package/dist-server/server/notificationText.js +125 -0
- package/dist-server/server/openVikingConfiguration.js +222 -0
- package/dist-server/server/openVikingMemoryProvider.js +279 -0
- package/dist-server/server/openVikingService.js +177 -0
- package/dist-server/server/openVikingSessionSync.js +286 -0
- package/dist-server/server/pairing.js +342 -0
- package/dist-server/server/profileIdentities.js +103 -0
- package/dist-server/server/pushCoordinator.js +1422 -0
- package/dist-server/server/pushEventAdapter.js +31 -0
- package/dist-server/server/pushEvents.js +1218 -0
- package/dist-server/server/realtimeApi.js +330 -0
- package/dist-server/server/realtimeBroker.js +835 -0
- package/dist-server/server/realtimeProtocol.js +353 -0
- package/dist-server/server/realtimeReceipts.js +60 -0
- package/dist-server/server/releases.js +46 -0
- package/dist-server/server/routes.js +2156 -0
- package/dist-server/server/runnerHub.js +687 -0
- package/dist-server/server/security.js +196 -0
- package/dist-server/server/serverIdentity.js +31 -0
- package/dist-server/server/serviceInstance.js +178 -0
- package/dist-server/server/sessionWorkingDirectory.js +39 -0
- package/dist-server/server/sharedComputers.js +221 -0
- package/dist-server/server/subaccountAccess.js +28 -0
- package/dist-server/server/taskCoordinator.js +580 -0
- package/dist-server/server/toolOperationJournal.js +81 -0
- package/dist-server/server/updateManager.js +340 -0
- package/dist-server/server/uploads.js +265 -0
- package/dist-server/server/upstream.js +375 -0
- package/dist-server/server/upstreamReadCache.js +133 -0
- package/dist-server/server/vmComputer.js +96 -0
- package/dist-server/server/websocket.js +753 -0
- package/dist-server/server/workspaceAssets.js +192 -0
- package/dist-server/server/workspaceCollaboration.js +224 -0
- package/dist-server/server/workspaceDiscussion.js +23 -0
- package/dist-server/server/workspaceEnvironment.js +43 -0
- package/dist-server/server/workspaceGateway.js +509 -0
- package/dist-server/server/workspaceInspector.js +47 -0
- package/dist-server/server/workspaceKnowledge.js +557 -0
- package/dist-server/server/workspaceKnowledgeRoutes.js +78 -0
- package/dist-server/server/workspaceKnowledgeTools.js +105 -0
- package/dist-server/server/workspaceMemoryContext.js +34 -0
- package/dist-server/server/workspaceMemorySynthesis.js +201 -0
- package/dist-server/server/workspaceMentions.js +31 -0
- package/dist-server/server/workspacePairedNode.js +166 -0
- package/dist-server/server/workspacePrompt.js +93 -0
- package/dist-server/server/workspaceRelay.js +90 -0
- package/dist-server/server/workspaceRemoteAgents.js +191 -0
- package/dist-server/server/workspaceRoutes.js +703 -0
- package/dist-server/server/workspaceRoutineTools.js +109 -0
- package/dist-server/server/workspaceRoutines.js +163 -0
- package/dist-server/server/workspaceRuntime.js +1363 -0
- package/dist-server/server/workspaceScheduler.js +592 -0
- package/dist-server/server/workspaceStore.js +1220 -0
- package/dist-server/server/workspaceSync.js +129 -0
- package/dist-server/server/workspaceTeamTools.js +312 -0
- package/dist-server/server/workspaceToolLease.js +280 -0
- package/dist-server/shared/agentIdentity.js +90 -0
- package/dist-server/shared/agentTasks.js +1 -0
- package/dist-server/shared/botEnvironment.js +28 -0
- package/dist-server/shared/botModelSettings.js +3 -0
- package/dist-server/shared/chatTools.js +32 -0
- package/dist-server/shared/chatTranscript.js +50 -0
- package/dist-server/shared/composeDesktops.js +1 -0
- package/dist-server/shared/computerControl.js +1 -0
- package/dist-server/shared/desktopEnvironment.js +1 -0
- package/dist-server/shared/desktopHost.js +1 -0
- package/dist-server/shared/executionEnvironment.js +1 -0
- package/dist-server/shared/fileTransfer.js +5 -0
- package/dist-server/shared/fileTransferEndpoint.mjs +133 -0
- package/dist-server/shared/grokAuth.js +1 -0
- package/dist-server/shared/hermesBridge.js +1 -0
- package/dist-server/shared/hostPaths.mjs +22 -0
- package/dist-server/shared/imageManagement.js +1 -0
- package/dist-server/shared/index.js +1 -0
- package/dist-server/shared/localVm.js +9 -0
- package/dist-server/shared/managedBrowser.js +1 -0
- package/dist-server/shared/messageFiles.js +90 -0
- package/dist-server/shared/openVikingSync.js +1 -0
- package/dist-server/shared/runner.js +2 -0
- package/dist-server/shared/serverFiles.js +55 -0
- package/dist-server/shared/serverIdentity.js +1 -0
- package/dist-server/shared/sse.js +47 -0
- package/dist-server/shared/types.js +8 -0
- package/dist-server/shared/workspace.js +61 -0
- package/dist-server/shared/workspaceKnowledge.js +1 -0
- package/dist-server/shared/workspaceLifecycle.js +1 -0
- package/dist-server/shared/workspaceMessagePatch.js +63 -0
- package/dist-server/shared/workspacePanels.js +1 -0
- package/dist-server/shared/workspacePlugins.js +1 -0
- package/licenses/LaoA-GrokBot/LICENSE +21 -0
- package/licenses/OpenMausBot/LICENSE +202 -0
- package/licenses/OpenMausBot/NOTICE +6 -0
- package/package.json +122 -0
- package/release.json +6 -0
|
@@ -0,0 +1,600 @@
|
|
|
1
|
+
import Router from '@koa/router';
|
|
2
|
+
import { createHash, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import { HttpError } from './errors.js';
|
|
5
|
+
import { parse } from './workspaceStore.js';
|
|
6
|
+
import {} from '../shared/workspace.js';
|
|
7
|
+
import { readHostTools } from './hostToolSettings.js';
|
|
8
|
+
import { readComputerNames } from './computerNames.js';
|
|
9
|
+
import { requireTeamToolBridge } from './workspaceToolLease.js';
|
|
10
|
+
import { copyBetweenEndpoints } from './fileTransfer.js';
|
|
11
|
+
import { deviceSourceText, deviceInventoryText } from '../shared/botEnvironment.js';
|
|
12
|
+
import { desktopHostExchangeSchema } from './desktopHostProtocol.js';
|
|
13
|
+
const digest = (s) => createHash('sha256').update(s).digest('hex');
|
|
14
|
+
const inputSchema = z.discriminatedUnion('kind', [
|
|
15
|
+
z.object({ kind: z.literal('click'), x: z.number().int().min(0).max(16384), y: z.number().int().min(0).max(16384), button: z.enum(['left', 'right', 'middle']).optional(), count: z.number().int().min(1).max(2).optional() }).strict(),
|
|
16
|
+
z.object({ kind: z.literal('drag'), fromX: z.number().int().min(0).max(16384), fromY: z.number().int().min(0).max(16384), toX: z.number().int().min(0).max(16384), toY: z.number().int().min(0).max(16384) }).strict(),
|
|
17
|
+
z.object({ kind: z.literal('text'), text: z.string().max(16000) }).strict(),
|
|
18
|
+
z.object({ kind: z.literal('key'), key: z.string().regex(/^[A-Za-z0-9_+ -]{1,40}$/), modifiers: z.array(z.enum(['ctrl', 'alt', 'shift', 'super'])).max(4).optional() }).strict(),
|
|
19
|
+
z.object({ kind: z.literal('scroll'), direction: z.enum(['up', 'down', 'left', 'right']), amount: z.number().int().min(1).max(50).optional() }).strict(),
|
|
20
|
+
]);
|
|
21
|
+
const browserSchema = z.discriminatedUnion('kind', [
|
|
22
|
+
z.object({ kind: z.enum(['navigate', 'new-tab']), url: z.string().max(4096).refine(value => { try {
|
|
23
|
+
const u = new URL(value);
|
|
24
|
+
return ['http:', 'https:'].includes(u.protocol) && !u.username && !u.password && !/[\\\x00-\x20]/.test(value);
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
return false;
|
|
28
|
+
} }, '请输入完整的 http 或 https 地址') }).strict(),
|
|
29
|
+
z.object({ kind: z.enum(['select-tab', 'close-tab']), tabId: z.string().uuid() }).strict(),
|
|
30
|
+
z.object({ kind: z.enum(['back', 'forward', 'reload', 'snapshot']) }).strict(),
|
|
31
|
+
z.object({ kind: z.enum(['click', 'fill']), ref: z.string().regex(/^e[0-9]+$/), snapshotId: z.string().uuid(), text: z.string().max(16000).optional() }).strict(),
|
|
32
|
+
]);
|
|
33
|
+
const fileSchema = z.discriminatedUnion('op', [
|
|
34
|
+
z.object({ op: z.literal('list'), path: z.string().min(1).max(2048) }).strict(),
|
|
35
|
+
z.object({ op: z.literal('read'), path: z.string().min(1).max(2048) }).strict(),
|
|
36
|
+
z.object({ op: z.literal('write'), path: z.string().min(1).max(2048), data: z.string().max(14 * 1024 * 1024).refine(value => Buffer.from(value, 'base64').toString('base64') === value, '文件内容必须是 base64') }).strict(),
|
|
37
|
+
]);
|
|
38
|
+
const shellSchema = z.object({ command: z.string().min(1).max(8000), cwd: z.string().max(2048).optional(), timeoutMs: z.number().int().min(1000).max(120000).optional() }).strict();
|
|
39
|
+
const copySchema = z.object({ sourceHost: z.string().trim().min(1).max(128), sourcePath: z.string().min(1).max(2048), targetHost: z.string().trim().min(1).max(128), targetPath: z.string().min(1).max(2048), overwrite: z.boolean().default(false) }).strict();
|
|
40
|
+
const newHostState = (key, remote) => ({ key, remote, seen: 0, pending: new Map(), queue: new Map(), manual: new Map(), paused: new Set(), frames: new Map(), generation: new Map(), notes: new Map(), activity: new Map() });
|
|
41
|
+
export const DESKTOP_ENVIRONMENT_TOOLS = [
|
|
42
|
+
{ id: 'desktop_environment_view', name: 'desktop_environment_view', description: '查看电脑真实桌面截图,返回截图尺寸、环境类型和电脑名称。仅在需要看窗口、图标布局或做点击输入时使用;列目录、读文件、写文件、跑命令不要先截图。可用 host 指定目标电脑;省略或写「本机」时只使用本轮消息来源电脑;来源未知或离线时必须明确目标,禁止回退。', inputSchema: { type: 'object', properties: { host: { type: 'string', description: '可选,目标电脑的名称或编号;缺省用本轮消息来源电脑;server 明确指服务器' } }, additionalProperties: false } },
|
|
43
|
+
{ id: 'desktop_environment_action', name: 'desktop_environment_action', description: '操作电脑桌面(click、text、key、scroll、drag)。做这些鼠标键盘操作前必须先截图,坐标用刚截到的像素;页面变化后重新截图。列目录和跑命令请用文件/shell 工具,不要用本工具。可用 host 指定目标电脑。', inputSchema: { type: 'object', properties: { host: { type: 'string' }, 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: { type: 'string' }, key: { type: 'string' }, modifiers: { type: 'array', items: { enum: ['ctrl', 'alt', 'shift', 'super'] } }, direction: { enum: ['up', 'down', 'left', 'right'] }, amount: { type: 'integer' } }, required: ['kind'], additionalProperties: false } },
|
|
44
|
+
{ id: 'desktop_file_list', name: 'desktop_file_list', description: '列出当前电脑允许范围内的目录内容,返回名称、类型、大小与修改时间。路径相对于用户主目录,例如 Desktop、Documents,或 ~/Desktop。可用 host 指定目标电脑。', inputSchema: { type: 'object', properties: { path: { type: 'string' }, host: { type: 'string' } }, required: ['path'], additionalProperties: false } },
|
|
45
|
+
{ id: 'desktop_file_read', name: 'desktop_file_read', description: '读取当前电脑上的一个文件,返回 base64 内容与大小。路径相对于用户主目录;超出允许范围会被拒绝。可用 host 指定目标电脑。', inputSchema: { type: 'object', properties: { path: { type: 'string' }, host: { type: 'string' } }, required: ['path'], additionalProperties: false } },
|
|
46
|
+
{ id: 'desktop_file_write', name: 'desktop_file_write', description: '把 base64 内容写入当前电脑上的文件(覆盖已存在文件)。路径相对于用户主目录;超出允许范围会被拒绝。可用 host 指定目标电脑。', inputSchema: { type: 'object', properties: { path: { type: 'string' }, data: { type: 'string' }, host: { type: 'string' } }, required: ['path', 'data'], additionalProperties: false } },
|
|
47
|
+
{ id: 'desktop_file_copy', name: 'desktop_file_copy', description: '把文件从一台电脑直接复制到另一台电脑,支持电脑之间、电脑与服务器之间、电脑与当前 Bot 虚拟机之间双向传输。填写来源和目标电脑的名称或编号(服务器用 server,当前 Bot 的虚拟机用 vm;本机指本轮消息来源电脑),以及各自用户主目录内的文件路径,例如 Desktop/a.txt。保留来源文件,默认拒绝覆盖目标同名文件;只有用户要求覆盖时才设 overwrite=true。最大 25 MiB,支持二进制文件,写入并校验后返回结果。文件数据由服务器中转,不经过模型或聊天附件。', inputSchema: { type: 'object', properties: { sourceHost: { type: 'string' }, sourcePath: { type: 'string' }, targetHost: { type: 'string' }, targetPath: { type: 'string' }, overwrite: { type: 'boolean', default: false } }, required: ['sourceHost', 'sourcePath', 'targetHost', 'targetPath'], additionalProperties: false } },
|
|
48
|
+
{ id: 'desktop_shell', name: 'desktop_shell', description: '在这台电脑的用户主目录执行一条 shell 命令,返回 stdout、stderr 与退出码。长任务会超时终止;不要用它代替文件工具读写大文件。可用 host 指定目标电脑。', inputSchema: { type: 'object', properties: { command: { type: 'string' }, cwd: { type: 'string' }, timeoutMs: { type: 'integer' }, host: { type: 'string' } }, required: ['command'], additionalProperties: false } },
|
|
49
|
+
];
|
|
50
|
+
export const DESKTOP_FILE_TOOL_IDS = new Set(['desktop_file_list', 'desktop_file_read', 'desktop_file_write', 'desktop_file_copy', 'desktop_shell']);
|
|
51
|
+
export const DESKTOP_FILE_TRANSFER_RULES = '电脑间传文件用 desktop_file_copy,一次指定 sourceHost、sourcePath、targetHost、targetPath;服务器用 server,当前 Bot 的虚拟机用 vm,设备名用设置里的名字,「本机」只指本轮消息来源电脑。例:把 mac1 桌面的 a.txt 放到 mac2 桌面,调用 {sourceHost:"mac1",sourcePath:"Desktop/a.txt",targetHost:"mac2",targetPath:"Desktop/a.txt"}。这是复制,保留原文件;只有用户明确要求覆盖时才传 overwrite:true。无需先截图,不要读取 base64 给模型、上传聊天附件或假设不同电脑共享文件路径。最大 25 MiB;工具返回已校验的成功结果后才报告完成。';
|
|
52
|
+
/** Macs connected to the server as computers. */
|
|
53
|
+
export const DESKTOP_ENVIRONMENT_RULES = '操作连接服务器的电脑时,使用本轮提供的 desktop_* 工具,并用 host 指定电脑名称或编号。Hermes 原生终端和文件工具不能代替该电脑上的操作。';
|
|
54
|
+
/** Yaoyao host Mac — same look-then-act pattern as the cloud computer. */
|
|
55
|
+
export const SERVER_COMPUTER_RULES = '操作服务器桌面时,使用本轮提供的 desktop_* 工具并明确指定 host="server"。处理 Hermes 运行环境内的文件与命令时,使用实际提供的原生工具;处理服务器桌面用户主目录内的文件时,使用已授权的 desktop_file_* 或 desktop_shell,不假定两者共享路径。';
|
|
56
|
+
/** The loopback native transport is admitted only by serviceInstance's
|
|
57
|
+
* private capability; remote hosts are admitted by DesktopHostHub's bearer
|
|
58
|
+
* pairing. Browser/desktop authority never crosses into the renderer. */
|
|
59
|
+
export class DesktopEnvironments {
|
|
60
|
+
store;
|
|
61
|
+
auth;
|
|
62
|
+
nodes;
|
|
63
|
+
sessions = new Map();
|
|
64
|
+
authorizing = new Map();
|
|
65
|
+
toolFrames = new WeakMap();
|
|
66
|
+
closed = false;
|
|
67
|
+
constructor(store, auth, nodes) {
|
|
68
|
+
this.store = store;
|
|
69
|
+
this.auth = auth;
|
|
70
|
+
this.nodes = nodes;
|
|
71
|
+
}
|
|
72
|
+
hostOnline(s) { return !this.closed && !!s.info && Date.now() - s.seen < (s.remote ? 15000 : 8000); }
|
|
73
|
+
get online() { const s = this.sessions.get('local'); return !!s && this.hostOnline(s); }
|
|
74
|
+
get idleForUpdate() { for (const s of this.sessions.values()) {
|
|
75
|
+
for (const key of s.manual.keys())
|
|
76
|
+
this.current(s, key);
|
|
77
|
+
if (s.pending.size || s.queue.size || s.manual.size)
|
|
78
|
+
return false;
|
|
79
|
+
} return true; }
|
|
80
|
+
ownerKey(owner) { return digest((this.nodes.localNodeID ?? this.nodes.local.url.toString()) + ':' + owner); }
|
|
81
|
+
ready(s, owner) { return this.hostOnline(s) && ['darwin', 'win32'].includes(s.info.platform) && s.info.screen && s.info.accessibility && s.info.approved.includes(this.ownerKey(owner)); }
|
|
82
|
+
/** File and shell grant: a separate approval tier held by the desktop app. */
|
|
83
|
+
readyFull(s, owner) { return this.hostOnline(s) && ['darwin', 'win32'].includes(s.info.platform) && (s.info.full ?? []).includes(this.ownerKey(owner)); }
|
|
84
|
+
fileTools(owner, agent) { return this.envTools(owner, agent).file; }
|
|
85
|
+
localSession() { let s = this.sessions.get('local'); if (!s) {
|
|
86
|
+
s = newHostState('local', false);
|
|
87
|
+
this.sessions.set('local', s);
|
|
88
|
+
} return s; }
|
|
89
|
+
/** Default session: agent desktopHost binding, else server local.
|
|
90
|
+
* 「本机」 at tool time prefers the user message deviceHost when provided. */
|
|
91
|
+
computers() { try {
|
|
92
|
+
const s = readHostTools(this.store.home);
|
|
93
|
+
return { script: s.scriptMachine, server: s.serverComputer };
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
return { script: false, server: false };
|
|
97
|
+
} }
|
|
98
|
+
names() { try {
|
|
99
|
+
return readComputerNames(this.store.home);
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
return {};
|
|
103
|
+
} }
|
|
104
|
+
label(s) { const custom = this.names()[s.key]; if (s.key === 'local')
|
|
105
|
+
return custom || '服务器'; return custom || s.info?.name || ''; }
|
|
106
|
+
hostOpen(s) { const g = this.computers(); return s.key === 'local' ? g.server : g.script; }
|
|
107
|
+
sessionFor(agent) {
|
|
108
|
+
const g = this.computers();
|
|
109
|
+
if (g.script && agent.desktopHost && agent.desktopHost !== 'local') {
|
|
110
|
+
const pinned = this.sessions.get(agent.desktopHost);
|
|
111
|
+
if (pinned)
|
|
112
|
+
return pinned;
|
|
113
|
+
}
|
|
114
|
+
if (!g.server)
|
|
115
|
+
return undefined;
|
|
116
|
+
return this.sessions.get('local');
|
|
117
|
+
}
|
|
118
|
+
/** Tool aliases are relative to the triggering message, never to a Bot binding. */
|
|
119
|
+
namedHost(host, deviceHost) {
|
|
120
|
+
if (host === '本机' || host === 'local')
|
|
121
|
+
return this.messageHost(deviceHost);
|
|
122
|
+
if (host === 'server' || host === '服务器')
|
|
123
|
+
return this.requireHost(this.localSession());
|
|
124
|
+
const matches = [...this.sessions.values()].filter(s => s.key === host ||
|
|
125
|
+
this.label(s).toLowerCase() === host.toLowerCase() || s.info?.name.toLowerCase() === host.toLowerCase());
|
|
126
|
+
if (matches.length > 1)
|
|
127
|
+
throw new HttpError(409, '电脑名称重复,请使用电脑编号指定目标。', 'desktop_host_ambiguous');
|
|
128
|
+
const s = matches[0];
|
|
129
|
+
if (!s)
|
|
130
|
+
throw new HttpError(409, `指定的电脑未连接:${host.slice(0, 64)}`, 'desktop_host_unknown');
|
|
131
|
+
return this.requireHost(s);
|
|
132
|
+
}
|
|
133
|
+
requireHost(s) {
|
|
134
|
+
if (!this.hostOpen(s))
|
|
135
|
+
throw new HttpError(403, '全局设置未开放这台电脑。', 'desktop_host_disabled');
|
|
136
|
+
if (!this.hostOnline(s))
|
|
137
|
+
throw new HttpError(409, '目标电脑已离线,请连接原电脑后重试。', 'desktop_offline');
|
|
138
|
+
return s;
|
|
139
|
+
}
|
|
140
|
+
messageHost(deviceHost) {
|
|
141
|
+
if (!deviceHost)
|
|
142
|
+
throw new HttpError(409, '当前消息没有可控制的来源电脑,请指定电脑名称或编号。', 'desktop_source_required');
|
|
143
|
+
const s = this.sessions.get(deviceHost);
|
|
144
|
+
if (!s)
|
|
145
|
+
throw new HttpError(409, '消息来源电脑未连接;不会改用其他电脑。', 'desktop_offline');
|
|
146
|
+
return this.requireHost(s);
|
|
147
|
+
}
|
|
148
|
+
selected(_owner, agent) {
|
|
149
|
+
if (agent.archived || agent.remoteAgentId)
|
|
150
|
+
return undefined;
|
|
151
|
+
const g = this.computers();
|
|
152
|
+
return g.script || g.server ? 'local' : undefined;
|
|
153
|
+
}
|
|
154
|
+
toolMode(owner, agent) { return this.selected(owner, agent); }
|
|
155
|
+
modes(owner, agent) { return { desktop: !!this.selected(owner, agent), browser: false }; }
|
|
156
|
+
envTools(owner, agent) {
|
|
157
|
+
const snapshot = this.snapshot(owner, agent);
|
|
158
|
+
return { view: snapshot.hosts.some(host => host.capabilities.view.enabled), browser: false, file: snapshot.hosts.some(host => host.capabilities.fileRead.enabled) };
|
|
159
|
+
}
|
|
160
|
+
/** Viewer host ids are absolute; the wire id local identifies the server. */
|
|
161
|
+
takeoverSession(a, host) {
|
|
162
|
+
if (typeof host === 'string' && host)
|
|
163
|
+
return this.namedHost(host === 'local' ? 'server' : host);
|
|
164
|
+
return this.sessionFor(a);
|
|
165
|
+
}
|
|
166
|
+
targetFor(_agent, host, deviceHost) {
|
|
167
|
+
return typeof host === 'string' && host ? this.namedHost(host, deviceHost) : this.messageHost(deviceHost);
|
|
168
|
+
}
|
|
169
|
+
/** Collect current state without connecting a host, launching a browser or starting a computer. */
|
|
170
|
+
snapshot(owner, agent, deviceHost, policy) {
|
|
171
|
+
const capturedAt = Date.now(), global = policy ?? { ...this.computers(), maxMiB: (() => { try {
|
|
172
|
+
return readHostTools(this.store.home).fileTransferMaxMiB;
|
|
173
|
+
}
|
|
174
|
+
catch {
|
|
175
|
+
return 25;
|
|
176
|
+
} })() };
|
|
177
|
+
const records = this.store.list('_system', 'desktop-host');
|
|
178
|
+
const revoked = new Set(records.filter(record => !record.enabled).map(record => record.id));
|
|
179
|
+
const states = [...this.sessions.values()];
|
|
180
|
+
for (const record of records)
|
|
181
|
+
if (!states.some(host => host.key === record.id))
|
|
182
|
+
states.push(newHostState(record.id, true));
|
|
183
|
+
if (deviceHost && !states.some(host => host.key === deviceHost))
|
|
184
|
+
states.push(newHostState(deviceHost, deviceHost !== 'local'));
|
|
185
|
+
// Revoked pairings remain stored for reauthorization, not as offline computers.
|
|
186
|
+
// Filter after merging sessions and message origin so neither can resurrect them.
|
|
187
|
+
const hosts = states.filter(s => !revoked.has(s.key)).map((s) => {
|
|
188
|
+
const info = s.info, online = this.hostOnline(s), record = records.find(record => record.id === s.key), open = (s.key === 'local' ? global.server : global.script) && record?.enabled !== false;
|
|
189
|
+
const manual = this.current(s, 'local'), waiting = manual ? 'human_control' : s.paused.has('local') ? 'paused' : 'ready';
|
|
190
|
+
const base = agent && (agent.archived || agent.remoteAgentId) ? 'agent_unavailable' : !open ? 'disabled' : !online ? 'offline' : !['darwin', 'win32'].includes(info?.platform ?? '') ? 'unsupported' : undefined;
|
|
191
|
+
const capability = (reason) => ({ enabled: !reason, status: reason ?? waiting });
|
|
192
|
+
const screen = capability(base ?? (!info?.approved.includes(this.ownerKey(owner)) ? 'not_authorized' : !info.screen || !info.accessibility ? 'system_permission_required' : undefined));
|
|
193
|
+
const files = capability(base ?? (!(info?.full ?? []).includes(this.ownerKey(owner)) ? 'not_authorized' : undefined));
|
|
194
|
+
const metadata = online && info?.environment ? { version: info.environment.version, osRelease: info.environment.osRelease, arch: info.environment.arch, timezone: info.environment.timezone, ...(files.enabled ? structuredClone(info.environment) : {}) } : undefined;
|
|
195
|
+
return { id: s.key, target: s.key === 'local' ? 'server' : s.key, name: this.label(s) || record?.name || s.key, kind: s.key === 'local' ? 'server' : 'computer', source: s.key === deviceHost, online, open,
|
|
196
|
+
...(info ? { epoch: info.id, platform: info.platform } : {}), ...(s.seen ? { lastSeen: s.seen } : {}), ...(metadata ? { metadata } : {}),
|
|
197
|
+
capabilities: { view: { ...screen }, input: { ...screen }, fileRead: { ...files }, fileWrite: { ...files }, shell: { ...files }, fileTransfer: { ...files } },
|
|
198
|
+
transfer: { protocol: !info ? 'unknown' : info.fileTransferVersion === 1 ? 'chunked' : 'legacy', readMaxMiB: !info ? null : info.fileTransferVersion === 1 ? global.maxMiB : Math.min(global.maxMiB, 12), writeMaxMiB: !info ? null : info.fileTransferVersion === 1 ? global.maxMiB : Math.min(global.maxMiB, 10) } };
|
|
199
|
+
}).sort((a, b) => a.id === 'local' ? -1 : b.id === 'local' ? 1 : a.id.localeCompare(b.id));
|
|
200
|
+
return { capturedAt, ...(deviceHost ? { sourceHost: deviceHost } : {}), hosts };
|
|
201
|
+
}
|
|
202
|
+
onlineHostsLine(owner, deviceHost) { return deviceInventoryText(this.snapshot(owner, undefined, deviceHost)); }
|
|
203
|
+
deviceContextLine(owner, deviceHost) { return deviceSourceText(this.snapshot(owner, undefined, deviceHost)); }
|
|
204
|
+
agent(owner, id) { const a = this.store.require(owner, 'agent', id); this.nodes.requireSource(owner, a); if (a.archived || a.remoteAgentId)
|
|
205
|
+
throw new HttpError(409, '此机器人无法使用桌面环境', 'computer_unavailable'); return a; }
|
|
206
|
+
resource(owner, agent, mode) { return mode === 'local' ? 'local' : digest(this.ownerKey(owner) + ':' + agent.id + ':' + (agent.browserProfile ?? 'persistent')); }
|
|
207
|
+
hostStates(owner) { return [...this.sessions.values()].map(s => { const online = this.hostOnline(s), info = online ? s.info : undefined; return { id: s.key, name: this.label(s), platform: info?.platform ?? '', online, local: { supported: ['darwin', 'win32'].includes(info?.platform ?? ''), authorized: !!info && info.approved.includes(this.ownerKey(owner)), screen: info?.screen === true, accessibility: info?.accessibility === true, ready: !!info && this.ready(s, owner), fullAuthorized: !!info && (info.full ?? []).includes(this.ownerKey(owner)) }, browser: { available: online } }; }).sort((a, b) => a.id === 'local' ? -1 : b.id === 'local' ? 1 : a.name.localeCompare(b.name)); }
|
|
208
|
+
state(owner, agent) { const mode = this.selected(owner, agent), s = this.sessionFor(agent), online = !!s && this.hostOnline(s), info = online ? s.info : undefined; return { online, host: info ? { id: s.key, name: this.label(s), platform: info.platform } : null, local: { supported: ['darwin', 'win32'].includes(info?.platform ?? ''), authorized: !!info && info.approved.includes(this.ownerKey(owner)), screen: info?.screen === true, accessibility: info?.accessibility === true, ready: !!info && this.ready(s, owner), fullAuthorized: !!info && (info.full ?? []).includes(this.ownerKey(owner)) }, browser: { available: online, profile: agent.browserProfile ?? 'persistent' }, selected: mode ?? null, agent: this.store.agentSummary(agent), hosts: this.hostStates(owner) }; }
|
|
209
|
+
/** Every Bot follows the same global desktop policy. */
|
|
210
|
+
modeOpen(owner, agent, mode) { return this.selected(owner, agent) === mode; }
|
|
211
|
+
check(s, owner, agentId, mode, epoch, version, files = false) { const a = this.agent(owner, agentId); if (!s || !this.hostOnline(s) || s.info.id !== epoch)
|
|
212
|
+
throw new HttpError(409, '桌面端已断开,请在电脑上打开夭夭后重试。', 'desktop_offline'); if (this.auth.pushAuthorizationVersion(owner) !== version || !this.modeOpen(owner, a, mode))
|
|
213
|
+
throw new HttpError(410, '电脑授权已改变,请重新连接。', 'computer_control_expired'); this.requireHost(s); if (files && !this.readyFull(s, owner))
|
|
214
|
+
throw new HttpError(403, '请在桌面端授权文件与命令访问。', 'desktop_full_required'); if (mode === 'local' && !files && !this.ready(s, owner))
|
|
215
|
+
throw new HttpError(403, s.info.platform === 'win32' ? '请在 Windows 客户端授权本机控制,并解锁电脑、恢复桌面会话。' : '请在桌面端授权本机控制,并开启屏幕录制和辅助功能。', 'desktop_permission_required'); }
|
|
216
|
+
invalidate(s) { for (const p of s.pending.values()) {
|
|
217
|
+
if (p.sent && ['input', 'browser'].includes(String(p.command.operation)))
|
|
218
|
+
s.paused.add(String(p.command.resource));
|
|
219
|
+
clearTimeout(p.timer);
|
|
220
|
+
p.reject(new HttpError(409, '桌面连接已改变;执行结果未确认,不会重试。', 'desktop_disconnected'));
|
|
221
|
+
} s.pending.clear(); s.frames.clear(); for (const [key, m] of s.manual) {
|
|
222
|
+
s.paused.add(key);
|
|
223
|
+
this.store.remove('_system', 'computer-control', m.id);
|
|
224
|
+
} s.manual.clear(); }
|
|
225
|
+
close() { this.closed = true; for (const s of this.sessions.values())
|
|
226
|
+
this.invalidate(s); }
|
|
227
|
+
async bridge(ctx) {
|
|
228
|
+
if (ctx.method !== 'POST') {
|
|
229
|
+
ctx.status = 405;
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
let bytes = 0;
|
|
233
|
+
const chunks = [];
|
|
234
|
+
for await (const chunk of ctx.req) {
|
|
235
|
+
bytes += chunk.length;
|
|
236
|
+
if (bytes > 24 * 1024 * 1024)
|
|
237
|
+
throw new HttpError(413, '桌面响应过大', 'desktop_limit');
|
|
238
|
+
chunks.push(Buffer.from(chunk));
|
|
239
|
+
}
|
|
240
|
+
let json;
|
|
241
|
+
try {
|
|
242
|
+
json = JSON.parse(Buffer.concat(chunks).toString());
|
|
243
|
+
}
|
|
244
|
+
catch {
|
|
245
|
+
throw new HttpError(400, '桌面请求格式无效', 'desktop_invalid');
|
|
246
|
+
}
|
|
247
|
+
ctx.body = this.exchange(json);
|
|
248
|
+
}
|
|
249
|
+
/** Loopback App exchange; kept for the local service-instance channel. */
|
|
250
|
+
exchange(body) { return this.exchangeFor(this.localSession(), body); }
|
|
251
|
+
/** Remote computer exchange, admitted upstream by DesktopHostHub. */
|
|
252
|
+
remoteExchange(id, body) {
|
|
253
|
+
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(id))
|
|
254
|
+
throw new HttpError(404, '电脑不存在', 'desktop_host_unknown');
|
|
255
|
+
let s = this.sessions.get(id);
|
|
256
|
+
if (!s) {
|
|
257
|
+
s = newHostState(id, true);
|
|
258
|
+
this.sessions.set(id, s);
|
|
259
|
+
}
|
|
260
|
+
return this.exchangeFor(s, body);
|
|
261
|
+
}
|
|
262
|
+
/** Revocation or replacement of a paired host fences its live commands. */
|
|
263
|
+
dropHost(id) { const s = this.sessions.get(id); if (s) {
|
|
264
|
+
this.invalidate(s);
|
|
265
|
+
this.sessions.delete(id);
|
|
266
|
+
} }
|
|
267
|
+
exchangeFor(s, body) {
|
|
268
|
+
const value = parse(desktopHostExchangeSchema, body);
|
|
269
|
+
if (this.closed)
|
|
270
|
+
throw new HttpError(503, '服务已停止', 'desktop_closed');
|
|
271
|
+
if (s.info && (s.info.id !== value.host.id || !this.hostOnline(s)))
|
|
272
|
+
this.invalidate(s);
|
|
273
|
+
s.info = value.host;
|
|
274
|
+
s.seen = Date.now();
|
|
275
|
+
for (const result of value.results) {
|
|
276
|
+
const p = s.pending.get(result.id);
|
|
277
|
+
if (!p || p.epoch !== value.host.id)
|
|
278
|
+
continue;
|
|
279
|
+
s.pending.delete(p.id);
|
|
280
|
+
clearTimeout(p.timer);
|
|
281
|
+
try {
|
|
282
|
+
p.check();
|
|
283
|
+
if (result.error)
|
|
284
|
+
throw new HttpError(409, result.error, 'desktop_command_failed');
|
|
285
|
+
p.resolve(result.value);
|
|
286
|
+
}
|
|
287
|
+
catch (error) {
|
|
288
|
+
p.reject(error);
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
const commands = [];
|
|
292
|
+
for (const p of s.pending.values()) {
|
|
293
|
+
if (p.sent)
|
|
294
|
+
continue;
|
|
295
|
+
try {
|
|
296
|
+
p.check();
|
|
297
|
+
p.sent = true;
|
|
298
|
+
commands.push({ id: p.id, deadline: p.deadline, ...p.command });
|
|
299
|
+
}
|
|
300
|
+
catch (error) {
|
|
301
|
+
s.pending.delete(p.id);
|
|
302
|
+
clearTimeout(p.timer);
|
|
303
|
+
p.reject(error);
|
|
304
|
+
}
|
|
305
|
+
if (commands.length >= 8)
|
|
306
|
+
break;
|
|
307
|
+
}
|
|
308
|
+
return { commands, capabilities: { environmentMetadata: 1, desktopPlatforms: ['darwin', 'win32'] } };
|
|
309
|
+
}
|
|
310
|
+
command(s, command, check, timeout = 30000) {
|
|
311
|
+
check();
|
|
312
|
+
if (!this.hostOnline(s))
|
|
313
|
+
throw new HttpError(409, '桌面端未连接,请在电脑上打开夭夭。', 'desktop_offline');
|
|
314
|
+
if (s.pending.size >= 64)
|
|
315
|
+
throw new HttpError(429, '桌面操作过多,请稍后重试', 'desktop_busy');
|
|
316
|
+
return new Promise((resolve, reject) => { const id = randomUUID(), deadline = Date.now() + timeout, timer = setTimeout(() => { s.pending.delete(id); if (['input', 'browser'].includes(String(command.operation)))
|
|
317
|
+
s.paused.add(String(command.resource)); reject(new HttpError(504, '桌面操作未确认,不会自动重试。', 'desktop_timeout')); }, timeout); timer.unref(); s.pending.set(id, { id, epoch: s.info.id, deadline, command, check, resolve, reject, timer, sent: false }); });
|
|
318
|
+
}
|
|
319
|
+
context(s, owner, agent, mode, files = false) { const epoch = s?.info?.id ?? '', version = this.auth.pushAuthorizationVersion(owner) ?? 0, profile = agent.browserProfile ?? 'persistent', resource = this.resource(owner, agent, mode); return { key: resource, check: () => { this.check(s, owner, agent.id, mode, epoch, version, files); if ((this.agent(owner, agent.id).browserProfile ?? 'persistent') !== profile)
|
|
320
|
+
throw new HttpError(410, '浏览器资料已切换', 'computer_control_expired'); }, command: { mode, owner: this.ownerKey(owner), resource, profile } }; }
|
|
321
|
+
current(s, key) { const m = s.manual.get(key); if (m && (!this.hostOnline(s) || m.epoch !== s.info.id || m.expiresAt <= Date.now() || this.auth.pushAuthorizationVersion(m.owner) !== m.version)) {
|
|
322
|
+
s.manual.delete(key);
|
|
323
|
+
s.paused.add(key);
|
|
324
|
+
s.frames.delete(key);
|
|
325
|
+
this.store.remove('_system', 'computer-control', m.id);
|
|
326
|
+
return undefined;
|
|
327
|
+
} return m; }
|
|
328
|
+
serial(s, key, work) { const next = (s.queue.get(key) ?? Promise.resolve()).catch(() => { }).then(work); s.queue.set(key, next); void next.finally(() => { if (s.queue.get(key) === next)
|
|
329
|
+
s.queue.delete(key); }).catch(() => { }); return next; }
|
|
330
|
+
async capture(s, c) {
|
|
331
|
+
const cached = s.frames.get(c.key);
|
|
332
|
+
c.check();
|
|
333
|
+
if (cached && cached.generation === (s.generation.get(c.key) ?? 0) && Date.now() - cached.capturedAt < 700)
|
|
334
|
+
return cached;
|
|
335
|
+
const generation = s.generation.get(c.key) ?? 0;
|
|
336
|
+
const value = await this.command(s, { ...c.command, operation: 'view' }, c.check);
|
|
337
|
+
const image = parse(z.object({ data: z.string().min(1).max(22 * 1024 * 1024), width: z.number().int().min(1).max(16384), height: z.number().int().min(1).max(16384) }).passthrough(), value);
|
|
338
|
+
if (generation !== (s.generation.get(c.key) ?? 0))
|
|
339
|
+
throw new HttpError(409, '控制状态改变,请刷新画面', 'computer_frame_stale');
|
|
340
|
+
const frame = { ...image, id: randomUUID(), generation, capturedAt: Date.now() };
|
|
341
|
+
s.frames.set(c.key, frame);
|
|
342
|
+
return frame;
|
|
343
|
+
}
|
|
344
|
+
status(s, owner, a, mode) { const key = this.resource(owner, a, mode), m = s ? this.current(s, key) : undefined, online = !!s && this.hostOnline(s); return { backend: mode, hostName: online ? s.info.name : undefined, mode: !online ? 'off' : m ? (m.owner === owner && m.ready ? 'human' : 'pausing') : s.paused.has(key) ? 'error' : s.activity.get(key) ? 'agent' : 'idle', controlId: m?.owner === owner ? m.id : undefined, generation: s?.generation.get(key) ?? 0, canResume: !!s?.activity.get(key), error: !online ? '请在电脑上打开夭夭桌面端' : s.paused.has(key) ? '接管已断开,请重新接管并交还后继续' : undefined }; }
|
|
345
|
+
assertIdle(owner, agentId) { const a = this.agent(owner, agentId), mode = this.selected(owner, a); if (mode) {
|
|
346
|
+
const s = this.sessionFor(a);
|
|
347
|
+
if (s && this.current(s, this.resource(owner, a, mode)))
|
|
348
|
+
throw new HttpError(409, '请先交还电脑控制权', 'computer_busy');
|
|
349
|
+
} }
|
|
350
|
+
async requireAvailable(owner, a, target) {
|
|
351
|
+
const tools = this.envTools(owner, a);
|
|
352
|
+
if (tools.view || tools.file)
|
|
353
|
+
await requireTeamToolBridge(target, a.profile);
|
|
354
|
+
}
|
|
355
|
+
async copyFile(owner, agent, input, signal, assertActive, epoch, deviceHost, vmTransfer) {
|
|
356
|
+
const args = parse(copySchema, input), source = args.sourceHost === 'vm' ? undefined : this.namedHost(args.sourceHost, deviceHost), target = args.targetHost === 'vm' ? undefined : this.namedHost(args.targetHost, deviceHost);
|
|
357
|
+
if (!source && !target)
|
|
358
|
+
throw new HttpError(400, '请至少指定一台电脑或服务器', 'desktop_transfer_invalid');
|
|
359
|
+
if ((!source || !target) && (!vmTransfer || !readHostTools(this.store.home).vm))
|
|
360
|
+
throw new HttpError(409, '当前 Bot 没有可用的虚拟机文件传输', 'computer_transfer_unavailable');
|
|
361
|
+
const maxBytes = readHostTools(this.store.home).fileTransferMaxMiB * 1024 * 1024;
|
|
362
|
+
const hosts = [...new Set([source, target].filter((host) => !!host))].sort((a, b) => a.key.localeCompare(b.key));
|
|
363
|
+
const contexts = hosts.map(host => ({ host, context: this.context(host, owner, agent, 'local', true), epoch: typeof epoch === 'string' ? (host === this.sessionFor(agent) ? epoch : undefined) : epoch?.[host.key] }));
|
|
364
|
+
const check = () => { signal.throwIfAborted(); assertActive(); for (const item of contexts) {
|
|
365
|
+
if (epoch && typeof epoch === 'object' && !Object.hasOwn(epoch, item.host.key))
|
|
366
|
+
throw new HttpError(410, '目标电脑不在本轮环境快照中,请发起新一轮对话。', 'desktop_context_changed');
|
|
367
|
+
item.context.check();
|
|
368
|
+
if (this.sessions.get(item.host.key) !== item.host || (item.epoch !== undefined && item.host.info?.id !== item.epoch))
|
|
369
|
+
throw new HttpError(410, '传输中的电脑连接已改变,请核对文件后重试。', 'desktop_disconnected');
|
|
370
|
+
} };
|
|
371
|
+
check();
|
|
372
|
+
const command = async (host, action) => { const context = contexts.find(item => item.host === host).context; if (action.op !== 'transfer-abort')
|
|
373
|
+
await available(); return this.command(host, { ...context.command, operation: 'file', action }, action.op === 'transfer-abort' ? context.check : check, 60000); };
|
|
374
|
+
// A stable lock order prevents A→B and B→A transfers from deadlocking.
|
|
375
|
+
const locked = (index) => index < contexts.length
|
|
376
|
+
? this.serial(contexts[index].host, contexts[index].context.key, () => locked(index + 1))
|
|
377
|
+
: perform();
|
|
378
|
+
const available = async () => {
|
|
379
|
+
while (contexts.some(({ host, context }) => this.current(host, context.key) || host.paused.has(context.key))) {
|
|
380
|
+
check();
|
|
381
|
+
await new Promise(resolve => setTimeout(resolve, 150));
|
|
382
|
+
}
|
|
383
|
+
check();
|
|
384
|
+
};
|
|
385
|
+
const perform = async () => {
|
|
386
|
+
await available();
|
|
387
|
+
const endpoint = (host, path) => host
|
|
388
|
+
? { host: host.key, name: this.label(host), path, chunks: host.info?.fileTransferVersion === 1, call: action => command(host, action) }
|
|
389
|
+
: { host: 'vm', name: '当前 Bot 的虚拟机', path, chunks: true, call: async (action) => { if (action.op !== 'transfer-abort')
|
|
390
|
+
await available(); return vmTransfer(action); } };
|
|
391
|
+
const result = await copyBetweenEndpoints(endpoint(source, args.sourcePath), endpoint(target, args.targetPath), maxBytes, args.overwrite, check);
|
|
392
|
+
const handoffNotes = contexts.flatMap(({ host }) => { const key = owner + ':' + agent.id, note = host.notes.get(key); if (!note)
|
|
393
|
+
return []; host.notes.delete(key); return [`${this.label(host)}:${note}`]; });
|
|
394
|
+
return { ...result, ...(handoffNotes.length ? { handoffNotes } : {}) };
|
|
395
|
+
};
|
|
396
|
+
for (const { host, context } of contexts)
|
|
397
|
+
host.activity.set(context.key, (host.activity.get(context.key) ?? 0) + 1);
|
|
398
|
+
try {
|
|
399
|
+
return await locked(0);
|
|
400
|
+
}
|
|
401
|
+
finally {
|
|
402
|
+
for (const { host, context } of contexts)
|
|
403
|
+
host.activity.set(context.key, Math.max(0, (host.activity.get(context.key) ?? 1) - 1));
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
async call(owner, agentId, id, input, signal, assertActive, expected, epoch, deviceHost, vmTransfer) {
|
|
407
|
+
if (id === 'desktop_browser' || expected === 'browser')
|
|
408
|
+
throw new HttpError(404, '当前环境不支持这个工具', 'tool_not_found');
|
|
409
|
+
const a = this.agent(owner, agentId);
|
|
410
|
+
if (id === 'desktop_file_copy')
|
|
411
|
+
return this.copyFile(owner, a, input, signal, assertActive, epoch, deviceHost, vmTransfer);
|
|
412
|
+
const { host, ...arguments_ } = typeof input === 'object' && input ? input : {};
|
|
413
|
+
const requestedHost = host === undefined ? undefined : parse(z.string().trim().min(1).max(128), host);
|
|
414
|
+
const s = this.targetFor(a, requestedHost, deviceHost);
|
|
415
|
+
const c = this.context(s, owner, a, expected, DESKTOP_FILE_TOOL_IDS.has(id));
|
|
416
|
+
const pinned = typeof epoch === 'string' ? (s === this.sessionFor(a) ? epoch : undefined) : epoch?.[s.key];
|
|
417
|
+
const check = () => { signal.throwIfAborted(); assertActive(); if (epoch && typeof epoch === 'object' && !Object.hasOwn(epoch, s.key))
|
|
418
|
+
throw new HttpError(410, '目标电脑不在本轮环境快照中,请发起新一轮对话。', 'desktop_context_changed'); c.check(); if (pinned !== undefined && s.info?.id !== pinned)
|
|
419
|
+
throw new HttpError(410, '桌面连接已改变', 'desktop_disconnected'); };
|
|
420
|
+
check();
|
|
421
|
+
s.activity.set(c.key, (s.activity.get(c.key) ?? 0) + 1);
|
|
422
|
+
try {
|
|
423
|
+
return await this.serial(s, c.key, async () => {
|
|
424
|
+
while (this.current(s, c.key) || s.paused.has(c.key)) {
|
|
425
|
+
check();
|
|
426
|
+
await new Promise(resolve => setTimeout(resolve, 150));
|
|
427
|
+
}
|
|
428
|
+
check();
|
|
429
|
+
let result;
|
|
430
|
+
if (id === 'desktop_environment_view') {
|
|
431
|
+
const frame = await this.capture(s, { ...c, check });
|
|
432
|
+
this.toolFrames.set(signal, frame.id);
|
|
433
|
+
result = { content: [{ type: 'image', mimeType: 'image/png', data: frame.data }, { type: 'text', text: JSON.stringify({ width: frame.width, height: frame.height, host: s.info.name, mode: expected }) }] };
|
|
434
|
+
}
|
|
435
|
+
else if (DESKTOP_FILE_TOOL_IDS.has(id) && expected === 'local') {
|
|
436
|
+
if (!this.readyFull(s, owner))
|
|
437
|
+
throw new HttpError(403, '请在桌面端授权文件与命令访问后重试。', 'desktop_full_required');
|
|
438
|
+
const action = id === 'desktop_shell' ? parse(shellSchema, arguments_) : parse(fileSchema, { op: id === 'desktop_file_list' ? 'list' : id === 'desktop_file_read' ? 'read' : 'write', ...arguments_ });
|
|
439
|
+
result = await this.command(s, { ...c.command, operation: id === 'desktop_shell' ? 'shell' : 'file', action }, check, id === 'desktop_shell' ? 150000 : 60000);
|
|
440
|
+
}
|
|
441
|
+
else if (id === 'desktop_environment_action') {
|
|
442
|
+
const frame = s.frames.get(c.key);
|
|
443
|
+
if (!frame || this.toolFrames.get(signal) !== frame.id || Date.now() - frame.capturedAt > 15000)
|
|
444
|
+
throw new HttpError(409, '请先查看最新电脑画面', 'computer_frame_stale');
|
|
445
|
+
result = await this.command(s, { ...c.command, operation: 'input', action: parse(inputSchema, arguments_), frame: { width: frame.width, height: frame.height } }, check);
|
|
446
|
+
s.frames.delete(c.key);
|
|
447
|
+
}
|
|
448
|
+
else
|
|
449
|
+
throw new HttpError(404, '当前环境不支持这个工具', 'tool_not_found');
|
|
450
|
+
const note = s.notes.get(owner + ':' + agentId);
|
|
451
|
+
if (note) {
|
|
452
|
+
s.notes.delete(owner + ':' + agentId);
|
|
453
|
+
if (result.content)
|
|
454
|
+
result.content.push({ type: 'text', text: '人工交还说明:' + note });
|
|
455
|
+
else
|
|
456
|
+
result = { ...result, handoffNote: note };
|
|
457
|
+
}
|
|
458
|
+
return result;
|
|
459
|
+
});
|
|
460
|
+
}
|
|
461
|
+
finally {
|
|
462
|
+
s.activity.set(c.key, Math.max(0, (s.activity.get(c.key) ?? 1) - 1));
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
/** Epochs of every connected host; pins multi-host tool calls per machine. */
|
|
466
|
+
hostEpochs(owner, agent) { const epochs = {}; for (const s of this.sessions.values())
|
|
467
|
+
if (s.info)
|
|
468
|
+
epochs[s.key] = s.info.id; return epochs; }
|
|
469
|
+
hostEpoch(owner, agent) { return this.sessionFor(agent)?.info?.id ?? ''; }
|
|
470
|
+
get epoch() { return this.sessions.get('local')?.info?.id ?? ''; }
|
|
471
|
+
grant(s, owner, a, c, body) { const m = this.current(s, c.key); const token = typeof body?.token === 'string' ? body.token : ''; if (!m || !m.ready || m.owner !== owner || m.agentId !== a.id || m.id !== body?.controlId || !timingSafeEqual(Buffer.from(digest(token), 'hex'), Buffer.from(digest(m.token), 'hex')))
|
|
472
|
+
throw new HttpError(410, '控制权已失效,请重新接管', 'computer_control_expired'); c.check(); return m; }
|
|
473
|
+
router() {
|
|
474
|
+
const router = new Router();
|
|
475
|
+
router.get('/api/app/agents/:id/desktop-environment', ctx => { const owner = this.auth.require(ctx).id, a = this.store.require(owner, 'agent', ctx.params.id); this.nodes.requireSource(owner, a); ctx.set('Cache-Control', 'no-store'); ctx.body = this.state(owner, a); });
|
|
476
|
+
router.post('/api/app/agents/:id/desktop-environment/authorize', async (ctx) => {
|
|
477
|
+
const user = this.auth.require(ctx);
|
|
478
|
+
this.auth.requireAdmin(ctx);
|
|
479
|
+
const a = this.agent(user.id, ctx.params.id);
|
|
480
|
+
const body = parse(z.object({ hostId: z.union([z.literal('local'), z.string().uuid()]).optional(), scope: z.enum(['screen', 'full']).default('screen') }).strict(), ctx.request.body ?? {});
|
|
481
|
+
const s = body.hostId !== undefined ? this.sessions.get(body.hostId) : this.sessionFor(a);
|
|
482
|
+
if (!s || !this.hostOnline(s))
|
|
483
|
+
throw new HttpError(409, '桌面端未连接,请在电脑上打开夭夭。', 'desktop_offline');
|
|
484
|
+
const owner = this.ownerKey(user.id), epoch = s.info.id, authorizeKey = user.id + ':' + s.key + ':' + body.scope;
|
|
485
|
+
let pending = this.authorizing.get(authorizeKey);
|
|
486
|
+
if (!pending) {
|
|
487
|
+
pending = this.command(s, { operation: 'authorize', owner, account: user.username, scope: body.scope }, () => { this.auth.requireAdmin(ctx); if (!this.hostOnline(s) || epoch !== s.info.id)
|
|
488
|
+
throw new HttpError(409, '桌面端已断开', 'desktop_offline'); }, 120000).finally(() => this.authorizing.delete(authorizeKey));
|
|
489
|
+
this.authorizing.set(authorizeKey, pending);
|
|
490
|
+
}
|
|
491
|
+
ctx.body = await pending;
|
|
492
|
+
});
|
|
493
|
+
router.put('/api/app/agents/:id/browser-profile', ctx => { const owner = this.auth.require(ctx).id, a = this.agent(owner, ctx.params.id), body = parse(z.object({ profile: z.enum(['persistent', 'temporary']) }).strict(), ctx.request.body); this.assertIdle(owner, a.id); this.store.updateAgent(owner, a.id, { browserProfile: body.profile }); ctx.body = { ok: true }; });
|
|
494
|
+
router.get('/api/app/agents/:id/browser', async (ctx) => { const owner = this.auth.require(ctx).id, a = this.agent(owner, ctx.params.id); if (this.selected(owner, a) !== 'browser')
|
|
495
|
+
throw new HttpError(409, '请先选择仅浏览器环境', 'desktop_unselected'); const s = this.sessionFor(a); ctx.body = await this.command(s, { ...this.context(s, owner, a, 'browser').command, operation: 'browser-state' }, this.context(s, owner, a, 'browser').check); });
|
|
496
|
+
router.get('/api/app/agents/:id/computer', async (ctx, next) => { const owner = this.auth.require(ctx).id, a = this.store.require(owner, 'agent', ctx.params.id), mode = this.selected(owner, a); if (typeof ctx.query.backend === 'string' && ctx.query.backend !== 'desktop')
|
|
497
|
+
return next(); if (!mode)
|
|
498
|
+
return next(); this.agent(owner, a.id); ctx.body = this.status(this.takeoverSession(a, ctx.query.host), owner, a, mode); });
|
|
499
|
+
router.get('/api/app/agents/:id/computer/frame', async (ctx, next) => { const owner = this.auth.require(ctx).id, a = this.store.require(owner, 'agent', ctx.params.id), mode = this.selected(owner, a); if (typeof ctx.query.backend === 'string' && ctx.query.backend !== 'desktop')
|
|
500
|
+
return next(); if (!mode)
|
|
501
|
+
return next(); this.agent(owner, a.id); const s = this.takeoverSession(a, ctx.query.host), c = this.context(s, owner, a, mode); ctx.set('Cache-Control', 'no-store'); c.check(); ctx.body = await this.capture(s, c); });
|
|
502
|
+
router.post('/api/app/agents/:id/computer/:action', async (ctx, next) => {
|
|
503
|
+
const owner = this.auth.require(ctx).id, a = this.store.require(owner, 'agent', ctx.params.id), mode = this.selected(owner, a);
|
|
504
|
+
if (typeof ctx.query.backend === 'string' && ctx.query.backend !== 'desktop')
|
|
505
|
+
return next();
|
|
506
|
+
if (!mode)
|
|
507
|
+
return next();
|
|
508
|
+
this.agent(owner, a.id);
|
|
509
|
+
const s = this.takeoverSession(a, ctx.query.host), c = this.context(s, owner, a, mode), body = ctx.request.body, action = ctx.params.action;
|
|
510
|
+
c.check();
|
|
511
|
+
if (action === 'take') {
|
|
512
|
+
const { requestId } = parse(z.object({ requestId: z.string().uuid() }).strict(), body), old = this.current(s, c.key);
|
|
513
|
+
if (old) {
|
|
514
|
+
if (old.owner !== owner || old.agentId !== a.id || old.requestId !== requestId)
|
|
515
|
+
throw new HttpError(409, '已有页面正在控制这台电脑', 'computer_busy');
|
|
516
|
+
while (!old.ready) {
|
|
517
|
+
c.check();
|
|
518
|
+
if (this.current(s, c.key) !== old)
|
|
519
|
+
throw new HttpError(410, '接管已失效', 'computer_control_expired');
|
|
520
|
+
await new Promise(resolve => setTimeout(resolve, 80));
|
|
521
|
+
}
|
|
522
|
+
ctx.body = { ...this.status(s, owner, a, mode), token: old.token };
|
|
523
|
+
return;
|
|
524
|
+
}
|
|
525
|
+
const m = { id: randomUUID(), token: randomBytes(32).toString('base64url'), requestId, owner, agentId: a.id, version: this.auth.pushAuthorizationVersion(owner) ?? 0, expiresAt: Date.now() + 90000, generation: (s.generation.get(c.key) ?? 0) + 1, epoch: s.info.id, actions: new Map() };
|
|
526
|
+
s.manual.set(c.key, m);
|
|
527
|
+
s.generation.set(c.key, m.generation);
|
|
528
|
+
s.frames.delete(c.key);
|
|
529
|
+
this.store.put('_system', 'computer-control', m.id, { owner, agentId: a.id, environmentId: 'desktop:' + s.key + ':' + c.key, expiresAt: m.expiresAt });
|
|
530
|
+
// The lane may contain agent calls waiting for this takeover. Only await
|
|
531
|
+
// commands already dispatched to the host, not the whole agent lane.
|
|
532
|
+
while ([...s.pending.values()].some(p => p.command.resource === c.key)) {
|
|
533
|
+
c.check();
|
|
534
|
+
if (this.current(s, c.key) !== m)
|
|
535
|
+
throw new HttpError(410, '接管已失效', 'computer_control_expired');
|
|
536
|
+
await new Promise(resolve => setTimeout(resolve, 80));
|
|
537
|
+
}
|
|
538
|
+
try {
|
|
539
|
+
await this.command(s, { ...c.command, operation: 'open' }, c.check);
|
|
540
|
+
m.ready = true;
|
|
541
|
+
m.expiresAt = Date.now() + 30000;
|
|
542
|
+
ctx.body = { ...this.status(s, owner, a, mode), token: m.token };
|
|
543
|
+
}
|
|
544
|
+
catch (error) {
|
|
545
|
+
s.manual.delete(c.key);
|
|
546
|
+
s.paused.add(c.key);
|
|
547
|
+
this.store.remove('_system', 'computer-control', m.id);
|
|
548
|
+
throw error;
|
|
549
|
+
}
|
|
550
|
+
return;
|
|
551
|
+
}
|
|
552
|
+
const m = this.grant(s, owner, a, c, body);
|
|
553
|
+
if (action === 'renew') {
|
|
554
|
+
m.expiresAt = Date.now() + 30000;
|
|
555
|
+
this.store.put('_system', 'computer-control', m.id, { owner, agentId: a.id, environmentId: 'desktop:' + s.key + ':' + c.key, expiresAt: m.expiresAt });
|
|
556
|
+
ctx.body = { ok: true };
|
|
557
|
+
return;
|
|
558
|
+
}
|
|
559
|
+
if (action === 'giveback') {
|
|
560
|
+
m.releasing = true;
|
|
561
|
+
await m.pending?.catch(() => { });
|
|
562
|
+
if (typeof body.notes === 'string')
|
|
563
|
+
s.notes.set(owner + ':' + a.id, body.notes.slice(0, 4000));
|
|
564
|
+
s.manual.delete(c.key);
|
|
565
|
+
s.paused.delete(c.key);
|
|
566
|
+
this.store.remove('_system', 'computer-control', m.id);
|
|
567
|
+
s.generation.set(c.key, m.generation + 1);
|
|
568
|
+
s.frames.delete(c.key);
|
|
569
|
+
ctx.body = { ok: true };
|
|
570
|
+
return;
|
|
571
|
+
}
|
|
572
|
+
if (action === 'input' || action === 'browser') {
|
|
573
|
+
const v = parse(z.object({ controlId: z.string(), token: z.string(), requestId: z.string().uuid(), generation: z.number().int(), frameId: z.string().uuid(), action: z.unknown() }).strict(), body), fingerprint = JSON.stringify([action, v.generation, v.frameId, v.action]), old = m.actions.get(v.requestId);
|
|
574
|
+
if (old) {
|
|
575
|
+
if (old.fingerprint !== fingerprint)
|
|
576
|
+
throw new HttpError(409, '请求编号冲突', 'idempotency_conflict');
|
|
577
|
+
ctx.body = await old.value;
|
|
578
|
+
return;
|
|
579
|
+
}
|
|
580
|
+
const f = s.frames.get(c.key);
|
|
581
|
+
if (!f || f.id !== v.frameId || f.generation !== v.generation || m.generation !== v.generation || Date.now() - f.capturedAt > 10000)
|
|
582
|
+
throw new HttpError(409, '画面已过期,请刷新后操作', 'computer_frame_stale');
|
|
583
|
+
if (m.releasing || m.actions.size >= 512)
|
|
584
|
+
throw new HttpError(409, '请交还后重新接管', 'computer_control_expired');
|
|
585
|
+
if (action === 'browser' && mode !== 'browser')
|
|
586
|
+
throw new HttpError(409, '当前环境不是浏览器', 'desktop_unselected');
|
|
587
|
+
const input = (action === 'browser' ? parse(browserSchema, v.action) : parse(inputSchema, v.action)), check = () => { this.grant(s, owner, a, c, body); if (this.current(s, c.key) !== m)
|
|
588
|
+
throw new HttpError(410, '控制权已失效', 'computer_control_expired'); };
|
|
589
|
+
const result = (m.pending ?? Promise.resolve()).catch(() => { }).then(() => this.command(s, { ...c.command, operation: action === 'browser' ? 'browser' : 'input', action: input, frame: { width: f.width, height: f.height } }, check));
|
|
590
|
+
m.pending = result;
|
|
591
|
+
m.actions.set(v.requestId, { fingerprint, value: result });
|
|
592
|
+
ctx.body = await result;
|
|
593
|
+
s.frames.delete(c.key);
|
|
594
|
+
return;
|
|
595
|
+
}
|
|
596
|
+
throw new HttpError(404, '电脑操作不存在', 'not_found');
|
|
597
|
+
});
|
|
598
|
+
return router;
|
|
599
|
+
}
|
|
600
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
const text = z.string().min(1).max(4096).regex(/^[^\u0000-\u001f\u007f]*$/);
|
|
3
|
+
export const desktopHostEnvironmentSchema = z.object({
|
|
4
|
+
version: z.literal(1), osRelease: text, arch: text, shell: text,
|
|
5
|
+
homeDirectory: text, defaultCwd: text, fileRoots: z.array(text).min(1).max(8),
|
|
6
|
+
shellScope: z.literal('user'), timezone: text,
|
|
7
|
+
}).strict();
|
|
8
|
+
export const desktopHostInfoSchema = z.object({
|
|
9
|
+
id: z.string().uuid(), name: z.string().max(128), platform: z.string().max(16),
|
|
10
|
+
screen: z.boolean(), accessibility: z.boolean(), approved: z.array(z.string().regex(/^[a-f0-9]{64}$/)).max(100),
|
|
11
|
+
full: z.array(z.string().regex(/^[a-f0-9]{64}$/)).max(100).optional(),
|
|
12
|
+
fileTransferVersion: z.literal(1).optional(), environment: desktopHostEnvironmentSchema.optional(),
|
|
13
|
+
}).strict();
|
|
14
|
+
export const desktopHostExchangeSchema = z.object({
|
|
15
|
+
host: desktopHostInfoSchema,
|
|
16
|
+
results: z.array(z.object({ id: z.string().uuid(), value: z.unknown().optional(), error: z.string().max(500).optional() }).strict()).max(20),
|
|
17
|
+
}).strict();
|