@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,652 @@
|
|
|
1
|
+
import { createHash, randomBytes, randomUUID } from 'node:crypto';
|
|
2
|
+
import { spawn } from 'node:child_process';
|
|
3
|
+
import { mkdir, realpath, chmod, lstat, rm, readFile } from 'node:fs/promises';
|
|
4
|
+
import { join, resolve, posix, dirname, basename } from 'node:path';
|
|
5
|
+
import { z } from 'zod';
|
|
6
|
+
import { recoverWorkspace } from './workspaceRecovery.js';
|
|
7
|
+
import { COMMAND_ROOT, GUEST_COMMAND } from './commandProcess.js';
|
|
8
|
+
import { ComputerUserData, COMPUTER_HOME } from './userData.js';
|
|
9
|
+
import { CLOSE_DESKTOP } from './desktopClose.js';
|
|
10
|
+
export const COMPUTER_WORKSPACE = '/home/cua/workspace';
|
|
11
|
+
export const CUA_DRIVER = '/usr/local/libexec/openmausbot/cua-driver';
|
|
12
|
+
export const CUA_SOCKET = '/run/user/1000/openmausbot-cua.sock';
|
|
13
|
+
const managedLabel = 'cn.samien.yaoyao.computer', runnerLabel = 'cn.samien.yaoyao.runner', specLabel = 'cn.samien.yaoyao.computer-spec', ownerLabel = 'cn.samien.yaoyao.computer-owner';
|
|
14
|
+
const mib = 1024 * 1024;
|
|
15
|
+
const command = (runtime, args, options = {}) => new Promise((resolveResult, reject) => {
|
|
16
|
+
const child = spawn(runtime, args, { stdio: 'pipe', signal: options.signal }), out = [], err = [];
|
|
17
|
+
let bytes = 0, failure;
|
|
18
|
+
const timer = setTimeout(() => { failure = Object.assign(new Error('电脑命令超时'), { killed: true }); child.kill('SIGTERM'); }, options.timeout ?? 15000);
|
|
19
|
+
const collect = (target, chunk) => { bytes += chunk.length; if (bytes > 8 * mib) {
|
|
20
|
+
failure = Object.assign(new Error('电脑输出超过限制'), { killed: true });
|
|
21
|
+
child.kill('SIGTERM');
|
|
22
|
+
}
|
|
23
|
+
else
|
|
24
|
+
target.push(chunk); };
|
|
25
|
+
child.stdout.on('data', chunk => collect(out, Buffer.from(chunk)));
|
|
26
|
+
child.stderr.on('data', chunk => collect(err, Buffer.from(chunk)));
|
|
27
|
+
child.once('error', error => { failure = error; });
|
|
28
|
+
child.stdin.on('error', () => { });
|
|
29
|
+
child.once('close', code => { clearTimeout(timer); const result = { stdout: Buffer.concat(out).toString(), stderr: Buffer.concat(err).toString() }; if (failure || code !== 0)
|
|
30
|
+
reject(Object.assign(failure ?? new Error('电脑命令失败'), { ...result, ...(!failure ? { code } : {}) }));
|
|
31
|
+
else
|
|
32
|
+
resolveResult(result); });
|
|
33
|
+
child.stdin.end(options.input);
|
|
34
|
+
});
|
|
35
|
+
const schema = z.object({
|
|
36
|
+
network: z.enum(['none', 'public-proxy', 'managed-proxy']).default('none'),
|
|
37
|
+
id: z.string().uuid(), ownerKey: z.string().min(1).max(256),
|
|
38
|
+
imageId: z.string().regex(/^sha256:[a-f0-9]{64}$/),
|
|
39
|
+
cpus: z.number().int().min(1).max(8).default(2), memoryMiB: z.number().int().min(1024).max(16384).default(4096),
|
|
40
|
+
cwd: z.string().max(4096).refine(value => !/[\u0000-\u001f,]/.test(value) && posix.isAbsolute(value) && posix.normalize(value) === value && value !== '/' && !/^\/(?:proc|sys|dev|run|tmp|etc|usr|bin|sbin)(?:\/|$)/.test(value) && !['/home/cua', '/root', '/var/lib/dbus/machine-id'].includes(value), '电脑工作目录不受支持').default(COMPUTER_WORKSPACE),
|
|
41
|
+
pids: z.number().int().min(64).max(1024).default(512),
|
|
42
|
+
}).strict();
|
|
43
|
+
class Semaphore {
|
|
44
|
+
max;
|
|
45
|
+
active = 0;
|
|
46
|
+
queue = [];
|
|
47
|
+
constructor(max) {
|
|
48
|
+
this.max = max;
|
|
49
|
+
}
|
|
50
|
+
acquire() {
|
|
51
|
+
const admit = () => { this.active++; let released = false; return () => { if (released)
|
|
52
|
+
return; released = true; this.release(); }; };
|
|
53
|
+
if (this.active < this.max)
|
|
54
|
+
return Promise.resolve(admit());
|
|
55
|
+
return new Promise(resolve => this.queue.push(() => resolve(admit())));
|
|
56
|
+
}
|
|
57
|
+
release() { this.active--; this.queue.shift()?.(); }
|
|
58
|
+
}
|
|
59
|
+
class Lane {
|
|
60
|
+
active = 0;
|
|
61
|
+
writer = false;
|
|
62
|
+
queue = [];
|
|
63
|
+
exec = new Semaphore(8);
|
|
64
|
+
gui = new Semaphore(1);
|
|
65
|
+
async read(action, slot = this.exec) {
|
|
66
|
+
await this.enter(false);
|
|
67
|
+
const releaseSlot = await slot.acquire();
|
|
68
|
+
try {
|
|
69
|
+
return await action();
|
|
70
|
+
}
|
|
71
|
+
finally {
|
|
72
|
+
releaseSlot();
|
|
73
|
+
this.leave();
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
async write(action) {
|
|
77
|
+
await this.enter(true);
|
|
78
|
+
try {
|
|
79
|
+
return await action();
|
|
80
|
+
}
|
|
81
|
+
finally {
|
|
82
|
+
this.leave();
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
enter(writer) {
|
|
86
|
+
// Writer preference: once a lifecycle operation queues, new operations wait behind it.
|
|
87
|
+
const blocked = writer ? this.writer || this.active > 0 : this.writer || this.queue.some(item => item.writer);
|
|
88
|
+
if (!blocked) {
|
|
89
|
+
this.writer = writer;
|
|
90
|
+
this.active++;
|
|
91
|
+
return Promise.resolve();
|
|
92
|
+
}
|
|
93
|
+
return new Promise(admit => this.queue.push({ writer, admit: () => { this.writer = writer; this.active++; admit(); } }));
|
|
94
|
+
}
|
|
95
|
+
leave() {
|
|
96
|
+
this.active--;
|
|
97
|
+
if (this.active > 0)
|
|
98
|
+
return;
|
|
99
|
+
this.writer = false;
|
|
100
|
+
while (this.queue.length) {
|
|
101
|
+
const head = this.queue[0];
|
|
102
|
+
if (head.writer) {
|
|
103
|
+
if (this.active === 0) {
|
|
104
|
+
this.queue.shift();
|
|
105
|
+
head.admit();
|
|
106
|
+
}
|
|
107
|
+
break;
|
|
108
|
+
}
|
|
109
|
+
this.queue.shift();
|
|
110
|
+
head.admit();
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
export class ComputerError extends Error {
|
|
115
|
+
code;
|
|
116
|
+
constructor(code, message) {
|
|
117
|
+
super(message);
|
|
118
|
+
this.code = code;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
const digest = (value) => createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
|
122
|
+
const capabilities = (values) => Array.isArray(values) ? values.map(value => String(value).toUpperCase().replace(/^CAP_/, '')).sort() : [];
|
|
123
|
+
/** A private container per environment. No tools, filesystem operations or
|
|
124
|
+
* process execution fall back to the host. Remote hosts run their own Runner. */
|
|
125
|
+
export class ContainerComputerProvider {
|
|
126
|
+
runtime;
|
|
127
|
+
runnerId;
|
|
128
|
+
home;
|
|
129
|
+
run;
|
|
130
|
+
environment;
|
|
131
|
+
userData;
|
|
132
|
+
fixedCapacity = false;
|
|
133
|
+
lanes = new Map();
|
|
134
|
+
capabilities = { isolation: 'container', shell: true, desktop: true, persistentWorkspace: true, sharedDesktop: false, snapshots: false, network: 'none' };
|
|
135
|
+
constructor(runtime, runnerId, home, run = command, environment = process.env) {
|
|
136
|
+
this.runtime = runtime;
|
|
137
|
+
this.runnerId = runnerId;
|
|
138
|
+
this.home = home;
|
|
139
|
+
this.run = run;
|
|
140
|
+
this.environment = environment;
|
|
141
|
+
z.string().uuid().parse(runnerId);
|
|
142
|
+
if (!['docker', 'podman'].includes(runtime))
|
|
143
|
+
throw new ComputerError('runtime_unsupported', '电脑运行时不受支持');
|
|
144
|
+
this.userData = new ComputerUserData(home, runtime, run);
|
|
145
|
+
}
|
|
146
|
+
lane(id) { let lane = this.lanes.get(id); if (!lane) {
|
|
147
|
+
lane = new Lane();
|
|
148
|
+
this.lanes.set(id, lane);
|
|
149
|
+
} return lane; }
|
|
150
|
+
async verifyRuntime() {
|
|
151
|
+
if (this.runtime === 'docker') {
|
|
152
|
+
const endpoint = this.environment.DOCKER_HOST || JSON.parse((await this.run('docker', ['context', 'inspect', '--format', '{{json .Endpoints.docker.Host}}'])).stdout);
|
|
153
|
+
if (typeof endpoint !== 'string' || !(/^(?:unix|npipe):\/\//.test(endpoint)))
|
|
154
|
+
throw new ComputerError('computer_remote_engine', '远程 Docker 引擎请在目的电脑安装 Runner');
|
|
155
|
+
}
|
|
156
|
+
else {
|
|
157
|
+
const connections = JSON.parse((await this.run('podman', ['system', 'connection', 'list', '--format', 'json'])).stdout);
|
|
158
|
+
const endpoint = this.environment.CONTAINER_HOST || connections.find((entry) => entry.Default)?.URI;
|
|
159
|
+
if (endpoint) {
|
|
160
|
+
const url = new URL(endpoint);
|
|
161
|
+
if (url.protocol !== 'unix:' && !['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname))
|
|
162
|
+
throw new ComputerError('computer_remote_engine', '远程 Podman 引擎请在目的电脑安装 Runner');
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
validateSpecification(value) {
|
|
167
|
+
const parsed = schema.safeParse(value);
|
|
168
|
+
if (!parsed.success)
|
|
169
|
+
throw new ComputerError('computer_spec_invalid', '电脑环境配置无效');
|
|
170
|
+
return parsed.data;
|
|
171
|
+
}
|
|
172
|
+
networkIds = new Map();
|
|
173
|
+
name(spec) { return `yaoyao-computer-${digest([this.runnerId, spec.id]).slice(0, 24)}`; }
|
|
174
|
+
labels(spec) { return { [managedLabel]: spec.id, [runnerLabel]: this.runnerId, [ownerLabel]: digest(spec.ownerKey), [specLabel]: digest(spec) }; }
|
|
175
|
+
async workspace(spec) {
|
|
176
|
+
const base = resolve(this.home, 'computer-workspaces');
|
|
177
|
+
await mkdir(base, { recursive: true, mode: 0o700 });
|
|
178
|
+
const canonical = await realpath(base), path = join(canonical, spec.id);
|
|
179
|
+
await recoverWorkspace(canonical, spec.id);
|
|
180
|
+
if (/[,\n\r\0]/.test(path))
|
|
181
|
+
throw new ComputerError('computer_path_invalid', '电脑数据目录包含不支持的字符');
|
|
182
|
+
await mkdir(path, { recursive: true, mode: 0o700 });
|
|
183
|
+
if (await realpath(path) !== path)
|
|
184
|
+
throw new ComputerError('computer_path_unsafe', '电脑工作区不能指向其他目录');
|
|
185
|
+
if (process.platform !== 'win32')
|
|
186
|
+
await chmod(path, 0o700);
|
|
187
|
+
return path;
|
|
188
|
+
}
|
|
189
|
+
async inspectRaw(name) {
|
|
190
|
+
try {
|
|
191
|
+
const result = await this.run(this.runtime, ['inspect', name]);
|
|
192
|
+
return JSON.parse(result.stdout)[0];
|
|
193
|
+
}
|
|
194
|
+
catch (error) {
|
|
195
|
+
if (/no such (?:object|container)|no container with name or ID/i.test(String(error.stderr ?? '')))
|
|
196
|
+
return undefined;
|
|
197
|
+
throw error;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
assertOwned(spec, detail) {
|
|
201
|
+
if (!detail || !/^[a-f0-9]{64}$/.test(String(detail.Id)) || Object.entries(this.labels(spec)).filter(([key]) => key !== specLabel).some(([key, value]) => detail.Config?.Labels?.[key] !== value))
|
|
202
|
+
throw new ComputerError('computer_owner_mismatch', '电脑实例不属于当前执行节点或配置已变化');
|
|
203
|
+
}
|
|
204
|
+
assertConfiguration(spec, detail, workspace, legacy = false) {
|
|
205
|
+
this.assertOwned(spec, detail);
|
|
206
|
+
if (legacy && detail.Config?.Labels?.['cn.samien.yaoyao.userdata'])
|
|
207
|
+
throw new ComputerError('computer_configuration_unsafe', '电脑用户资料挂载缺失,已保留原实例');
|
|
208
|
+
const host = detail.HostConfig ?? {}, expectedCaps = this.runtime === 'podman' ? ['SETGID', 'SETUID', 'SYS_CHROOT'] : ['SETGID', 'SETUID'];
|
|
209
|
+
const nanoCPUs = host.NanoCpus ?? (host.CpuPeriod > 0 ? host.CpuQuota / host.CpuPeriod * 1e9 : 0);
|
|
210
|
+
const ports = Object.entries(host.PortBindings ?? {}), mounts = detail.Mounts ?? [];
|
|
211
|
+
const destinations = spec.cwd === COMPUTER_WORKSPACE ? [COMPUTER_WORKSPACE] : [COMPUTER_WORKSPACE, spec.cwd];
|
|
212
|
+
const expected = [...destinations.map(destination => ({ source: workspace, destination, rw: true })), ...(legacy ? [] : this.userData.mounts(resolve(dirname(workspace), '..', 'computer-userdata', spec.id)))];
|
|
213
|
+
if (detail.Config?.Labels?.[specLabel] !== digest(spec) || detail.Image !== spec.imageId || host.Privileged !== false || host.Memory !== spec.memoryMiB * mib || host.MemorySwap !== spec.memoryMiB * mib
|
|
214
|
+
|| nanoCPUs !== spec.cpus * 1e9 || host.PidsLimit !== spec.pids || host.IpcMode !== 'private' || host.CgroupnsMode !== 'private'
|
|
215
|
+
|| (spec.network === 'managed-proxy' ? ![`container:${this.name(spec)}-network`, `container:${this.networkIds.get(spec.id)}`].includes(host.NetworkMode) : host.NetworkMode !== 'none') || host.PidMode === 'host' || host.UsernsMode === 'host' || host.UTSMode === 'host'
|
|
216
|
+
|| (host.SecurityOpt ?? []).some((value) => /^no-new-privileges(?::true)?$/.test(value) || /unconfined/.test(value))
|
|
217
|
+
|| JSON.stringify(capabilities(host.CapAdd)) !== JSON.stringify(expectedCaps) || !capabilities(host.CapDrop).includes('ALL')
|
|
218
|
+
|| (host.Devices ?? []).length || (host.DeviceRequests ?? []).length || host.RestartPolicy?.Name !== 'no'
|
|
219
|
+
|| mounts.length !== expected.length || mounts.some((mount) => mount.Type !== 'bind' || !expected.some(item => item.source === mount.Source && item.destination === mount.Destination && item.rw === mount.RW)) || new Set(mounts.map((mount) => mount.Destination)).size !== expected.length
|
|
220
|
+
|| ports.length !== 0)
|
|
221
|
+
throw new ComputerError('computer_configuration_unsafe', '电脑实例的隔离、资源或数据目录不符合要求,请先停止并核对');
|
|
222
|
+
}
|
|
223
|
+
state(spec, detail, workspace) {
|
|
224
|
+
this.assertConfiguration(spec, detail, workspace);
|
|
225
|
+
if (Object.values(detail.NetworkSettings?.Ports ?? {}).some(bindings => Array.isArray(bindings) && bindings.length))
|
|
226
|
+
throw new ComputerError('computer_viewer_unsafe', '电脑环境不能发布网络端口');
|
|
227
|
+
return { id: spec.id, containerId: detail.Id, running: detail.State?.Running === true, workspace, isolation: 'container' };
|
|
228
|
+
}
|
|
229
|
+
async migratedContainer(spec, detail, workspace) {
|
|
230
|
+
if (!detail || detail.Mounts?.some((mount) => mount.Destination === COMPUTER_WORKSPACE && mount.Source === workspace))
|
|
231
|
+
return detail;
|
|
232
|
+
let root = resolve(this.home);
|
|
233
|
+
while (dirname(root) !== root && basename(root) !== '.yaoyao')
|
|
234
|
+
root = dirname(root);
|
|
235
|
+
if (basename(root) !== '.yaoyao')
|
|
236
|
+
return detail;
|
|
237
|
+
let migration;
|
|
238
|
+
try {
|
|
239
|
+
migration = JSON.parse(await readFile(join(root, '.data-home-migration.json'), 'utf8'));
|
|
240
|
+
}
|
|
241
|
+
catch (error) {
|
|
242
|
+
if (error.code === 'ENOENT')
|
|
243
|
+
return detail;
|
|
244
|
+
throw error;
|
|
245
|
+
}
|
|
246
|
+
if (migration.phase !== 'complete' || migration.target !== root || migration.source !== join(dirname(root), '.hermes-yaoyao'))
|
|
247
|
+
return detail;
|
|
248
|
+
const oldWorkspace = migration.source + workspace.slice(root.length);
|
|
249
|
+
this.assertConfiguration(spec, detail, oldWorkspace, !this.hasUserData(detail));
|
|
250
|
+
if (detail.State?.Running)
|
|
251
|
+
throw new ComputerError('computer_migration_busy', '旧目录的虚拟机仍在运行,请停止后再迁移');
|
|
252
|
+
await this.userData.capture(spec, detail.Id, true);
|
|
253
|
+
// Preserve the old writable layer as a stopped backup; only the verified name changes.
|
|
254
|
+
await this.run(this.runtime, ['rename', detail.Id, `${this.name(spec)}-before-data-move-${detail.Id.slice(0, 8)}`]);
|
|
255
|
+
return undefined;
|
|
256
|
+
}
|
|
257
|
+
async inspect(value) {
|
|
258
|
+
await this.verifyRuntime();
|
|
259
|
+
const spec = this.validateSpecification(value), workspace = await this.workspace(spec), detail = await this.migratedContainer(spec, await this.inspectRaw(this.name(spec)), workspace);
|
|
260
|
+
if (detail && spec.network === 'managed-proxy') {
|
|
261
|
+
const gateway = await this.inspectRaw(this.name(spec) + '-network');
|
|
262
|
+
this.assertNetwork(spec, gateway);
|
|
263
|
+
this.networkIds.set(spec.id, gateway.Id);
|
|
264
|
+
}
|
|
265
|
+
if (detail && !this.hasUserData(detail)) {
|
|
266
|
+
this.assertConfiguration(spec, detail, workspace, true);
|
|
267
|
+
return { id: spec.id, containerId: detail.Id, running: detail.State?.Running === true, workspace, isolation: 'container' };
|
|
268
|
+
}
|
|
269
|
+
if (detail)
|
|
270
|
+
await this.userData.existing(spec).then(path => { if (!path)
|
|
271
|
+
throw new ComputerError('computer_data_missing', '电脑用户资料缺失,已停止自动重建'); });
|
|
272
|
+
return detail ? this.state(spec, detail, workspace) : undefined;
|
|
273
|
+
}
|
|
274
|
+
hasUserData(detail) { return detail.Mounts?.some((mount) => mount.Destination === COMPUTER_HOME); }
|
|
275
|
+
args(spec, workspace, userData) {
|
|
276
|
+
return ['create', '--name', this.name(spec), ...(spec.network === 'managed-proxy' ? [] : ['--hostname', this.name(spec), '--add-host', `${this.name(spec)}:127.0.0.1`]),
|
|
277
|
+
...Object.entries(this.labels(spec)).flatMap(([key, value]) => ['--label', `${key}=${value}`]),
|
|
278
|
+
...(userData ? ['--label', 'cn.samien.yaoyao.userdata=1'] : []),
|
|
279
|
+
'--restart', 'no', '--network', spec.network === 'managed-proxy' ? `container:${this.name(spec)}-network` : 'none', '--ipc', 'private', '--cgroupns', 'private',
|
|
280
|
+
'--memory', `${spec.memoryMiB}m`, '--memory-swap', `${spec.memoryMiB}m`, '--cpus', String(spec.cpus), '--pids-limit', String(spec.pids),
|
|
281
|
+
'--shm-size', '512m', '--cap-drop', 'ALL', '--cap-add', 'SETUID', '--cap-add', 'SETGID',
|
|
282
|
+
...(this.runtime === 'podman' ? ['--userns', 'keep-id:uid=1000,gid=1000', '--user', 'root', '--cap-add', 'SYS_CHROOT'] : []),
|
|
283
|
+
...[...new Set([COMPUTER_WORKSPACE, spec.cwd])].flatMap(destination => ['--mount', `type=bind,source=${workspace},target=${destination}${this.runtime === 'podman' ? ',relabel=private' : ''}`]),
|
|
284
|
+
...(userData ? this.userData.mounts(userData).flatMap(mount => ['--mount', `type=bind,source=${mount.source},target=${mount.destination}${mount.rw ? '' : ',readonly'}${this.runtime === 'podman' ? ',relabel=private' : ''}`]) : []),
|
|
285
|
+
...(spec.network === 'public-proxy' ? ['--env', 'HTTP_PROXY=http://127.0.0.1:3128', '--env', 'HTTPS_PROXY=http://127.0.0.1:3128', '--env', 'http_proxy=http://127.0.0.1:3128', '--env', 'https_proxy=http://127.0.0.1:3128', '--env', 'NO_PROXY=localhost,127.0.0.1,::1', '--env', 'no_proxy=localhost,127.0.0.1,::1'] : []),
|
|
286
|
+
'--env', `VNC_PW=${randomBytes(24).toString('base64url')}`, spec.imageId];
|
|
287
|
+
}
|
|
288
|
+
async ensure(value, authorize) {
|
|
289
|
+
const spec = this.validateSpecification(value);
|
|
290
|
+
return this.lane(spec.id).write(async () => {
|
|
291
|
+
authorize();
|
|
292
|
+
await this.verifyRuntime();
|
|
293
|
+
authorize();
|
|
294
|
+
const workspace = await this.workspace(spec);
|
|
295
|
+
if (spec.network === 'managed-proxy')
|
|
296
|
+
await this.ensureNetwork(spec, authorize);
|
|
297
|
+
let detail = await this.migratedContainer(spec, await this.inspectRaw(this.name(spec)), workspace);
|
|
298
|
+
if (detail && !this.hasUserData(detail)) {
|
|
299
|
+
// Verify the old boundary before copying private data. A single legacy
|
|
300
|
+
// flag is relaxed only for this one-time migration.
|
|
301
|
+
const checked = { ...detail, HostConfig: { ...detail.HostConfig, SecurityOpt: (detail.HostConfig?.SecurityOpt ?? []).filter((value) => !/^no-new-privileges(?::true)?$/.test(value)) } };
|
|
302
|
+
this.assertConfiguration(spec, checked, workspace, true);
|
|
303
|
+
await this.stopOwned(spec, detail.Id);
|
|
304
|
+
await this.userData.capture(spec, detail.Id, true);
|
|
305
|
+
authorize();
|
|
306
|
+
await this.run(this.runtime, ['rm', '--', detail.Id]);
|
|
307
|
+
detail = undefined;
|
|
308
|
+
}
|
|
309
|
+
if (detail?.HostConfig?.SecurityOpt?.some((value) => /^no-new-privileges(?::true)?$/.test(value))) {
|
|
310
|
+
await this.stopOwned(spec, detail.Id);
|
|
311
|
+
await this.run(this.runtime, ['rm', '--', detail.Id]);
|
|
312
|
+
detail = undefined;
|
|
313
|
+
}
|
|
314
|
+
if (!detail) {
|
|
315
|
+
const image = JSON.parse((await this.run(this.runtime, ['image', 'inspect', spec.imageId])).stdout)[0];
|
|
316
|
+
if (image?.Id !== spec.imageId || image.Config?.Labels?.['com.openmausbot.cua-driver'] !== '0.20.0' || image.Config?.Labels?.['com.openmausbot.image-layer'] !== '5')
|
|
317
|
+
throw new ComputerError('computer_image_incompatible', '电脑镜像缺少已验证的驱动,请先安装兼容镜像');
|
|
318
|
+
authorize();
|
|
319
|
+
let userData = await this.userData.existing(spec);
|
|
320
|
+
if (!userData) {
|
|
321
|
+
// Seed from an unstarted image container, so its desktop defaults and
|
|
322
|
+
// user-installed tools are available before the home is over-mounted.
|
|
323
|
+
const seed = await this.run(this.runtime, this.args(spec, workspace));
|
|
324
|
+
const seedId = seed.stdout.trim(), seedDetail = await this.inspectRaw(seedId);
|
|
325
|
+
this.assertConfiguration(spec, seedDetail, workspace, true);
|
|
326
|
+
await this.stopOwned(spec, seedId);
|
|
327
|
+
userData = await this.userData.capture(spec, seedId, false);
|
|
328
|
+
await this.run(this.runtime, ['rm', '--', seedId]);
|
|
329
|
+
}
|
|
330
|
+
await this.userData.beforeImageChange(spec, workspace);
|
|
331
|
+
authorize();
|
|
332
|
+
const created = await this.run(this.runtime, this.args(spec, workspace, userData));
|
|
333
|
+
const id = created.stdout.trim();
|
|
334
|
+
if (!/^[a-f0-9]{64}$/.test(id))
|
|
335
|
+
throw new ComputerError('computer_creation_uncertain', '电脑创建结果不确定,请核对实例');
|
|
336
|
+
detail = await this.inspectRaw(id);
|
|
337
|
+
}
|
|
338
|
+
let state = this.state(spec, detail, workspace);
|
|
339
|
+
if (!await this.userData.existing(spec))
|
|
340
|
+
throw new ComputerError('computer_data_missing', '电脑用户资料缺失,已停止自动重建');
|
|
341
|
+
authorize();
|
|
342
|
+
if (!state.running)
|
|
343
|
+
await this.run(this.runtime, ['start', '--', state.containerId]);
|
|
344
|
+
try {
|
|
345
|
+
authorize();
|
|
346
|
+
detail = await this.inspectRaw(state.containerId);
|
|
347
|
+
state = this.state(spec, detail, workspace);
|
|
348
|
+
authorize();
|
|
349
|
+
if (!state.running)
|
|
350
|
+
throw new ComputerError('computer_start_failed', '电脑环境未能启动');
|
|
351
|
+
return state;
|
|
352
|
+
}
|
|
353
|
+
catch (error) {
|
|
354
|
+
await this.stopOwned(spec, state.containerId).catch(() => { });
|
|
355
|
+
throw error;
|
|
356
|
+
}
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
async stopOwned(spec, id, graceful = true) {
|
|
360
|
+
const detail = await this.inspectRaw(id);
|
|
361
|
+
if (!detail)
|
|
362
|
+
return;
|
|
363
|
+
this.assertOwned(spec, detail);
|
|
364
|
+
if (detail.State?.Running && graceful)
|
|
365
|
+
await this.run(this.runtime, ['exec', '--user', '1000:1000', '--', id, 'python3', '-c', CLOSE_DESKTOP], { timeout: 6000 }).catch(() => { });
|
|
366
|
+
if (detail.State?.Running)
|
|
367
|
+
await this.run(this.runtime, ['stop', '--time', '10', '--', id], { timeout: 15000 });
|
|
368
|
+
const stopped = await this.inspectRaw(id);
|
|
369
|
+
if (stopped?.State?.Running)
|
|
370
|
+
throw new ComputerError('computer_stop_uncertain', '尚未确认电脑环境已停止');
|
|
371
|
+
}
|
|
372
|
+
async stop(value) {
|
|
373
|
+
const spec = this.validateSpecification(value);
|
|
374
|
+
return this.lane(spec.id).write(async () => { await this.verifyRuntime(); const detail = await this.inspectRaw(this.name(spec)); if (detail) {
|
|
375
|
+
this.assertOwned(spec, detail);
|
|
376
|
+
await this.stopOwned(spec, detail.Id);
|
|
377
|
+
} });
|
|
378
|
+
}
|
|
379
|
+
/** Called by the updater while the old Web service is quiesced. Old versions
|
|
380
|
+
* remove containers on shutdown, so waiting until the new service boots loses
|
|
381
|
+
* their writable homes. Leave the verified source intact until shutdown. */
|
|
382
|
+
async preserveUserData(value) {
|
|
383
|
+
const spec = this.validateSpecification(value);
|
|
384
|
+
return this.lane(spec.id).write(async () => {
|
|
385
|
+
if (await this.userData.existing(spec))
|
|
386
|
+
return false;
|
|
387
|
+
await this.verifyRuntime();
|
|
388
|
+
const detail = await this.inspectRaw(this.name(spec));
|
|
389
|
+
if (!detail)
|
|
390
|
+
return false;
|
|
391
|
+
this.assertOwned(spec, detail);
|
|
392
|
+
if (this.hasUserData(detail)) {
|
|
393
|
+
if (!await this.userData.existing(spec))
|
|
394
|
+
throw new Error('电脑用户资料缺失');
|
|
395
|
+
return false;
|
|
396
|
+
}
|
|
397
|
+
if (spec.network === 'managed-proxy') {
|
|
398
|
+
const gateway = await this.inspectRaw(this.name(spec) + '-network');
|
|
399
|
+
this.assertNetwork(spec, gateway);
|
|
400
|
+
this.networkIds.set(spec.id, gateway.Id);
|
|
401
|
+
}
|
|
402
|
+
this.assertConfiguration(spec, detail, await this.workspace(spec), true);
|
|
403
|
+
await this.stopOwned(spec, detail.Id);
|
|
404
|
+
await this.userData.capture(spec, detail.Id, true);
|
|
405
|
+
return true;
|
|
406
|
+
});
|
|
407
|
+
}
|
|
408
|
+
async remove(value) {
|
|
409
|
+
const spec = this.validateSpecification(value);
|
|
410
|
+
return this.lane(spec.id).write(async () => {
|
|
411
|
+
await this.verifyRuntime();
|
|
412
|
+
const detail = await this.inspectRaw(this.name(spec));
|
|
413
|
+
if (detail) {
|
|
414
|
+
this.assertOwned(spec, detail);
|
|
415
|
+
await this.stopOwned(spec, detail.Id);
|
|
416
|
+
// Shutdown, cancellation and image changes also pass through remove.
|
|
417
|
+
// Preserve legacy homes before any of those paths delete a container.
|
|
418
|
+
if (!this.hasUserData(detail)) {
|
|
419
|
+
const workspace = await this.workspace(spec);
|
|
420
|
+
if ((detail.Mounts ?? []).some((mount) => mount.Type !== 'bind' || mount.Source !== workspace))
|
|
421
|
+
throw new ComputerError('computer_configuration_unsafe', '旧电脑的数据挂载不符合要求,已保留原容器');
|
|
422
|
+
await this.userData.capture(spec, detail.Id, true);
|
|
423
|
+
}
|
|
424
|
+
await this.run(this.runtime, ['rm', '--', detail.Id]);
|
|
425
|
+
}
|
|
426
|
+
if (spec.network === 'managed-proxy') {
|
|
427
|
+
const gateway = await this.inspectRaw(this.name(spec) + '-network');
|
|
428
|
+
if (gateway) {
|
|
429
|
+
this.assertNetwork(spec, gateway);
|
|
430
|
+
await this.run(this.runtime, ['rm', '-f', '--', gateway.Id]);
|
|
431
|
+
}
|
|
432
|
+
this.networkIds.delete(spec.id);
|
|
433
|
+
}
|
|
434
|
+
// Persistent workspace deletion is a separate, explicit operation.
|
|
435
|
+
});
|
|
436
|
+
}
|
|
437
|
+
async waitForDesktop(state, authorize, signal) {
|
|
438
|
+
const deadline = Date.now() + 15000;
|
|
439
|
+
for (;;) {
|
|
440
|
+
authorize();
|
|
441
|
+
if (signal?.aborted)
|
|
442
|
+
throw new ComputerError('computer_cancelled', '操作已停止');
|
|
443
|
+
try {
|
|
444
|
+
await this.run(this.runtime, ['exec', '--user', '1000:1000', '--', state.containerId, CUA_DRIVER, 'call', 'health_report', '{}', '--socket', CUA_SOCKET], { timeout: 3000, signal });
|
|
445
|
+
authorize();
|
|
446
|
+
return;
|
|
447
|
+
}
|
|
448
|
+
catch (error) {
|
|
449
|
+
if (signal?.aborted)
|
|
450
|
+
throw new ComputerError('computer_cancelled', '操作已停止');
|
|
451
|
+
if (!/Cua Driver daemon is not running on/.test(String(error.stderr ?? '')) || Date.now() >= deadline)
|
|
452
|
+
throw error;
|
|
453
|
+
await new Promise(resolve => setTimeout(resolve, 250));
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
async execute(value, argv, options) {
|
|
458
|
+
const spec = this.validateSpecification(value);
|
|
459
|
+
if (!argv.length || argv.length > 64 || argv.some(arg => typeof arg !== 'string' || arg.includes('\0')) || argv.join('').length > 65536)
|
|
460
|
+
throw new ComputerError('computer_command_invalid', '电脑命令无效或过长');
|
|
461
|
+
return this.lane(spec.id).read(async () => {
|
|
462
|
+
options.authorize();
|
|
463
|
+
if (options.signal?.aborted)
|
|
464
|
+
throw new ComputerError('computer_cancelled', '操作已停止');
|
|
465
|
+
const state = await this.inspect(spec);
|
|
466
|
+
if (!state?.running)
|
|
467
|
+
throw new ComputerError('computer_not_running', '电脑环境尚未运行');
|
|
468
|
+
options.authorize();
|
|
469
|
+
if (argv[0] === CUA_DRIVER)
|
|
470
|
+
await this.waitForDesktop(state, options.authorize, options.signal);
|
|
471
|
+
if (options.signal?.aborted)
|
|
472
|
+
throw new ComputerError('computer_cancelled', '操作已停止');
|
|
473
|
+
const operationId = randomUUID(), timeout = Math.min(60000, Math.max(1000, options.timeout ?? 30000));
|
|
474
|
+
let cancellation;
|
|
475
|
+
const cancel = () => cancellation ??= (async () => {
|
|
476
|
+
try {
|
|
477
|
+
const result = await this.run(this.runtime, ['exec', '--user', '0:0', '--', state.containerId, 'python3', '-c', GUEST_COMMAND, 'cancel', COMMAND_ROOT, operationId], { timeout: 10000 });
|
|
478
|
+
if (JSON.parse(result.stdout).stopped !== true)
|
|
479
|
+
throw new Error('missing stop acknowledgement');
|
|
480
|
+
}
|
|
481
|
+
catch {
|
|
482
|
+
if (options.mayFence === undefined || options.mayFence())
|
|
483
|
+
this.fence(spec, state.containerId);
|
|
484
|
+
throw new ComputerError('computer_cancel_uncertain', '尚未确认电脑命令已停止,请检查电脑中的运行进程');
|
|
485
|
+
}
|
|
486
|
+
})();
|
|
487
|
+
// Observe cancellation immediately; waiting for the docker client to close
|
|
488
|
+
// would leave its guest command running after the holder had been revoked.
|
|
489
|
+
const abort = () => { void cancel().catch(() => { }); };
|
|
490
|
+
options.signal?.addEventListener('abort', abort, { once: true });
|
|
491
|
+
try {
|
|
492
|
+
if (options.signal?.aborted) {
|
|
493
|
+
await cancel();
|
|
494
|
+
throw new ComputerError('computer_cancelled', '操作已停止');
|
|
495
|
+
}
|
|
496
|
+
const user = options.user ?? 'cua', home = user === 'root' ? '/root' : '/home/cua';
|
|
497
|
+
const result = await this.run(this.runtime, ['exec', ...(options.input ? ['-i'] : []), '--user', '0:0', '--env', `HOME=${home}`, '--env', `USER=${user}`, '--workdir', spec.cwd, '--', state.containerId, 'python3', '-u', '-c', GUEST_COMMAND, 'run', COMMAND_ROOT, operationId, user, String(timeout / 1000), ...argv], { timeout: timeout + 5000, signal: options.signal, input: options.input });
|
|
498
|
+
if (options.signal?.aborted) {
|
|
499
|
+
await cancel();
|
|
500
|
+
throw new ComputerError('computer_cancelled', '操作已停止');
|
|
501
|
+
}
|
|
502
|
+
options.authorize();
|
|
503
|
+
return result;
|
|
504
|
+
}
|
|
505
|
+
catch (error) {
|
|
506
|
+
// Ambiguous client exits need a guest acknowledgement. If it cannot be
|
|
507
|
+
// obtained, retain the existing sole-holder fence without stopping peers.
|
|
508
|
+
if (options.signal?.aborted || error.killed || typeof error.code !== 'number') {
|
|
509
|
+
await cancel();
|
|
510
|
+
if (options.signal?.aborted)
|
|
511
|
+
throw new ComputerError('computer_cancelled', '操作已停止');
|
|
512
|
+
}
|
|
513
|
+
throw error;
|
|
514
|
+
}
|
|
515
|
+
finally {
|
|
516
|
+
options.signal?.removeEventListener('abort', abort);
|
|
517
|
+
}
|
|
518
|
+
}, options.lane === 'gui' ? this.lane(spec.id).gui : undefined);
|
|
519
|
+
}
|
|
520
|
+
/** Escalates to the lifecycle lane so the stop never runs under live operations. */
|
|
521
|
+
fence(spec, id) { void this.lane(spec.id).write(async () => { await this.stopOwned(spec, id, false).catch(() => { }); }).catch(() => { }); }
|
|
522
|
+
async installSkill(value, bundle, script, options) {
|
|
523
|
+
const spec = this.validateSpecification(value);
|
|
524
|
+
return this.lane(spec.id).read(async () => {
|
|
525
|
+
options.authorize();
|
|
526
|
+
if (options.signal?.aborted)
|
|
527
|
+
throw new ComputerError('computer_cancelled', '操作已停止');
|
|
528
|
+
const state = await this.inspect(spec);
|
|
529
|
+
if (!state?.running)
|
|
530
|
+
throw new ComputerError('computer_not_running', '电脑环境尚未运行');
|
|
531
|
+
options.authorize();
|
|
532
|
+
const result = await this.run(this.runtime, ['exec', '-i', '--user', '0:0', '--', state.containerId, 'python3', '-c', script, 'install'], { input: Buffer.from(JSON.stringify(bundle)), signal: options.signal, timeout: 30000 });
|
|
533
|
+
options.authorize();
|
|
534
|
+
return JSON.parse(result.stdout);
|
|
535
|
+
});
|
|
536
|
+
}
|
|
537
|
+
async capture(value, authorize) {
|
|
538
|
+
const spec = this.validateSpecification(value);
|
|
539
|
+
return this.lane(spec.id).read(async () => {
|
|
540
|
+
const state = await this.inspect(spec);
|
|
541
|
+
authorize();
|
|
542
|
+
if (!state?.running)
|
|
543
|
+
throw new ComputerError('computer_not_running', '电脑尚未运行');
|
|
544
|
+
await this.waitForDesktop(state, authorize);
|
|
545
|
+
const file = `/tmp/yaoyao-view-${randomBytes(12).toString('hex')}.png`;
|
|
546
|
+
const exec = (args) => this.run(this.runtime, ['exec', '--user', '1000:1000', '--', state.containerId, ...args], { timeout: 10000 });
|
|
547
|
+
try {
|
|
548
|
+
await exec([CUA_DRIVER, 'call', 'get_desktop_state', '{}', '--socket', CUA_SOCKET, '--screenshot-out-file', file]);
|
|
549
|
+
authorize();
|
|
550
|
+
const data = (await exec(['base64', '-w0', file])).stdout.trim(), bytes = Buffer.from(data, 'base64');
|
|
551
|
+
if (bytes.length < 24 || bytes.subarray(1, 4).toString() !== 'PNG')
|
|
552
|
+
throw new ComputerError('computer_frame_invalid', '电脑画面无效');
|
|
553
|
+
authorize();
|
|
554
|
+
return { data, width: bytes.readUInt32BE(16), height: bytes.readUInt32BE(20), capturedAt: Date.now() };
|
|
555
|
+
}
|
|
556
|
+
finally {
|
|
557
|
+
await exec(['rm', '-f', '--', file]).catch(() => { });
|
|
558
|
+
}
|
|
559
|
+
}, this.lane(spec.id).gui);
|
|
560
|
+
}
|
|
561
|
+
async deleteWorkspace(value) {
|
|
562
|
+
const spec = this.validateSpecification(value);
|
|
563
|
+
return this.lane(spec.id).write(async () => {
|
|
564
|
+
if (await this.inspectRaw(this.name(spec)))
|
|
565
|
+
throw new ComputerError('computer_busy', '删除工作区前必须移除电脑实例');
|
|
566
|
+
const base = await realpath(resolve(this.home, 'computer-workspaces')).catch(error => { if (error.code === 'ENOENT')
|
|
567
|
+
return undefined; throw error; });
|
|
568
|
+
const userData = await this.userData.existing(spec);
|
|
569
|
+
if (base) {
|
|
570
|
+
const path = join(base, spec.id), info = await lstat(path).catch(error => { if (error.code === 'ENOENT')
|
|
571
|
+
return undefined; throw error; });
|
|
572
|
+
if (info) {
|
|
573
|
+
if (!info.isDirectory() || info.isSymbolicLink() || await realpath(path) !== path)
|
|
574
|
+
throw new ComputerError('computer_path_unsafe', '拒绝删除非预期的电脑工作区');
|
|
575
|
+
await rm(path, { recursive: true });
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
if (userData)
|
|
579
|
+
await rm(userData, { recursive: true });
|
|
580
|
+
await rm(this.userData.path(spec.id) + '.required', { force: true });
|
|
581
|
+
});
|
|
582
|
+
}
|
|
583
|
+
assertNetwork(spec, gateway) {
|
|
584
|
+
const host = gateway?.HostConfig ?? {};
|
|
585
|
+
if (!gateway || gateway.Config?.Labels?.['cn.samien.yaoyao.network-owner'] !== digest({ id: spec.id, ownerKey: spec.ownerKey }) || host.NetworkMode !== 'none' || host.Privileged !== false || host.PidMode === 'host' || (gateway.Mounts ?? []).some((m) => m.Type !== 'tmpfs') || JSON.stringify(capabilities(host.CapAdd)) !== JSON.stringify(['NET_ADMIN']) || !capabilities(host.CapDrop).includes('ALL') || (host.Devices ?? []).length !== 1 || host.Devices[0].PathInContainer !== '/dev/net/tun' || Object.keys(host.PortBindings ?? {}).length)
|
|
586
|
+
throw new ComputerError('computer_network_unsafe', '网络网关隔离配置不匹配');
|
|
587
|
+
}
|
|
588
|
+
async verifyNetwork() {
|
|
589
|
+
await this.verifyRuntime();
|
|
590
|
+
try {
|
|
591
|
+
const image = JSON.parse((await this.run(this.runtime, ['image', 'inspect', 'localhost/yaoyao/network:1'])).stdout)[0];
|
|
592
|
+
if (image?.Config?.Labels?.['cn.samien.yaoyao.network-gateway'] !== '1')
|
|
593
|
+
throw new Error();
|
|
594
|
+
}
|
|
595
|
+
catch {
|
|
596
|
+
throw new ComputerError('computer_network_upgrade_required', '请在本地虚拟机设置中重新准备网络镜像');
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
async ensureNetwork(spec, authorize) {
|
|
600
|
+
const name = this.name(spec) + '-network';
|
|
601
|
+
let gateway = await this.inspectRaw(name);
|
|
602
|
+
if (gateway) {
|
|
603
|
+
this.assertNetwork(spec, gateway);
|
|
604
|
+
}
|
|
605
|
+
else {
|
|
606
|
+
const image = JSON.parse((await this.run(this.runtime, ['image', 'inspect', 'localhost/yaoyao/network:1'])).stdout)[0];
|
|
607
|
+
if (image?.Config?.Labels?.['cn.samien.yaoyao.network-gateway'] !== '1')
|
|
608
|
+
throw new ComputerError('computer_network_upgrade_required', '请重新准备虚拟机网络镜像');
|
|
609
|
+
authorize();
|
|
610
|
+
await this.run(this.runtime, ['create', '--name', name, '--label', `cn.samien.yaoyao.network-owner=${digest({ id: spec.id, ownerKey: spec.ownerKey })}`, '--network', 'none', '--dns', '198.18.0.1', '--cap-drop', 'ALL', '--cap-add', 'NET_ADMIN', '--device', '/dev/net/tun', '--memory', '128m', '--pids-limit', '64', '--read-only', '--tmpfs', '/run', image.Id, '--init']);
|
|
611
|
+
gateway = await this.inspectRaw(name);
|
|
612
|
+
}
|
|
613
|
+
this.assertNetwork(spec, gateway);
|
|
614
|
+
this.networkIds.set(spec.id, gateway.Id);
|
|
615
|
+
authorize();
|
|
616
|
+
if (!gateway?.State?.Running)
|
|
617
|
+
await this.run(this.runtime, ['start', name]);
|
|
618
|
+
}
|
|
619
|
+
async openNetworkPipe(value, authorize) {
|
|
620
|
+
const spec = this.validateSpecification(value);
|
|
621
|
+
authorize();
|
|
622
|
+
await this.ensureNetwork(spec, authorize);
|
|
623
|
+
return spawn(this.runtime, ['exec', '-i', '--user', '0:0', '--', this.name(spec) + '-network', 'python3', '/usr/local/libexec/yaoyao/network_gateway.py'], { stdio: 'pipe' });
|
|
624
|
+
}
|
|
625
|
+
async openPipe(value, argv, authorize) {
|
|
626
|
+
const spec = this.validateSpecification(value);
|
|
627
|
+
authorize();
|
|
628
|
+
const state = await this.inspect(spec);
|
|
629
|
+
authorize();
|
|
630
|
+
if (!state?.running)
|
|
631
|
+
throw new ComputerError('computer_not_running', '电脑环境尚未运行');
|
|
632
|
+
return spawn(this.runtime, ['exec', '-i', '--user', '1000:1000', '--workdir', spec.cwd, '--', state.containerId, ...argv], { stdio: 'pipe' });
|
|
633
|
+
}
|
|
634
|
+
async configureNetwork(value, authorize) {
|
|
635
|
+
const spec = this.validateSpecification(value);
|
|
636
|
+
if (spec.network !== 'public-proxy')
|
|
637
|
+
return;
|
|
638
|
+
return this.lane(spec.id).read(async () => {
|
|
639
|
+
authorize();
|
|
640
|
+
const state = await this.inspect(spec);
|
|
641
|
+
authorize();
|
|
642
|
+
if (!state?.running)
|
|
643
|
+
throw new ComputerError('computer_not_running', '电脑环境尚未运行');
|
|
644
|
+
const script = 'import pathlib,json; chrome={"ProxyMode":"fixed_servers","ProxyServer":"http://127.0.0.1:3128","ProxyBypassList":"localhost;127.0.0.1;[::1]","QuicAllowed":False}; firefox={"policies":{"Proxy":{"Mode":"manual","HTTPProxy":"http://127.0.0.1:3128","SSLProxy":"http://127.0.0.1:3128","Passthrough":"localhost,127.0.0.1,::1","Locked":True},"DNSOverHTTPS":{"Enabled":False,"Locked":True}}}; paths=[("/etc/chromium/policies/managed/yaoyao.json",chrome),("/etc/opt/chrome/policies/managed/yaoyao.json",chrome),("/usr/lib/firefox/policies/managed/yaoyao.json",firefox),("/usr/lib/firefox-esr/distribution/policies.json",firefox),("/opt/firefox/distribution/policies.json",firefox)]; [(pathlib.Path(p).parent.mkdir(parents=True,exist_ok=True),pathlib.Path(p).write_text(json.dumps(v))) for p,v in paths]';
|
|
645
|
+
await this.run(this.runtime, ['exec', '--user', '0', '--', state.containerId, 'python3', '-c', script]);
|
|
646
|
+
authorize();
|
|
647
|
+
});
|
|
648
|
+
}
|
|
649
|
+
async health(value, authorize) {
|
|
650
|
+
return JSON.parse((await this.execute(value, [CUA_DRIVER, 'call', 'health_report', '{}', '--socket', CUA_SOCKET], { authorize, lane: 'gui' })).stdout);
|
|
651
|
+
}
|
|
652
|
+
}
|