@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,1220 @@
|
|
|
1
|
+
import { chmodSync, mkdirSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
4
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
5
|
+
import { EventEmitter } from 'node:events';
|
|
6
|
+
import { messageAppendPatch } from '../shared/workspaceMessagePatch.js';
|
|
7
|
+
import { z } from 'zod';
|
|
8
|
+
import { HttpError } from './errors.js';
|
|
9
|
+
import { isVisibleMessageFile } from '../shared/messageFiles.js';
|
|
10
|
+
import { notificationPlainText } from './notificationText.js';
|
|
11
|
+
import { readHostTools } from './hostToolSettings.js';
|
|
12
|
+
import { supportsHostEnvironment, deriveComputer } from '../shared/workspace.js';
|
|
13
|
+
import { decodeAgentMascotAvatar, isAgentImageAvatar, defaultAgentIdentity, encodeAgentAvatar, normalizeAvatar, randomAgentIdentity, MAX_AVATAR_DESCRIPTOR_LENGTH } from '../shared/agentIdentity.js';
|
|
14
|
+
const name = z
|
|
15
|
+
.string()
|
|
16
|
+
.trim()
|
|
17
|
+
.min(1)
|
|
18
|
+
.max(100)
|
|
19
|
+
.refine((v) => !/[\u0000-\u001f@]/.test(v), '名称不能包含 @ 或控制字符');
|
|
20
|
+
const avatar = z
|
|
21
|
+
.string()
|
|
22
|
+
.max(MAX_AVATAR_DESCRIPTOR_LENGTH)
|
|
23
|
+
.refine((v) => !v || isAgentImageAvatar(v) || !!decodeAgentMascotAvatar(v) || /^builtin:team-animal:(fox|whale|owl|rabbit|bear)$/.test(v), '请选择有效的内置头像或 PNG、JPEG、WebP 图片');
|
|
24
|
+
const taskTitle = z.string().trim().min(1).max(100).refine((v) => !/[\u0000-\u001f]/.test(v), '标题不能包含控制字符');
|
|
25
|
+
const envsInput = z.object({ vm: z.boolean().optional(), cloud: z.boolean().optional(), desktop: z.boolean().optional(), browser: z.boolean().optional() }).strict();
|
|
26
|
+
const personaInput = {
|
|
27
|
+
job: z.string().trim().max(120).optional(),
|
|
28
|
+
antiJobs: z.array(z.string().trim().min(1).max(120)).max(8).optional(),
|
|
29
|
+
voice: z.enum(['concise', 'casual', 'rigorous', 'custom']).optional(),
|
|
30
|
+
voiceCustom: z.string().max(200).optional(),
|
|
31
|
+
actBias: z.enum(['ask_first', 'ask_key_then_act', 'act_now']).optional(),
|
|
32
|
+
};
|
|
33
|
+
const modelIdentifier = z.string().trim().min(1).max(512).refine(value => !/[\s"'\\\u0000-\u001f]/.test(value) && !value.startsWith('-'), '模型或 Provider 标识无效');
|
|
34
|
+
export const botModelSettingsInput = z.object({
|
|
35
|
+
provider: modelIdentifier.nullable(), model: modelIdentifier.nullable(),
|
|
36
|
+
reasoningEffort: z.enum(['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra']).nullable(),
|
|
37
|
+
fastMode: z.enum(['normal', 'fast', 'auto', 'cold']).nullable(),
|
|
38
|
+
}).strict().refine(value => (value.provider === null) === (value.model === null), '模型与 Provider 必须一起选择');
|
|
39
|
+
export const agentInput = z
|
|
40
|
+
.object({
|
|
41
|
+
name,
|
|
42
|
+
avatar: avatar.default(''),
|
|
43
|
+
instructions: z.string().max(24_000).default(''),
|
|
44
|
+
description: z.string().trim().max(500).default(''),
|
|
45
|
+
execution: z.enum(['profile', 'computer']).default('profile'),
|
|
46
|
+
computer: z.enum(['auto', 'cloud', 'vm', 'local', 'browser', 'off']).optional(),
|
|
47
|
+
envs: envsInput.optional(),
|
|
48
|
+
desktopHost: z.union([z.literal('local'), z.string().uuid(), z.null()]).optional(),
|
|
49
|
+
allowHostEnvironment: z.boolean().default(false),
|
|
50
|
+
vmExecution: z.enum(['worker', 'profile']).optional(),
|
|
51
|
+
browserProfile: z.enum(['persistent', 'temporary']).optional(),
|
|
52
|
+
canManageTeam: z.boolean().default(true),
|
|
53
|
+
canCollaborate: z.boolean().default(true),
|
|
54
|
+
memoryEnabled: z.boolean().default(true),
|
|
55
|
+
approvalPolicy: z.enum(['ask', 'allow', 'deny']).default('ask'),
|
|
56
|
+
...personaInput,
|
|
57
|
+
nodeId: z.string().default('local'),
|
|
58
|
+
profile: z.string().min(1).max(256),
|
|
59
|
+
})
|
|
60
|
+
.strict();
|
|
61
|
+
export const agentPatch = z
|
|
62
|
+
.object({
|
|
63
|
+
modelSettings: botModelSettingsInput.nullable().optional(),
|
|
64
|
+
expectedRevision: z.number().int().positive().optional(),
|
|
65
|
+
name: name.optional(),
|
|
66
|
+
avatar: avatar.optional(),
|
|
67
|
+
instructions: z.string().max(24_000).optional(),
|
|
68
|
+
description: z.string().trim().max(500).optional(),
|
|
69
|
+
execution: z.enum(['profile', 'computer']).optional(),
|
|
70
|
+
computer: z.enum(['auto', 'cloud', 'vm', 'local', 'browser', 'off']).optional(),
|
|
71
|
+
envs: envsInput.optional(),
|
|
72
|
+
desktopHost: z.union([z.literal('local'), z.string().uuid(), z.null()]).optional(),
|
|
73
|
+
allowHostEnvironment: z.boolean().optional(),
|
|
74
|
+
vmExecution: z.enum(['worker', 'profile']).optional(),
|
|
75
|
+
browserProfile: z.enum(['persistent', 'temporary']).optional(),
|
|
76
|
+
nodeId: z.string().min(1).max(256).optional(),
|
|
77
|
+
profile: z.string().min(1).max(256).optional(),
|
|
78
|
+
canManageTeam: z.boolean().optional(),
|
|
79
|
+
canCollaborate: z.boolean().optional(),
|
|
80
|
+
memoryEnabled: z.boolean().optional(),
|
|
81
|
+
approvalPolicy: z.enum(['ask', 'allow', 'deny']).optional(),
|
|
82
|
+
job: z.string().trim().max(120).nullable().optional(),
|
|
83
|
+
antiJobs: z.array(z.string().trim().min(1).max(120)).max(8).nullable().optional(),
|
|
84
|
+
voice: z.enum(['concise', 'casual', 'rigorous', 'custom']).nullable().optional(),
|
|
85
|
+
voiceCustom: z.string().max(200).nullable().optional(),
|
|
86
|
+
actBias: z.enum(['ask_first', 'ask_key_then_act', 'act_now']).nullable().optional(),
|
|
87
|
+
archived: z.boolean().optional(),
|
|
88
|
+
})
|
|
89
|
+
.strict();
|
|
90
|
+
const memberRoles = z.record(z.string().uuid(), z.object({
|
|
91
|
+
name: z.string().trim().min(1).max(100),
|
|
92
|
+
description: z.string().max(500),
|
|
93
|
+
}).strict()).refine(value => Object.keys(value).length <= 8, '最多 8 个群内角色');
|
|
94
|
+
export const groupInput = z
|
|
95
|
+
.object({
|
|
96
|
+
name,
|
|
97
|
+
avatar: avatar.default(''),
|
|
98
|
+
memberIds: z.array(z.string().uuid()).min(2).max(8),
|
|
99
|
+
memberRoles: memberRoles.default({}),
|
|
100
|
+
instructions: z.string().max(24_000).default(''),
|
|
101
|
+
administratorId: z.string().uuid().optional(),
|
|
102
|
+
collaborationMode: z.enum(['discussion', 'host', 'free']).optional(),
|
|
103
|
+
mode: z.enum(['host', 'free']).default('host'),
|
|
104
|
+
autoReplyIds: z.array(z.string().uuid()).max(8).default([]),
|
|
105
|
+
maxReplyRounds: z.union([z.literal(-1), z.number().int().min(1).max(100)]).default(3),
|
|
106
|
+
})
|
|
107
|
+
.strict();
|
|
108
|
+
export const conversationPatch = z
|
|
109
|
+
.object({
|
|
110
|
+
name: name.optional(),
|
|
111
|
+
avatar: avatar.optional(),
|
|
112
|
+
instructions: z.string().max(24_000).optional(),
|
|
113
|
+
memberIds: z.array(z.string().uuid()).min(1).max(8).optional(),
|
|
114
|
+
memberRoles: memberRoles.optional(),
|
|
115
|
+
administratorId: z.string().uuid().optional(),
|
|
116
|
+
collaborationMode: z.enum(['discussion', 'host', 'free']).optional(),
|
|
117
|
+
mode: z.enum(['host', 'free']).optional(),
|
|
118
|
+
autoReplyIds: z.array(z.string().uuid()).max(8).optional(),
|
|
119
|
+
maxReplyRounds: z.union([z.literal(-1), z.number().int().min(1).max(100)]).optional(),
|
|
120
|
+
archived: z.boolean().optional(),
|
|
121
|
+
pinned: z.boolean().optional(),
|
|
122
|
+
})
|
|
123
|
+
.strict();
|
|
124
|
+
export const taskInput = z
|
|
125
|
+
.object({ title: z.string().trim().max(100).refine((v) => !/[\u0000-\u001f]/.test(v), '标题不能包含控制字符').optional() })
|
|
126
|
+
.strict();
|
|
127
|
+
export const taskPatch = z
|
|
128
|
+
.object({ title: taskTitle })
|
|
129
|
+
.strict();
|
|
130
|
+
export function parse(schema, value) {
|
|
131
|
+
const parsed = schema.safeParse(value);
|
|
132
|
+
if (!parsed.success)
|
|
133
|
+
throw new HttpError(400, parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join('; '), 'invalid_workspace_request');
|
|
134
|
+
return parsed.data;
|
|
135
|
+
}
|
|
136
|
+
export class WorkspaceStore {
|
|
137
|
+
home;
|
|
138
|
+
messagePatchesEnabled;
|
|
139
|
+
summaryTimers = new Map();
|
|
140
|
+
scheduleSummary(owner, conversation) {
|
|
141
|
+
const key = `${owner}\0${conversation.id}`;
|
|
142
|
+
if (this.summaryTimers.has(key))
|
|
143
|
+
return;
|
|
144
|
+
const timer = setTimeout(() => {
|
|
145
|
+
this.summaryTimers.delete(key);
|
|
146
|
+
try {
|
|
147
|
+
const current = this.get(owner, 'conversation', conversation.id);
|
|
148
|
+
if (!current || current.archived)
|
|
149
|
+
return;
|
|
150
|
+
const latest = this.messages(owner, current.id, Number.MAX_SAFE_INTEGER, 1)[0];
|
|
151
|
+
if (!latest || !latest.content.trim())
|
|
152
|
+
return;
|
|
153
|
+
this.atomic(() => {
|
|
154
|
+
current.updatedAt = Date.now();
|
|
155
|
+
current.lastMessageAt = Math.max(current.lastMessageAt ?? 0, latest.createdAt);
|
|
156
|
+
current.preview = notificationPlainText(latest.content, { maximum: 160, fallback: '' });
|
|
157
|
+
current.previewAgentId = latest.role === 'assistant' ? latest.agentId : undefined;
|
|
158
|
+
this.put(owner, 'conversation', current.id, current);
|
|
159
|
+
this.event(owner, 'conversation.changed', current, current.id);
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
catch { /* The message is already durable; a later update can retry its list summary. */ }
|
|
163
|
+
}, Math.max(1, 250 - (Date.now() - conversation.updatedAt)));
|
|
164
|
+
timer.unref();
|
|
165
|
+
this.summaryTimers.set(key, timer);
|
|
166
|
+
}
|
|
167
|
+
wireEvents = new WeakMap();
|
|
168
|
+
wireEvent(event) { return this.wireEvents.get(event) ?? event; }
|
|
169
|
+
hasPatchEvents(owner, after, through) {
|
|
170
|
+
return !!this.db.prepare("SELECT 1 FROM workspace_events WHERE owner=? AND seq>? AND seq<=? AND type='message.patch' LIMIT 1").get(owner, after, through);
|
|
171
|
+
}
|
|
172
|
+
prepareAgent;
|
|
173
|
+
observers = new Set();
|
|
174
|
+
observe(listener) {
|
|
175
|
+
this.observers.add(listener);
|
|
176
|
+
return () => { this.observers.delete(listener); };
|
|
177
|
+
}
|
|
178
|
+
publish(owner, event) {
|
|
179
|
+
this.changes.emit(owner, event);
|
|
180
|
+
for (const listener of this.observers) {
|
|
181
|
+
try {
|
|
182
|
+
listener(owner, event);
|
|
183
|
+
}
|
|
184
|
+
catch { /* Observers cannot undo a committed transaction. */ }
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
db;
|
|
188
|
+
changes = new EventEmitter();
|
|
189
|
+
transactionEvents;
|
|
190
|
+
constructor(home, options = {}) {
|
|
191
|
+
this.home = home;
|
|
192
|
+
this.messagePatchesEnabled = options.messagePatches ?? process.env.HERMES_YAOYAO_WORKSPACE_MESSAGE_PATCHES !== '0';
|
|
193
|
+
mkdirSync(home, { recursive: true, mode: 0o700 });
|
|
194
|
+
const path = join(home, 'workspace.sqlite3');
|
|
195
|
+
this.db = new DatabaseSync(path);
|
|
196
|
+
chmodSync(path, 0o600);
|
|
197
|
+
this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000;
|
|
198
|
+
CREATE TABLE IF NOT EXISTS workspace_entities(owner TEXT NOT NULL,kind TEXT NOT NULL,id TEXT NOT NULL,data TEXT NOT NULL,PRIMARY KEY(owner,kind,id));
|
|
199
|
+
CREATE TABLE IF NOT EXISTS workspace_events(seq INTEGER PRIMARY KEY AUTOINCREMENT,owner TEXT NOT NULL,type TEXT NOT NULL,conversation_id TEXT,data TEXT NOT NULL);
|
|
200
|
+
CREATE INDEX IF NOT EXISTS workspace_events_owner ON workspace_events(owner,seq);
|
|
201
|
+
CREATE TABLE IF NOT EXISTS workspace_commands(owner TEXT NOT NULL,id TEXT NOT NULL,fingerprint TEXT NOT NULL,result TEXT NOT NULL,PRIMARY KEY(owner,id));`);
|
|
202
|
+
this.db.exec(`CREATE INDEX IF NOT EXISTS workspace_turn_run ON workspace_entities(owner, json_extract(data,'$.runId')) WHERE kind='turn';
|
|
203
|
+
CREATE INDEX IF NOT EXISTS workspace_turn_status ON workspace_entities(owner, json_extract(data,'$.status'), json_extract(data,'$.planned')) WHERE kind='turn';
|
|
204
|
+
CREATE INDEX IF NOT EXISTS workspace_turn_conversation ON workspace_entities(owner, json_extract(data,'$.conversationId')) WHERE kind='turn';
|
|
205
|
+
CREATE INDEX IF NOT EXISTS workspace_message_task ON workspace_entities(owner, json_extract(data,'$.conversationTaskId'), json_extract(data,'$.seq')) WHERE kind='message';
|
|
206
|
+
CREATE INDEX IF NOT EXISTS workspace_message_conversation ON workspace_entities(owner, json_extract(data,'$.conversationId'), json_extract(data,'$.seq')) WHERE kind='message';
|
|
207
|
+
CREATE INDEX IF NOT EXISTS workspace_message_hidden ON workspace_entities(owner, json_extract(data,'$.conversationId'), json_extract(data,'$.conversationTaskId'), json_extract(data,'$.seq')) WHERE kind='message' AND json_extract(data,'$.visible')=0;
|
|
208
|
+
CREATE INDEX IF NOT EXISTS workspace_task_unread ON workspace_entities(owner, json_extract(data,'$.conversationId'), json_extract(data,'$.unread')) WHERE kind='conversation-task';
|
|
209
|
+
CREATE INDEX IF NOT EXISTS workspace_run_task ON workspace_entities(owner, json_extract(data,'$.conversationTaskId'), json_extract(data,'$.status')) WHERE kind='run';
|
|
210
|
+
CREATE INDEX IF NOT EXISTS workspace_turn_task ON workspace_entities(owner, json_extract(data,'$.conversationTaskId'), json_extract(data,'$.status')) WHERE kind='turn';`);
|
|
211
|
+
this.db.exec('CREATE TABLE IF NOT EXISTS server_identity(singleton INTEGER PRIMARY KEY CHECK(singleton=1), server_id TEXT NOT NULL, name TEXT NOT NULL, revision INTEGER NOT NULL)');
|
|
212
|
+
this.db.prepare('INSERT OR IGNORE INTO server_identity VALUES(1, ?, ?, 0)').run(randomUUID(), '');
|
|
213
|
+
this.changes.setMaxListeners(0);
|
|
214
|
+
this.atomic(() => {
|
|
215
|
+
this.db.exec('CREATE TABLE IF NOT EXISTS workspace_migrations(id TEXT PRIMARY KEY)');
|
|
216
|
+
if (this.db.prepare('SELECT id FROM workspace_migrations WHERE id=?').get('avatar-v2'))
|
|
217
|
+
return;
|
|
218
|
+
for (const owner of this.owners()) {
|
|
219
|
+
for (const agent of this.list(owner, 'agent')) {
|
|
220
|
+
this.put(owner, 'agent', agent.id, { ...agent, avatar: normalizeAvatar(agent.avatar) });
|
|
221
|
+
}
|
|
222
|
+
for (const conversation of this.list(owner, 'conversation')) {
|
|
223
|
+
if (conversation.kind !== 'direct')
|
|
224
|
+
continue;
|
|
225
|
+
const agent = this.get(owner, 'agent', conversation.memberIds[0] || '');
|
|
226
|
+
this.put(owner, 'conversation', conversation.id, { ...conversation, avatar: agent?.avatar ?? normalizeAvatar(conversation.avatar) });
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
this.db.prepare('INSERT INTO workspace_migrations VALUES(?)').run('avatar-v2');
|
|
230
|
+
});
|
|
231
|
+
this.atomic(() => {
|
|
232
|
+
if (this.db.prepare('SELECT id FROM workspace_migrations WHERE id=?').get('avatar-random-default-v1'))
|
|
233
|
+
return;
|
|
234
|
+
for (const owner of this.owners()) {
|
|
235
|
+
for (const agent of this.list(owner, 'agent')) {
|
|
236
|
+
const identity = decodeAgentMascotAvatar(agent.avatar);
|
|
237
|
+
const isSystemDefault = identity && !identity.imageDataURL && identity.shape === 'circle'
|
|
238
|
+
&& identity.color === '#00c875' && identity.expression === 'idle' && !identity.bodyId;
|
|
239
|
+
if (!isSystemDefault)
|
|
240
|
+
continue;
|
|
241
|
+
const avatar = encodeAgentAvatar(randomAgentIdentity(agent.id, agent.name));
|
|
242
|
+
this.put(owner, 'agent', agent.id, { ...agent, avatar });
|
|
243
|
+
for (const conversation of this.list(owner, 'conversation')) {
|
|
244
|
+
if (conversation.kind === 'direct' && conversation.memberIds[0] === agent.id) {
|
|
245
|
+
this.put(owner, 'conversation', conversation.id, { ...conversation, avatar });
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
this.db.prepare('INSERT INTO workspace_migrations VALUES(?)').run('avatar-random-default-v1');
|
|
251
|
+
});
|
|
252
|
+
this.atomic(() => {
|
|
253
|
+
const migration = 'conversation-task-history-v1';
|
|
254
|
+
if (this.db.prepare('SELECT id FROM workspace_migrations WHERE id=?').get(migration))
|
|
255
|
+
return;
|
|
256
|
+
for (const owner of this.owners()) {
|
|
257
|
+
for (const conversation of this.list(owner, 'conversation')) {
|
|
258
|
+
if (conversation.kind === 'group')
|
|
259
|
+
this.backfillConversationTask(owner, conversation);
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
this.db.prepare('INSERT INTO workspace_migrations VALUES(?)').run(migration);
|
|
263
|
+
});
|
|
264
|
+
this.atomic(() => {
|
|
265
|
+
const migration = 'workspace-unread-flag-v1';
|
|
266
|
+
if (this.db.prepare('SELECT id FROM workspace_migrations WHERE id=?').get(migration))
|
|
267
|
+
return;
|
|
268
|
+
for (const owner of this.owners()) {
|
|
269
|
+
for (const task of this.list(owner, 'conversation-task')) {
|
|
270
|
+
task.unread ??= task.unreadCount > 0;
|
|
271
|
+
task.unreadVersion ??= task.unread ? 1 : 0;
|
|
272
|
+
task.unreadCount = task.unread ? 1 : 0;
|
|
273
|
+
this.put(owner, 'conversation-task', task.id, task);
|
|
274
|
+
}
|
|
275
|
+
for (const conversation of this.list(owner, 'conversation')) {
|
|
276
|
+
conversation.unread ??= conversation.kind === 'group'
|
|
277
|
+
? this.hasUnreadTask(owner, conversation.id)
|
|
278
|
+
: !!this.db.prepare("SELECT 1 FROM workspace_entities WHERE owner=? AND kind='message' AND json_extract(data,'$.conversationId')=? AND json_extract(data,'$.seq')>? AND coalesce(json_extract(data,'$.visible'),1)!=0 LIMIT 1").get(owner, conversation.id, conversation.readSeq);
|
|
279
|
+
conversation.unreadVersion ??= conversation.unread ? 1 : 0;
|
|
280
|
+
conversation.unreadCount = conversation.unread ? 1 : 0;
|
|
281
|
+
this.put(owner, 'conversation', conversation.id, conversation);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
this.db.prepare('INSERT INTO workspace_migrations VALUES(?)').run(migration);
|
|
285
|
+
});
|
|
286
|
+
this.atomic(() => {
|
|
287
|
+
const migration = 'host-environment-option-v1';
|
|
288
|
+
if (this.db.prepare('SELECT id FROM workspace_migrations WHERE id=?').get(migration))
|
|
289
|
+
return;
|
|
290
|
+
for (const row of this.db.prepare("SELECT owner,id,data FROM workspace_entities WHERE kind='agent' AND json_extract(data,'$.computer')='hybrid'").all()) {
|
|
291
|
+
const agent = JSON.parse(String(row.data));
|
|
292
|
+
this.put(String(row.owner), 'agent', String(row.id), { ...agent, computer: 'vm', execution: 'computer', allowHostEnvironment: !agent.temporaryGoalId && !agent.remoteAgentId, revision: (agent.revision ?? 0) + 1 });
|
|
293
|
+
}
|
|
294
|
+
this.db.prepare('INSERT INTO workspace_migrations VALUES(?)').run(migration);
|
|
295
|
+
});
|
|
296
|
+
}
|
|
297
|
+
hasUnreadTask(owner, conversationId) {
|
|
298
|
+
return !!this.db.prepare("SELECT 1 FROM workspace_entities WHERE owner=? AND kind='conversation-task' AND json_extract(data,'$.conversationId')=? AND json_extract(data,'$.unread')=1 LIMIT 1").get(owner, conversationId);
|
|
299
|
+
}
|
|
300
|
+
get(owner, kind, id) {
|
|
301
|
+
const row = this.db
|
|
302
|
+
.prepare('SELECT data FROM workspace_entities WHERE owner=? AND kind=? AND id=?')
|
|
303
|
+
.get(owner, kind, id);
|
|
304
|
+
return row ? JSON.parse(String(row.data)) : undefined;
|
|
305
|
+
}
|
|
306
|
+
require(owner, kind, id) {
|
|
307
|
+
const value = this.get(owner, kind, id);
|
|
308
|
+
if (!value)
|
|
309
|
+
throw new HttpError(404, '记录不存在', 'workspace_not_found');
|
|
310
|
+
return value;
|
|
311
|
+
}
|
|
312
|
+
list(owner, kind) {
|
|
313
|
+
return this.db
|
|
314
|
+
.prepare('SELECT data FROM workspace_entities WHERE owner=? AND kind=?')
|
|
315
|
+
.all(owner, kind)
|
|
316
|
+
.map((r) => JSON.parse(String(r.data)));
|
|
317
|
+
}
|
|
318
|
+
owners() {
|
|
319
|
+
return this.db
|
|
320
|
+
.prepare('SELECT DISTINCT owner FROM workspace_entities')
|
|
321
|
+
.all()
|
|
322
|
+
.map((r) => String(r.owner));
|
|
323
|
+
}
|
|
324
|
+
put(owner, kind, id, value) {
|
|
325
|
+
this.db
|
|
326
|
+
.prepare('INSERT INTO workspace_entities VALUES(?,?,?,?) ON CONFLICT(owner,kind,id) DO UPDATE SET data=excluded.data')
|
|
327
|
+
.run(owner, kind, id, JSON.stringify(value));
|
|
328
|
+
}
|
|
329
|
+
remove(owner, kind, id) {
|
|
330
|
+
this.db
|
|
331
|
+
.prepare('DELETE FROM workspace_entities WHERE owner=? AND kind=? AND id=?')
|
|
332
|
+
.run(owner, kind, id);
|
|
333
|
+
}
|
|
334
|
+
atomic(fn) {
|
|
335
|
+
if (this.transactionEvents)
|
|
336
|
+
return fn();
|
|
337
|
+
this.db.exec('BEGIN IMMEDIATE');
|
|
338
|
+
this.transactionEvents = [];
|
|
339
|
+
try {
|
|
340
|
+
const result = fn();
|
|
341
|
+
this.db.exec('COMMIT');
|
|
342
|
+
const events = this.transactionEvents;
|
|
343
|
+
this.transactionEvents = undefined;
|
|
344
|
+
for (const entry of events)
|
|
345
|
+
this.publish(entry.owner, entry.event);
|
|
346
|
+
return result;
|
|
347
|
+
}
|
|
348
|
+
catch (error) {
|
|
349
|
+
this.db.exec('ROLLBACK');
|
|
350
|
+
this.transactionEvents = undefined;
|
|
351
|
+
throw error;
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
event(owner, type, data, conversationId, projection) {
|
|
355
|
+
const seq = Number(this.db
|
|
356
|
+
.prepare('INSERT INTO workspace_events(owner,type,conversation_id,data) VALUES(?,?,?,?)')
|
|
357
|
+
.run(owner, type, conversationId ?? null, JSON.stringify(data)).lastInsertRowid);
|
|
358
|
+
const wire = { seq, type, conversationId, data: this.eventDataForDisplay(owner, type, data) };
|
|
359
|
+
const event = projection ? { seq, conversationId, type: projection.type, data: this.eventDataForDisplay(owner, projection.type, projection.data) } : wire;
|
|
360
|
+
if (projection)
|
|
361
|
+
this.wireEvents.set(event, wire);
|
|
362
|
+
if (this.transactionEvents)
|
|
363
|
+
this.transactionEvents.push({ owner, event });
|
|
364
|
+
else
|
|
365
|
+
this.publish(owner, event);
|
|
366
|
+
return seq;
|
|
367
|
+
}
|
|
368
|
+
events(owner, after) {
|
|
369
|
+
return this.db
|
|
370
|
+
.prepare('SELECT * FROM workspace_events WHERE owner=? AND seq>? ORDER BY seq LIMIT 250')
|
|
371
|
+
.all(owner, after)
|
|
372
|
+
.map((r) => ({
|
|
373
|
+
seq: Number(r.seq),
|
|
374
|
+
type: String(r.type),
|
|
375
|
+
conversationId: r.conversation_id ? String(r.conversation_id) : undefined,
|
|
376
|
+
data: this.eventDataForDisplay(owner, String(r.type), JSON.parse(String(r.data))),
|
|
377
|
+
}));
|
|
378
|
+
}
|
|
379
|
+
cursor(owner) {
|
|
380
|
+
return Number(this.db
|
|
381
|
+
.prepare('SELECT coalesce(max(seq),0) AS n FROM workspace_events WHERE owner=?')
|
|
382
|
+
.get(owner).n);
|
|
383
|
+
}
|
|
384
|
+
command(owner, id, payload, fn) {
|
|
385
|
+
parse(z.string().uuid(), id);
|
|
386
|
+
const fingerprint = createHash('sha256').update(JSON.stringify(payload)).digest('hex');
|
|
387
|
+
return this.atomic(() => {
|
|
388
|
+
const old = this.db
|
|
389
|
+
.prepare('SELECT fingerprint,result FROM workspace_commands WHERE owner=? AND id=?')
|
|
390
|
+
.get(owner, id);
|
|
391
|
+
if (old) {
|
|
392
|
+
if (old.fingerprint !== fingerprint)
|
|
393
|
+
throw new HttpError(409, '请求编号已用于其他内容', 'idempotency_conflict');
|
|
394
|
+
return JSON.parse(String(old.result));
|
|
395
|
+
}
|
|
396
|
+
const result = fn();
|
|
397
|
+
this.db
|
|
398
|
+
.prepare('INSERT INTO workspace_commands VALUES(?,?,?,?)')
|
|
399
|
+
.run(owner, id, fingerprint, JSON.stringify(result));
|
|
400
|
+
return result;
|
|
401
|
+
});
|
|
402
|
+
}
|
|
403
|
+
taskMemberIds(owner, conversation, taskId) {
|
|
404
|
+
const base = conversation.memberIds.filter(id => !this.get(owner, 'agent', id)?.temporaryGoalId);
|
|
405
|
+
if (!taskId)
|
|
406
|
+
return base;
|
|
407
|
+
const goal = this.get(owner, 'goal', taskId);
|
|
408
|
+
if (!goal || goal.conversationId !== conversation.id || ['complete', 'blocked', 'cancelled', 'cancelling'].includes(goal.status))
|
|
409
|
+
return base;
|
|
410
|
+
return [...new Set([...base, ...this.list(owner, 'agent').filter(agent => !agent.archived && agent.temporaryGoalId === taskId && agent.helperActivation === (goal.activation ?? 1)).map(agent => agent.id)])];
|
|
411
|
+
}
|
|
412
|
+
requireAgentTask(owner, agent, conversationId, taskId) {
|
|
413
|
+
if (!agent.temporaryGoalId)
|
|
414
|
+
return;
|
|
415
|
+
const conversation = this.require(owner, 'conversation', conversationId);
|
|
416
|
+
if (agent.temporaryGoalId !== taskId || !this.taskMemberIds(owner, conversation, taskId).includes(agent.id))
|
|
417
|
+
throw new HttpError(403, '临时助手只能执行所属任务', 'helper_task_bound');
|
|
418
|
+
}
|
|
419
|
+
createAgent(owner, input, origin, allocatedId = randomUUID()) {
|
|
420
|
+
const body = parse(agentInput, input);
|
|
421
|
+
// Legacy per-Bot permissions cannot override the shared policy.
|
|
422
|
+
body.approvalPolicy = readHostTools(this.home).approvalPolicy;
|
|
423
|
+
body.canManageTeam = true;
|
|
424
|
+
body.canCollaborate = true;
|
|
425
|
+
if (!supportsHostEnvironment(body) || origin)
|
|
426
|
+
body.allowHostEnvironment = false;
|
|
427
|
+
if (body.computer !== 'vm' || origin)
|
|
428
|
+
body.vmExecution = 'worker';
|
|
429
|
+
if (body.vmExecution === 'profile')
|
|
430
|
+
body.allowHostEnvironment = true;
|
|
431
|
+
if (origin?.createdByAgentId)
|
|
432
|
+
this.require(owner, 'agent', origin.createdByAgentId);
|
|
433
|
+
return this.atomic(() => {
|
|
434
|
+
if (this.list(owner, 'agent').some((a) => a.name.toLocaleLowerCase() === body.name.toLocaleLowerCase()))
|
|
435
|
+
throw new HttpError(409, '机器人名称已存在', 'duplicate_agent_name');
|
|
436
|
+
const now = Date.now(), id = allocatedId;
|
|
437
|
+
const agent = {
|
|
438
|
+
...body,
|
|
439
|
+
...origin,
|
|
440
|
+
avatar: body.avatar ? normalizeAvatar(body.avatar) : encodeAgentAvatar(randomAgentIdentity(id, body.name)),
|
|
441
|
+
id,
|
|
442
|
+
archived: false,
|
|
443
|
+
revision: 1,
|
|
444
|
+
teamAuthorizationVersion: body.canManageTeam ? 1 : 0,
|
|
445
|
+
createdAt: now,
|
|
446
|
+
updatedAt: now,
|
|
447
|
+
};
|
|
448
|
+
this.prepareAgent?.(owner, agent);
|
|
449
|
+
this.put(owner, 'agent', id, agent);
|
|
450
|
+
if (origin?.temporaryGoalId) {
|
|
451
|
+
this.event(owner, 'agent.changed', agent);
|
|
452
|
+
return agent;
|
|
453
|
+
}
|
|
454
|
+
const conversation = {
|
|
455
|
+
id: randomUUID(),
|
|
456
|
+
kind: 'direct',
|
|
457
|
+
name: agent.name,
|
|
458
|
+
avatar: agent.avatar,
|
|
459
|
+
memberIds: [id],
|
|
460
|
+
instructions: '',
|
|
461
|
+
administratorId: id,
|
|
462
|
+
mode: 'host',
|
|
463
|
+
autoReplyIds: [],
|
|
464
|
+
maxReplyRounds: 1,
|
|
465
|
+
archived: false,
|
|
466
|
+
pinned: false,
|
|
467
|
+
readSeq: 0,
|
|
468
|
+
unread: false,
|
|
469
|
+
unreadVersion: 0,
|
|
470
|
+
lastSeq: 0,
|
|
471
|
+
preview: '',
|
|
472
|
+
createdAt: now,
|
|
473
|
+
updatedAt: now,
|
|
474
|
+
};
|
|
475
|
+
this.put(owner, 'conversation', conversation.id, conversation);
|
|
476
|
+
this.event(owner, 'agent.changed', agent);
|
|
477
|
+
this.event(owner, 'conversation.changed', conversation, conversation.id);
|
|
478
|
+
return agent;
|
|
479
|
+
});
|
|
480
|
+
}
|
|
481
|
+
updateAgent(owner, id, input) {
|
|
482
|
+
// Persona fields use null from clients to clear; normalizing with an
|
|
483
|
+
// always-present key keeps the clear semantics when spreading over the record.
|
|
484
|
+
const { job, antiJobs, voice, voiceCustom, actBias, expectedRevision, ...rest } = parse(agentPatch, input);
|
|
485
|
+
const patch = rest;
|
|
486
|
+
// Only materialize keys the request actually carried; null clears the field.
|
|
487
|
+
if (job !== undefined)
|
|
488
|
+
patch.job = job ?? undefined;
|
|
489
|
+
if (antiJobs !== undefined)
|
|
490
|
+
patch.antiJobs = antiJobs ?? undefined;
|
|
491
|
+
if (voice !== undefined)
|
|
492
|
+
patch.voice = voice ?? undefined;
|
|
493
|
+
if (voiceCustom !== undefined)
|
|
494
|
+
patch.voiceCustom = voiceCustom ?? undefined;
|
|
495
|
+
if (actBias !== undefined)
|
|
496
|
+
patch.actBias = actBias ?? undefined;
|
|
497
|
+
delete patch.approvalPolicy;
|
|
498
|
+
delete patch.canManageTeam;
|
|
499
|
+
delete patch.canCollaborate;
|
|
500
|
+
if (!Object.keys(patch).length)
|
|
501
|
+
return this.require(owner, 'agent', id);
|
|
502
|
+
if (patch.avatar !== undefined)
|
|
503
|
+
patch.avatar = normalizeAvatar(patch.avatar);
|
|
504
|
+
if (patch.desktopHost === null)
|
|
505
|
+
patch.desktopHost = undefined;
|
|
506
|
+
if (patch.computer === 'browser')
|
|
507
|
+
patch.computer = 'off';
|
|
508
|
+
return this.atomic(() => {
|
|
509
|
+
const agent = this.require(owner, 'agent', id);
|
|
510
|
+
if (expectedRevision !== undefined && agent.revision !== expectedRevision)
|
|
511
|
+
throw new HttpError(409, 'Bot 资料已在其他地方更新,请重新加载后保存。', 'agent_revision_conflict');
|
|
512
|
+
// Parallel-environment agents keep their set; a raw computer write only
|
|
513
|
+
// toggles the VM leg (local-vm enable/disable and Compose bindings).
|
|
514
|
+
if (patch.computer !== undefined && agent.envs) {
|
|
515
|
+
const envs = { ...agent.envs };
|
|
516
|
+
if (patch.computer === 'vm')
|
|
517
|
+
envs.vm = true;
|
|
518
|
+
else if (patch.computer === 'off' || patch.computer === 'auto')
|
|
519
|
+
envs.vm = false;
|
|
520
|
+
patch.envs = envs;
|
|
521
|
+
}
|
|
522
|
+
if (patch.envs) {
|
|
523
|
+
patch.envs = { ...patch.envs, browser: false };
|
|
524
|
+
patch.computer = deriveComputer({ vm: patch.envs.vm === true, cloud: patch.envs.cloud === true, desktop: patch.envs.desktop === true, browser: false });
|
|
525
|
+
patch.execution = 'profile';
|
|
526
|
+
}
|
|
527
|
+
const desktopHostChanged = patch.desktopHost !== undefined && patch.desktopHost !== (agent.desktopHost ?? null);
|
|
528
|
+
if (patch.vmExecution === 'profile' && patch.allowHostEnvironment === false)
|
|
529
|
+
throw new HttpError(400, '本机协作模式需要本机环境,请选择虚拟机模式', 'computer_profile_host_required');
|
|
530
|
+
if (agent.vmExecution === 'profile') {
|
|
531
|
+
if (patch.allowHostEnvironment === false && patch.vmExecution === undefined)
|
|
532
|
+
patch.vmExecution = 'worker';
|
|
533
|
+
if (patch.vmExecution === 'worker' && patch.allowHostEnvironment === undefined)
|
|
534
|
+
patch.allowHostEnvironment = false;
|
|
535
|
+
}
|
|
536
|
+
if ((patch.computer ?? agent.computer) !== 'vm' && (patch.vmExecution !== undefined || agent.vmExecution === 'profile'))
|
|
537
|
+
patch.vmExecution = 'worker';
|
|
538
|
+
if ((patch.vmExecution ?? agent.vmExecution) === 'profile' && (patch.computer ?? agent.computer) === 'vm')
|
|
539
|
+
patch.allowHostEnvironment = true;
|
|
540
|
+
if (!supportsHostEnvironment({ ...agent, ...patch }) && (agent.allowHostEnvironment === true || patch.allowHostEnvironment !== undefined))
|
|
541
|
+
patch.allowHostEnvironment = false;
|
|
542
|
+
const sourceChanged = (patch.nodeId !== undefined && patch.nodeId !== agent.nodeId) || (patch.profile !== undefined && patch.profile !== agent.profile);
|
|
543
|
+
const hostPermissionChanged = patch.allowHostEnvironment !== undefined && patch.allowHostEnvironment !== (agent.allowHostEnvironment === true);
|
|
544
|
+
const destinationChanged = desktopHostChanged || hostPermissionChanged || (patch.vmExecution !== undefined && patch.vmExecution !== (agent.vmExecution ?? 'worker')) || (patch.computer !== undefined && patch.computer !== agent.computer) || (patch.browserProfile !== undefined && patch.browserProfile !== (agent.browserProfile ?? 'persistent'));
|
|
545
|
+
if (sourceChanged || destinationChanged) {
|
|
546
|
+
if (this.list(owner, 'turn').some(work => work.agentId === id && ['queued', 'running', 'waiting', 'uncertain', 'cancelling'].includes(work.status)))
|
|
547
|
+
throw new HttpError(409, '请先停止当前任务,再修改机器人来源或电脑', 'agent_execution_busy');
|
|
548
|
+
if (this.list('_system', 'computer-control').some(grant => grant.owner === owner && grant.expiresAt > Date.now() && (grant.agentId === id || grant.environmentId === (agent.computerEnvironmentId ?? id))))
|
|
549
|
+
throw new HttpError(409, '请先交还电脑控制权', 'agent_execution_busy');
|
|
550
|
+
if (sourceChanged && agent.computerEnvironmentId) {
|
|
551
|
+
const shared = this.require(owner, 'shared-computer', agent.computerEnvironmentId);
|
|
552
|
+
if ((patch.nodeId ?? agent.nodeId) !== shared.nodeId || (!shared.managedLocalVm && !shared.managedCompose && shared.profile !== '*' && (patch.profile ?? agent.profile) !== shared.profile))
|
|
553
|
+
throw new HttpError(409, '请先解除电脑共享,再切换到其他来源', 'shared_computer_active');
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
if (agent.temporaryGoalId && (Object.keys(patch).some(key => key !== 'archived') || patch.archived === false))
|
|
557
|
+
throw new HttpError(409, '临时助手由所属任务管理,不能修改权限或恢复为持久成员', 'helper_task_bound');
|
|
558
|
+
if (agent.computerEnvironmentId && patch.execution === 'profile' && (patch.envs?.vm ?? agent.envs?.vm) !== true)
|
|
559
|
+
throw new HttpError(409, '请先解除电脑共享,再切换执行环境', 'shared_computer_active');
|
|
560
|
+
if (patch.execution && patch.execution !== (agent.execution ?? 'profile') && this.list(owner, 'turn').some(work => work.agentId === id && ['running', 'waiting', 'uncertain'].includes(work.status)))
|
|
561
|
+
throw new HttpError(409, '请先停止当前任务,再切换执行环境', 'agent_execution_busy');
|
|
562
|
+
if (agent.remoteAgentId && Object.keys(patch).some(key => key !== 'archived' && key !== 'approvalPolicy'))
|
|
563
|
+
throw new HttpError(409, '引用机器人的配置由远端管理', 'remote_agent_read_only');
|
|
564
|
+
if (patch.name &&
|
|
565
|
+
this.list(owner, 'agent').some((a) => a.id !== id && a.name.toLocaleLowerCase() === patch.name.toLocaleLowerCase()))
|
|
566
|
+
throw new HttpError(409, '机器人名称已存在', 'duplicate_agent_name');
|
|
567
|
+
const next = { ...agent, ...patch, revision: agent.revision + 1, updatedAt: Date.now() };
|
|
568
|
+
if (patch.archived !== undefined && patch.archived !== agent.archived)
|
|
569
|
+
next.teamAuthorizationVersion = (agent.teamAuthorizationVersion ?? 0) + 1;
|
|
570
|
+
if (patch.archived === true)
|
|
571
|
+
this.detachAgentComputer(owner, next);
|
|
572
|
+
this.put(owner, 'agent', id, next);
|
|
573
|
+
if (sourceChanged)
|
|
574
|
+
for (const binding of this.list(owner, 'binding').filter(binding => binding.id.endsWith(`:${id}`))) {
|
|
575
|
+
this.put(owner, 'binding-reset', binding.id, { id: binding.id });
|
|
576
|
+
this.remove(owner, 'binding', binding.id);
|
|
577
|
+
}
|
|
578
|
+
this.event(owner, 'agent.changed', next);
|
|
579
|
+
for (const c of this.list(owner, 'conversation').filter((c) => c.kind === 'direct' && c.memberIds[0] === id)) {
|
|
580
|
+
Object.assign(c, { name: next.name, avatar: next.avatar, archived: next.archived });
|
|
581
|
+
this.put(owner, 'conversation', c.id, c);
|
|
582
|
+
this.event(owner, 'conversation.changed', c, c.id);
|
|
583
|
+
}
|
|
584
|
+
return next;
|
|
585
|
+
});
|
|
586
|
+
}
|
|
587
|
+
conversationLifecycle(owner, id) {
|
|
588
|
+
const conversation = this.require(owner, 'conversation', id);
|
|
589
|
+
const agent = conversation.kind === 'direct' ? this.require(owner, 'agent', conversation.memberIds[0]) : undefined;
|
|
590
|
+
const groups = agent ? this.list(owner, 'conversation')
|
|
591
|
+
.filter(group => group.kind === 'group' && group.memberIds.includes(agent.id))
|
|
592
|
+
.sort((a, b) => a.id.localeCompare(b.id)) : [];
|
|
593
|
+
return {
|
|
594
|
+
name: conversation.name,
|
|
595
|
+
kind: conversation.kind,
|
|
596
|
+
groups: groups.map(group => ({ id: group.id, name: group.name, administrator: group.administratorId === agent?.id })),
|
|
597
|
+
confirmationToken: createHash('sha256').update(JSON.stringify([
|
|
598
|
+
conversation.id, conversation.name, conversation.archived, agent?.revision,
|
|
599
|
+
groups.map(group => [group.id, group.name, group.administratorId, group.memberIds]),
|
|
600
|
+
])).digest('hex'),
|
|
601
|
+
};
|
|
602
|
+
}
|
|
603
|
+
requireConversationIdle(owner, id) {
|
|
604
|
+
if (['run', 'turn'].some(kind => this.list(owner, kind).some(run => run.conversationId === id && !['complete', 'failed', 'interrupted', 'skipped'].includes(run.status))))
|
|
605
|
+
throw new HttpError(409, '聊天仍有任务未结束,请停止任务后重试', 'conversation_running');
|
|
606
|
+
if (this.list(owner, 'goal').some(goal => (goal.conversationId === id || goal.origin?.conversationId === id) && !['complete', 'blocked', 'cancelled'].includes(goal.status)))
|
|
607
|
+
throw new HttpError(409, '聊天仍有关联任务未结束,请停止任务后重试', 'conversation_running');
|
|
608
|
+
}
|
|
609
|
+
changeConversationLifecycle(owner, id, action, confirmationToken) {
|
|
610
|
+
this.atomic(() => {
|
|
611
|
+
const conversation = this.require(owner, 'conversation', id);
|
|
612
|
+
const agent = conversation.kind === 'direct' ? this.require(owner, 'agent', conversation.memberIds[0]) : undefined;
|
|
613
|
+
if (action === 'restore') {
|
|
614
|
+
if (agent)
|
|
615
|
+
this.updateAgent(owner, agent.id, { archived: false });
|
|
616
|
+
else
|
|
617
|
+
this.updateConversation(owner, id, { archived: false });
|
|
618
|
+
return;
|
|
619
|
+
}
|
|
620
|
+
const preview = this.conversationLifecycle(owner, id);
|
|
621
|
+
const managed = preview.groups.filter(group => group.administrator);
|
|
622
|
+
if (managed.length)
|
|
623
|
+
throw new HttpError(409, `此 Bot 是群聊${managed.map(group => `「${group.name}」`).join('、')}的管理者,请先转交管理权,再归档或删除`, 'agent_group_administrator');
|
|
624
|
+
if (confirmationToken !== undefined && confirmationToken !== preview.confirmationToken)
|
|
625
|
+
throw new HttpError(409, '聊天或群聊成员已变化,请重新确认后操作', 'lifecycle_confirmation_stale');
|
|
626
|
+
if (preview.groups.length && !confirmationToken)
|
|
627
|
+
throw new HttpError(409, '此 Bot 仍是群聊成员,请确认退出群聊后再归档或删除', 'agent_in_group');
|
|
628
|
+
if (agent?.temporaryGoalId)
|
|
629
|
+
throw new HttpError(409, '临时助手由所属任务管理', 'helper_task_bound');
|
|
630
|
+
if (agent && this.list(owner, 'turn').some(turn => turn.agentId === agent.id && !['complete', 'failed', 'interrupted', 'skipped'].includes(turn.status)))
|
|
631
|
+
throw new HttpError(409, 'Bot 仍有任务未结束,请停止任务后重试', 'agent_running');
|
|
632
|
+
for (const conversationId of [id, ...preview.groups.map(group => group.id)])
|
|
633
|
+
this.requireConversationIdle(owner, conversationId);
|
|
634
|
+
for (const group of preview.groups) {
|
|
635
|
+
const current = this.require(owner, 'conversation', group.id);
|
|
636
|
+
this.updateConversation(owner, group.id, { memberIds: current.memberIds.filter(memberId => memberId !== agent.id) });
|
|
637
|
+
}
|
|
638
|
+
if (agent) {
|
|
639
|
+
this.updateAgent(owner, agent.id, { archived: true });
|
|
640
|
+
if (action === 'delete')
|
|
641
|
+
this.deleteAgent(owner, agent.id);
|
|
642
|
+
}
|
|
643
|
+
else {
|
|
644
|
+
this.updateConversation(owner, id, { archived: true });
|
|
645
|
+
if (action === 'delete')
|
|
646
|
+
this.deleteConversation(owner, id);
|
|
647
|
+
}
|
|
648
|
+
});
|
|
649
|
+
}
|
|
650
|
+
detachAgentComputer(owner, agent) {
|
|
651
|
+
const environmentId = agent.computerEnvironmentId;
|
|
652
|
+
if (!environmentId)
|
|
653
|
+
return;
|
|
654
|
+
if (this.list(owner, 'turn').some(work => work.agentId === agent.id && !['complete', 'failed', 'interrupted', 'skipped'].includes(work.status)))
|
|
655
|
+
throw new HttpError(409, 'Bot 仍有任务未结束,请停止任务后重试', 'agent_running');
|
|
656
|
+
if (this.list('_system', 'computer-control').some(grant => grant.owner === owner && grant.expiresAt > Date.now() && (grant.agentId === agent.id || grant.environmentId === environmentId)))
|
|
657
|
+
throw new HttpError(409, '请先交还电脑控制权,再归档或删除 Bot', 'agent_execution_busy');
|
|
658
|
+
// Revoke only this membership; the desktop and other members keep their data.
|
|
659
|
+
const shared = this.get(owner, 'shared-computer', environmentId);
|
|
660
|
+
if (shared) {
|
|
661
|
+
shared.memberIds = shared.memberIds.filter(id => id !== agent.id);
|
|
662
|
+
if (!shared.memberIds.length)
|
|
663
|
+
shared.archived = true;
|
|
664
|
+
this.put(owner, 'shared-computer', shared.id, shared);
|
|
665
|
+
}
|
|
666
|
+
delete agent.computerEnvironmentId;
|
|
667
|
+
delete agent.computerEnvironmentName;
|
|
668
|
+
}
|
|
669
|
+
deleteAgent(owner, id) {
|
|
670
|
+
this.atomic(() => {
|
|
671
|
+
const agent = this.require(owner, 'agent', id);
|
|
672
|
+
if (!agent.archived)
|
|
673
|
+
throw new HttpError(409, '请先归档 Bot,再删除', 'agent_not_archived');
|
|
674
|
+
if (agent.temporaryGoalId)
|
|
675
|
+
throw new HttpError(409, '临时助手由所属任务管理', 'helper_task_bound');
|
|
676
|
+
const conversations = this.list(owner, 'conversation');
|
|
677
|
+
if (conversations.some(c => c.kind === 'group' && c.memberIds.includes(id)))
|
|
678
|
+
throw new HttpError(409, '此 Bot 仍是群聊成员,请先从群聊移除或删除相关群聊', 'agent_in_group');
|
|
679
|
+
if (this.list(owner, 'turn').some(work => work.agentId === id && !['complete', 'failed', 'interrupted', 'skipped'].includes(work.status)))
|
|
680
|
+
throw new HttpError(409, 'Bot 仍有任务未结束,请停止任务后重试', 'agent_running');
|
|
681
|
+
this.detachAgentComputer(owner, agent);
|
|
682
|
+
for (const conversation of conversations.filter(c => c.kind === 'direct' && c.memberIds[0] === id))
|
|
683
|
+
this.deleteConversation(owner, conversation.id, true);
|
|
684
|
+
for (const kind of ['routine', 'routine-run'])
|
|
685
|
+
for (const item of this.list(owner, kind).filter(item => item.agentId === id))
|
|
686
|
+
this.remove(owner, kind, item.id);
|
|
687
|
+
for (const plugin of this.list(owner, 'bot-mcp-plugin')) {
|
|
688
|
+
if (!plugin.agentIds.includes(id))
|
|
689
|
+
continue;
|
|
690
|
+
this.put(owner, 'bot-mcp-plugin', plugin.id, { ...plugin, agentIds: plugin.agentIds.filter(agentId => agentId !== id), revision: plugin.revision + 1 });
|
|
691
|
+
}
|
|
692
|
+
this.remove(owner, 'agent', id);
|
|
693
|
+
this.event(owner, 'agent.deleted', { id });
|
|
694
|
+
});
|
|
695
|
+
}
|
|
696
|
+
deleteConversation(owner, id, deletingAgent = false) {
|
|
697
|
+
this.atomic(() => {
|
|
698
|
+
const conversation = this.require(owner, 'conversation', id);
|
|
699
|
+
if (conversation.kind === 'direct' && !deletingAgent)
|
|
700
|
+
throw new HttpError(400, '请删除对应的 Bot', 'delete_agent_instead');
|
|
701
|
+
if (!conversation.archived)
|
|
702
|
+
throw new HttpError(409, '请先归档聊天,再删除', 'conversation_not_archived');
|
|
703
|
+
this.requireConversationIdle(owner, id);
|
|
704
|
+
const taskIds = new Set(this.list(owner, 'conversation-task').filter(task => task.conversationId === id).map(task => task.id));
|
|
705
|
+
for (const taskId of taskIds) {
|
|
706
|
+
this.remove(owner, 'context', taskId);
|
|
707
|
+
this.db.prepare("DELETE FROM workspace_entities WHERE owner=? AND kind='task-delivery' AND json_extract(data,'$.goalId')=?").run(owner, taskId);
|
|
708
|
+
}
|
|
709
|
+
// Keep files in the file library, matching task deletion; detach their chat references.
|
|
710
|
+
for (const file of this.list(owner, 'file')) {
|
|
711
|
+
if (file.conversationId === id || (file.conversationTaskId && taskIds.has(file.conversationTaskId)))
|
|
712
|
+
this.put(owner, 'file', file.id, { ...file, conversationId: undefined, conversationTaskId: undefined, messageId: undefined });
|
|
713
|
+
}
|
|
714
|
+
const bindingPrefix = `${id}:`;
|
|
715
|
+
this.db.prepare("DELETE FROM workspace_entities WHERE owner=? AND ((kind='binding' AND substr(id,1,?)=?) OR (kind='interaction-binding' AND substr(json_extract(data,'$.key'),1,?)=?))").run(owner, bindingPrefix.length, bindingPrefix, bindingPrefix.length, bindingPrefix);
|
|
716
|
+
this.db.prepare("DELETE FROM workspace_entities WHERE owner=? AND kind IN ('message','run','turn','interaction','interaction-binding','binding','conversation-task','goal','assignment') AND json_extract(data,'$.conversationId')=?").run(owner, id);
|
|
717
|
+
this.db.prepare("DELETE FROM workspace_commands WHERE owner=? AND json_extract(result,'$.conversationId')=?").run(owner, id);
|
|
718
|
+
this.remove(owner, 'context', id);
|
|
719
|
+
if (this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='workspace_inspector'").get())
|
|
720
|
+
this.db.prepare('DELETE FROM workspace_inspector WHERE owner=? AND conversation_id=?').run(owner, id);
|
|
721
|
+
this.remove(owner, 'conversation', id);
|
|
722
|
+
this.event(owner, 'conversation.deleted', { id }, id);
|
|
723
|
+
});
|
|
724
|
+
}
|
|
725
|
+
createGroup(owner, input) {
|
|
726
|
+
const parsed = parse(groupInput, input);
|
|
727
|
+
const body = { ...parsed, administratorId: parsed.administratorId ?? parsed.memberIds[0] };
|
|
728
|
+
if (body.collaborationMode)
|
|
729
|
+
body.mode = body.collaborationMode === 'host' ? 'host' : 'free';
|
|
730
|
+
const ids = new Set(body.memberIds);
|
|
731
|
+
if (ids.size !== body.memberIds.length ||
|
|
732
|
+
!ids.has(body.administratorId) ||
|
|
733
|
+
body.autoReplyIds.some((id) => !ids.has(id)) ||
|
|
734
|
+
Object.keys(body.memberRoles).some(id => !ids.has(id)))
|
|
735
|
+
throw new HttpError(400, '群成员或管理员无效', 'invalid_members');
|
|
736
|
+
for (const id of ids) {
|
|
737
|
+
const agent = this.require(owner, 'agent', id);
|
|
738
|
+
if (agent.temporaryGoalId)
|
|
739
|
+
throw new HttpError(409, '临时助手不能加入持久团队', 'helper_task_bound');
|
|
740
|
+
if (agent.archived)
|
|
741
|
+
throw new HttpError(409, '已归档机器人不能加入新群', 'agent_archived');
|
|
742
|
+
}
|
|
743
|
+
const now = Date.now();
|
|
744
|
+
const c = {
|
|
745
|
+
...body,
|
|
746
|
+
id: randomUUID(),
|
|
747
|
+
kind: 'group',
|
|
748
|
+
archived: false,
|
|
749
|
+
pinned: false,
|
|
750
|
+
readSeq: 0,
|
|
751
|
+
unread: false,
|
|
752
|
+
unreadVersion: 0,
|
|
753
|
+
lastSeq: 0,
|
|
754
|
+
preview: '',
|
|
755
|
+
createdAt: now,
|
|
756
|
+
updatedAt: now,
|
|
757
|
+
};
|
|
758
|
+
this.atomic(() => {
|
|
759
|
+
this.put(owner, 'conversation', c.id, c);
|
|
760
|
+
this.event(owner, 'conversation.changed', c, c.id);
|
|
761
|
+
this.createTask(owner, c.id, {});
|
|
762
|
+
});
|
|
763
|
+
return c;
|
|
764
|
+
}
|
|
765
|
+
backfillConversationTask(owner, conversation) {
|
|
766
|
+
const legacyMessages = this.list(owner, 'message')
|
|
767
|
+
.filter(message => message.conversationId === conversation.id && !message.conversationTaskId)
|
|
768
|
+
.sort((a, b) => a.seq - b.seq || a.createdAt - b.createdAt || a.id.localeCompare(b.id));
|
|
769
|
+
if (!legacyMessages.length)
|
|
770
|
+
return;
|
|
771
|
+
const existingTasks = this.tasks(owner, conversation.id);
|
|
772
|
+
const assignedTaskIds = new Set(this.list(owner, 'message')
|
|
773
|
+
.filter(message => message.conversationId === conversation.id && message.conversationTaskId)
|
|
774
|
+
.map(message => message.conversationTaskId));
|
|
775
|
+
const reusable = existingTasks.length === 1
|
|
776
|
+
&& existingTasks[0].titleSource === 'automatic'
|
|
777
|
+
&& existingTasks[0].title === '新任务'
|
|
778
|
+
&& existingTasks[0].messageCount === 0
|
|
779
|
+
&& !assignedTaskIds.has(existingTasks[0].id)
|
|
780
|
+
? existingTasks[0]
|
|
781
|
+
: undefined;
|
|
782
|
+
const visibleMessages = legacyMessages.filter(message => message.visible !== false);
|
|
783
|
+
const meaningfulMessages = visibleMessages.filter(message => message.content.trim() || message.attachments.length);
|
|
784
|
+
const firstMessage = legacyMessages[0], lastMessage = meaningfulMessages.at(-1) ?? visibleMessages.at(-1) ?? legacyMessages.at(-1), firstUserMessage = visibleMessages.find(message => message.role === 'user' && (message.content.trim() || message.attachments.length)), title = notificationPlainText(firstUserMessage?.content ?? '', {
|
|
785
|
+
maximum: 48,
|
|
786
|
+
fallback: firstUserMessage?.attachments[0]?.name ?? '',
|
|
787
|
+
}).trim()
|
|
788
|
+
|| notificationPlainText(conversation.preview, { maximum: 48, fallback: '' }).trim()
|
|
789
|
+
|| '历史任务', lastSeq = legacyMessages.reduce((value, message) => Math.max(value, message.seq), 0), readSeq = Math.min(conversation.readSeq, lastSeq), task = {
|
|
790
|
+
...(reusable ?? {
|
|
791
|
+
id: randomUUID(),
|
|
792
|
+
conversationId: conversation.id,
|
|
793
|
+
title: '历史任务',
|
|
794
|
+
titleSource: 'automatic',
|
|
795
|
+
messageCount: 0,
|
|
796
|
+
readSeq: 0,
|
|
797
|
+
lastSeq: 0,
|
|
798
|
+
unreadCount: 0,
|
|
799
|
+
createdAt: firstMessage.createdAt,
|
|
800
|
+
updatedAt: lastMessage.createdAt,
|
|
801
|
+
}),
|
|
802
|
+
title,
|
|
803
|
+
titleSource: 'automatic',
|
|
804
|
+
messageCount: visibleMessages.length,
|
|
805
|
+
readSeq,
|
|
806
|
+
lastSeq,
|
|
807
|
+
unreadCount: visibleMessages.some(message => message.seq > readSeq) ? 1 : 0,
|
|
808
|
+
lastMessageAt: lastMessage.createdAt,
|
|
809
|
+
createdAt: firstMessage.createdAt,
|
|
810
|
+
updatedAt: lastMessage.createdAt,
|
|
811
|
+
};
|
|
812
|
+
for (const message of legacyMessages) {
|
|
813
|
+
this.put(owner, 'message', message.id, {
|
|
814
|
+
...message,
|
|
815
|
+
conversationTaskId: task.id,
|
|
816
|
+
});
|
|
817
|
+
}
|
|
818
|
+
const migratedInteractions = new Map();
|
|
819
|
+
for (const kind of ['run', 'turn', 'interaction']) {
|
|
820
|
+
for (const entity of this.list(owner, kind)) {
|
|
821
|
+
if (entity.conversationId !== conversation.id || entity.conversationTaskId)
|
|
822
|
+
continue;
|
|
823
|
+
this.put(owner, kind, entity.id, { ...entity, conversationTaskId: task.id });
|
|
824
|
+
if (kind === 'interaction' && entity.agentId) {
|
|
825
|
+
migratedInteractions.set(entity.id, entity.agentId);
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
for (const [interactionId, agentId] of migratedInteractions) {
|
|
830
|
+
const binding = this.get(owner, 'interaction-binding', interactionId);
|
|
831
|
+
if (!binding || binding.conversationTaskId)
|
|
832
|
+
continue;
|
|
833
|
+
this.put(owner, 'interaction-binding', interactionId, {
|
|
834
|
+
...binding,
|
|
835
|
+
key: `${conversation.id}:${task.id}:${agentId}`,
|
|
836
|
+
conversationTaskId: task.id,
|
|
837
|
+
});
|
|
838
|
+
}
|
|
839
|
+
for (const agentId of conversation.memberIds) {
|
|
840
|
+
const legacyKey = `${conversation.id}:${agentId}`, taskKey = `${conversation.id}:${task.id}:${agentId}`, binding = this.get(owner, 'binding', legacyKey);
|
|
841
|
+
if (!binding || binding.conversationTaskId)
|
|
842
|
+
continue;
|
|
843
|
+
this.put(owner, 'binding', taskKey, { ...binding, conversationTaskId: task.id });
|
|
844
|
+
this.remove(owner, 'binding', legacyKey);
|
|
845
|
+
}
|
|
846
|
+
const context = this.get(owner, 'context', conversation.id);
|
|
847
|
+
if (context && !context.conversationTaskId) {
|
|
848
|
+
this.put(owner, 'context', task.id, { ...context, conversationTaskId: task.id });
|
|
849
|
+
this.remove(owner, 'context', conversation.id);
|
|
850
|
+
}
|
|
851
|
+
this.db.prepare(`UPDATE workspace_commands
|
|
852
|
+
SET result=json_set(result,'$.conversationTaskId',?)
|
|
853
|
+
WHERE owner=? AND json_extract(result,'$.conversationId')=?
|
|
854
|
+
AND json_extract(result,'$.conversationTaskId') IS NULL`).run(task.id, owner, conversation.id);
|
|
855
|
+
const activeRuns = this.list(owner, 'run')
|
|
856
|
+
.filter(run => run.conversationTaskId === task.id && !['complete', 'failed', 'interrupted'].includes(run.status))
|
|
857
|
+
.sort((a, b) => a.createdAt - b.createdAt || a.id.localeCompare(b.id));
|
|
858
|
+
task.activeRunId = activeRuns[0]?.id;
|
|
859
|
+
task.activeRunStatus = activeRuns[0]?.status;
|
|
860
|
+
this.put(owner, 'conversation-task', task.id, task);
|
|
861
|
+
}
|
|
862
|
+
tasks(owner, conversationId) {
|
|
863
|
+
const conversation = this.require(owner, 'conversation', conversationId);
|
|
864
|
+
if (conversation.kind !== 'group')
|
|
865
|
+
throw new HttpError(400, '单聊不支持任务', 'conversation_tasks_unsupported');
|
|
866
|
+
return this.list(owner, 'conversation-task')
|
|
867
|
+
.filter((task) => task.conversationId === conversationId)
|
|
868
|
+
.sort((a, b) => b.updatedAt - a.updatedAt || b.createdAt - a.createdAt || a.id.localeCompare(b.id));
|
|
869
|
+
}
|
|
870
|
+
createTask(owner, conversationId, input) {
|
|
871
|
+
const body = parse(taskInput, input), conversation = this.require(owner, 'conversation', conversationId);
|
|
872
|
+
if (conversation.kind !== 'group')
|
|
873
|
+
throw new HttpError(400, '单聊不支持任务', 'conversation_tasks_unsupported');
|
|
874
|
+
const now = Date.now(), explicitTitle = body.title?.trim(), task = {
|
|
875
|
+
id: randomUUID(),
|
|
876
|
+
conversationId,
|
|
877
|
+
title: explicitTitle || '新任务',
|
|
878
|
+
titleSource: explicitTitle ? 'user' : 'automatic',
|
|
879
|
+
messageCount: 0,
|
|
880
|
+
readSeq: 0,
|
|
881
|
+
lastSeq: 0,
|
|
882
|
+
unread: false,
|
|
883
|
+
unreadVersion: 0,
|
|
884
|
+
unreadCount: 0,
|
|
885
|
+
createdAt: now,
|
|
886
|
+
updatedAt: now,
|
|
887
|
+
};
|
|
888
|
+
this.atomic(() => {
|
|
889
|
+
this.put(owner, 'conversation-task', task.id, task);
|
|
890
|
+
this.event(owner, 'task.changed', task, conversationId);
|
|
891
|
+
});
|
|
892
|
+
return task;
|
|
893
|
+
}
|
|
894
|
+
requireTask(owner, conversationId, taskId) {
|
|
895
|
+
const task = this.require(owner, 'conversation-task', taskId);
|
|
896
|
+
if (task.conversationId !== conversationId)
|
|
897
|
+
throw new HttpError(404, '任务不存在', 'workspace_task_not_found');
|
|
898
|
+
return task;
|
|
899
|
+
}
|
|
900
|
+
resolveTask(owner, conversationId, taskId) {
|
|
901
|
+
const conversation = this.require(owner, 'conversation', conversationId);
|
|
902
|
+
if (conversation.kind === 'direct') {
|
|
903
|
+
if (taskId)
|
|
904
|
+
throw new HttpError(400, '单聊不支持任务', 'conversation_tasks_unsupported');
|
|
905
|
+
return undefined;
|
|
906
|
+
}
|
|
907
|
+
if (taskId)
|
|
908
|
+
return this.requireTask(owner, conversationId, taskId);
|
|
909
|
+
return this.tasks(owner, conversationId)[0] ?? this.createTask(owner, conversationId, {});
|
|
910
|
+
}
|
|
911
|
+
updateTask(owner, conversationId, taskId, input) {
|
|
912
|
+
const patch = parse(taskPatch, input);
|
|
913
|
+
return this.atomic(() => {
|
|
914
|
+
const task = this.requireTask(owner, conversationId, taskId), next = { ...task, title: patch.title, titleSource: 'user', updatedAt: Date.now() };
|
|
915
|
+
this.put(owner, 'conversation-task', task.id, next);
|
|
916
|
+
this.event(owner, 'task.changed', next, conversationId);
|
|
917
|
+
return next;
|
|
918
|
+
});
|
|
919
|
+
}
|
|
920
|
+
markTaskRead(owner, conversationId, taskId, seq, unreadVersion) {
|
|
921
|
+
return this.atomic(() => {
|
|
922
|
+
const task = this.requireTask(owner, conversationId, taskId);
|
|
923
|
+
task.readSeq = Math.max(task.readSeq, Math.min(seq, task.lastSeq));
|
|
924
|
+
if (unreadVersion === undefined ? seq >= task.lastSeq : unreadVersion === (task.unreadVersion ?? 0))
|
|
925
|
+
task.unread = false;
|
|
926
|
+
task.unreadCount = task.unread ? 1 : 0;
|
|
927
|
+
this.put(owner, 'conversation-task', task.id, task);
|
|
928
|
+
const conversation = this.require(owner, 'conversation', conversationId);
|
|
929
|
+
conversation.unread = this.hasUnreadTask(owner, conversationId);
|
|
930
|
+
conversation.unreadCount = conversation.unread ? 1 : 0;
|
|
931
|
+
this.put(owner, 'conversation', conversationId, conversation);
|
|
932
|
+
this.event(owner, 'task.changed', task, conversationId);
|
|
933
|
+
this.event(owner, 'conversation.changed', conversation, conversationId);
|
|
934
|
+
return task;
|
|
935
|
+
});
|
|
936
|
+
}
|
|
937
|
+
markConversationRead(owner, conversationId, seq, unreadVersion) {
|
|
938
|
+
return this.atomic(() => {
|
|
939
|
+
const conversation = this.require(owner, 'conversation', conversationId);
|
|
940
|
+
conversation.readSeq = Math.max(conversation.readSeq, Math.min(seq, conversation.lastSeq));
|
|
941
|
+
if (conversation.kind === 'direct' && (unreadVersion === undefined ? seq >= conversation.lastSeq : unreadVersion === (conversation.unreadVersion ?? 0)))
|
|
942
|
+
conversation.unread = false;
|
|
943
|
+
conversation.unreadCount = conversation.unread ? 1 : 0;
|
|
944
|
+
this.put(owner, 'conversation', conversationId, conversation);
|
|
945
|
+
this.event(owner, 'conversation.changed', conversation, conversationId);
|
|
946
|
+
return this.conversationSummary(owner, conversation);
|
|
947
|
+
});
|
|
948
|
+
}
|
|
949
|
+
deleteTask(owner, conversationId, taskId) {
|
|
950
|
+
this.atomic(() => {
|
|
951
|
+
const task = this.requireTask(owner, conversationId, taskId);
|
|
952
|
+
if (this.list(owner, 'run').some(run => run.conversationTaskId === taskId && !['complete', 'failed', 'interrupted'].includes(run.status)))
|
|
953
|
+
throw new HttpError(409, '任务仍在运行,暂时无法移除', 'workspace_task_running');
|
|
954
|
+
const messageIds = new Set(this.list(owner, 'message').filter(message => message.conversationTaskId === taskId).map(message => message.id));
|
|
955
|
+
this.db.prepare("DELETE FROM workspace_entities WHERE owner=? AND kind IN ('message','run','turn','interaction','interaction-binding','binding') AND json_extract(data,'$.conversationTaskId')=?").run(owner, taskId);
|
|
956
|
+
this.remove(owner, 'context', taskId);
|
|
957
|
+
this.remove(owner, 'conversation-task', taskId);
|
|
958
|
+
this.db.prepare("DELETE FROM workspace_commands WHERE owner=? AND json_extract(result,'$.conversationTaskId')=?").run(owner, taskId);
|
|
959
|
+
for (const file of this.list(owner, 'file')) {
|
|
960
|
+
if (!file.messageId || !messageIds.has(file.messageId))
|
|
961
|
+
continue;
|
|
962
|
+
this.put(owner, 'file', String(file.id), { ...file, conversationId: undefined, messageId: undefined });
|
|
963
|
+
}
|
|
964
|
+
this.event(owner, 'task.deleted', { id: taskId, conversationId }, conversationId);
|
|
965
|
+
const remaining = this.tasks(owner, conversationId);
|
|
966
|
+
if (!remaining.length)
|
|
967
|
+
this.createTask(owner, conversationId, {});
|
|
968
|
+
const conversation = this.require(owner, 'conversation', conversationId), history = this.messages(owner, conversationId, Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER);
|
|
969
|
+
const last = history.at(-1);
|
|
970
|
+
conversation.preview = last ? notificationPlainText(last.content, { maximum: 160, fallback: '' }) : '';
|
|
971
|
+
conversation.previewAgentId = last?.role === 'assistant' ? last.agentId : undefined;
|
|
972
|
+
conversation.lastMessageAt = last?.createdAt;
|
|
973
|
+
conversation.updatedAt = Date.now();
|
|
974
|
+
conversation.unread = this.hasUnreadTask(owner, conversationId);
|
|
975
|
+
conversation.unreadCount = conversation.unread ? 1 : 0;
|
|
976
|
+
this.projectConversationRuns(owner, conversation);
|
|
977
|
+
this.put(owner, 'conversation', conversationId, conversation);
|
|
978
|
+
this.event(owner, 'conversation.changed', conversation, conversationId);
|
|
979
|
+
});
|
|
980
|
+
}
|
|
981
|
+
updateConversation(owner, id, input) {
|
|
982
|
+
const patch = parse(conversationPatch, input), c = this.require(owner, 'conversation', id);
|
|
983
|
+
if (c.kind === 'direct' && Object.keys(patch).some((k) => k !== 'pinned'))
|
|
984
|
+
throw new HttpError(400, '请编辑机器人资料', 'edit_agent_instead');
|
|
985
|
+
if (patch.collaborationMode !== undefined && patch.collaborationMode !== c.collaborationMode) {
|
|
986
|
+
this.requireConversationIdle(owner, id);
|
|
987
|
+
patch.mode = patch.collaborationMode === 'host' ? 'host' : 'free';
|
|
988
|
+
}
|
|
989
|
+
else if (patch.mode !== undefined && patch.mode !== c.mode && c.collaborationMode)
|
|
990
|
+
patch.collaborationMode = patch.mode;
|
|
991
|
+
const memberIds = patch.memberIds ?? c.memberIds;
|
|
992
|
+
const members = new Set(memberIds);
|
|
993
|
+
const discussion = (patch.collaborationMode ?? c.collaborationMode) === 'discussion';
|
|
994
|
+
if (discussion && !members.has(patch.administratorId ?? c.administratorId))
|
|
995
|
+
patch.administratorId = memberIds[0];
|
|
996
|
+
if (!discussion && !members.has(c.administratorId))
|
|
997
|
+
throw new HttpError(400, '当前管理员不能移除,请先更换管理员并保存', 'administrator_required');
|
|
998
|
+
if (members.size !== memberIds.length ||
|
|
999
|
+
!members.has(patch.administratorId ?? c.administratorId) ||
|
|
1000
|
+
patch.autoReplyIds?.some((a) => !members.has(a) && !c.memberIds.includes(a)) ||
|
|
1001
|
+
Object.keys(patch.memberRoles ?? {}).some(a => !members.has(a) && !c.memberIds.includes(a)))
|
|
1002
|
+
throw new HttpError(400, '群成员或管理员无效', 'invalid_members');
|
|
1003
|
+
for (const memberId of memberIds) {
|
|
1004
|
+
const agent = this.require(owner, 'agent', memberId);
|
|
1005
|
+
if (agent.temporaryGoalId)
|
|
1006
|
+
throw new HttpError(409, '临时助手不能加入其他群聊', 'helper_task_bound');
|
|
1007
|
+
if (!c.memberIds.includes(memberId) && agent.archived)
|
|
1008
|
+
throw new HttpError(409, '已归档机器人不能加入群聊', 'agent_archived');
|
|
1009
|
+
}
|
|
1010
|
+
const next = {
|
|
1011
|
+
...c, ...patch, memberIds,
|
|
1012
|
+
autoReplyIds: (patch.autoReplyIds ?? c.autoReplyIds).filter(a => members.has(a)),
|
|
1013
|
+
memberRoles: Object.fromEntries(Object.entries(patch.memberRoles ?? c.memberRoles ?? {}).filter(([id]) => members.has(id))),
|
|
1014
|
+
updatedAt: Date.now(),
|
|
1015
|
+
};
|
|
1016
|
+
this.atomic(() => {
|
|
1017
|
+
this.put(owner, 'conversation', id, next);
|
|
1018
|
+
this.event(owner, 'conversation.changed', next, id);
|
|
1019
|
+
});
|
|
1020
|
+
return next;
|
|
1021
|
+
}
|
|
1022
|
+
messages(owner, conversationId, before = Number.MAX_SAFE_INTEGER, limit = 100, includeHidden = false, conversationTaskId) {
|
|
1023
|
+
this.require(owner, 'conversation', conversationId);
|
|
1024
|
+
if (conversationTaskId)
|
|
1025
|
+
this.requireTask(owner, conversationId, conversationTaskId);
|
|
1026
|
+
const taskClause = conversationTaskId ? "AND json_extract(data,'$.conversationTaskId')=?" : '';
|
|
1027
|
+
return this.db
|
|
1028
|
+
.prepare(`SELECT data FROM workspace_entities WHERE owner=? AND kind='message' AND json_extract(data,'$.conversationId')=? ${taskClause} AND json_extract(data,'$.seq')<? ${includeHidden ? '' : "AND coalesce(json_extract(data,'$.visible'),1) != 0"} ORDER BY json_extract(data,'$.seq') DESC LIMIT ?`)
|
|
1029
|
+
.all(...(conversationTaskId ? [owner, conversationId, conversationTaskId, before, limit] : [owner, conversationId, before, limit]))
|
|
1030
|
+
.map((r) => this.messageForDisplay(owner, JSON.parse(String(r.data))))
|
|
1031
|
+
.reverse();
|
|
1032
|
+
}
|
|
1033
|
+
nativeMessageForFile;
|
|
1034
|
+
visibleFiles(owner) {
|
|
1035
|
+
const messages = new Map(this.list(owner, 'message').map(message => [message.id, message]));
|
|
1036
|
+
return this.list(owner, 'file').filter(file => isVisibleMessageFile(file, messages.get(file.messageId ?? '') ?? this.nativeMessageForFile?.(owner, file)));
|
|
1037
|
+
}
|
|
1038
|
+
messageForDisplay(owner, message) {
|
|
1039
|
+
const peer = message.peerMessageId && message.role === 'system'
|
|
1040
|
+
? this.get(owner, 'peer-message', message.peerMessageId) : undefined;
|
|
1041
|
+
const incoming = !!peer && !!message.runId && message.conversationId === peer.conversationId && message.conversationTaskId === peer.taskId;
|
|
1042
|
+
const outgoing = !!peer && !message.runId && message.conversationId === peer.originConversationId && message.conversationTaskId === peer.originTaskId;
|
|
1043
|
+
if (peer && (incoming || outgoing)) {
|
|
1044
|
+
const peerId = incoming ? peer.fromAgentId : peer.toAgentId ?? peer.targetGroupId;
|
|
1045
|
+
const peerKind = outgoing && peer.targetGroupId ? 'group' : 'agent';
|
|
1046
|
+
const entity = peerKind === 'group' ? this.get(owner, 'conversation', peerId) : this.get(owner, 'agent', peerId);
|
|
1047
|
+
const peerName = entity?.name || (incoming ? peer.fromName ?? message.agentName : peer.targetName) || (peerKind === 'group' ? '群聊' : 'Bot');
|
|
1048
|
+
const peerAvatar = entity?.avatar || (incoming ? peer.fromAvatar : peer.targetAvatar) || '';
|
|
1049
|
+
const files = peer.fileIds.flatMap(id => {
|
|
1050
|
+
const file = this.get(owner, 'file', id) ?? message.attachments.find(file => file.id === id);
|
|
1051
|
+
return file ? [{ id: file.id, name: file.name, mimeType: file.mimeType, size: file.size, sender: file.sender, createdAt: file.createdAt }] : [];
|
|
1052
|
+
});
|
|
1053
|
+
return { ...message, reasoning: '', tools: [], attachments: message.visible === false ? [] : files,
|
|
1054
|
+
communication: { direction: incoming ? 'incoming' : 'outgoing', peerId, peerName, peerAvatar, peerKind, content: peer.content } };
|
|
1055
|
+
}
|
|
1056
|
+
const attachments = message.role === 'user' || message.role === 'assistant'
|
|
1057
|
+
? message.attachments.filter(file => isVisibleMessageFile(this.get(owner, 'file', file.id) ?? file, message))
|
|
1058
|
+
: [];
|
|
1059
|
+
return { ...message, attachments };
|
|
1060
|
+
}
|
|
1061
|
+
eventDataForDisplay(owner, type, data) {
|
|
1062
|
+
if (type === 'message.changed')
|
|
1063
|
+
return this.messageForDisplay(owner, data);
|
|
1064
|
+
return data;
|
|
1065
|
+
}
|
|
1066
|
+
saveMessage(owner, message) {
|
|
1067
|
+
this.atomic(() => {
|
|
1068
|
+
const c = this.require(owner, 'conversation', message.conversationId);
|
|
1069
|
+
const previous = this.get(owner, 'message', message.id);
|
|
1070
|
+
// Do not emit revisions for gateway events which did not change the message.
|
|
1071
|
+
if (previous?.status === 'streaming' && message.status === 'streaming' && JSON.stringify({ ...previous, revision: undefined }) === JSON.stringify({ ...message, revision: undefined }))
|
|
1072
|
+
return;
|
|
1073
|
+
message.revision = (previous?.revision ?? 0) + 1;
|
|
1074
|
+
const patch = this.messagePatchesEnabled ? messageAppendPatch(previous, message) : undefined;
|
|
1075
|
+
const updateSummary = !patch || Date.now() - c.updatedAt >= 250;
|
|
1076
|
+
if (previous && previous.conversationTaskId !== message.conversationTaskId)
|
|
1077
|
+
throw new HttpError(409, '消息不能移入其他任务', 'message_task_mismatch');
|
|
1078
|
+
const task = c.kind === 'group'
|
|
1079
|
+
? message.conversationTaskId
|
|
1080
|
+
? this.requireTask(owner, c.id, message.conversationTaskId)
|
|
1081
|
+
: (() => { throw new HttpError(400, '群聊消息必须指定任务', 'workspace_task_required'); })()
|
|
1082
|
+
: undefined;
|
|
1083
|
+
if (previous?.visible === false && message.visible !== false)
|
|
1084
|
+
message.seq = 0;
|
|
1085
|
+
if (!message.seq)
|
|
1086
|
+
message.seq = c.lastSeq + 1;
|
|
1087
|
+
c.lastSeq = Math.max(c.lastSeq, message.seq);
|
|
1088
|
+
const needsAttention = (value) => !!value && value.role !== 'user' && value.visible !== false
|
|
1089
|
+
&& ['complete', 'failed', 'interrupted'].includes(value.status)
|
|
1090
|
+
&& !!(value.content.trim() || value.error || value.browserCard || value.serviceWarnings?.length || this.messageForDisplay(owner, value).attachments.length);
|
|
1091
|
+
if (needsAttention(message) && !needsAttention(previous)) {
|
|
1092
|
+
c.unread = true;
|
|
1093
|
+
c.unreadVersion = (c.unreadVersion ?? 0) + 1;
|
|
1094
|
+
if (task) {
|
|
1095
|
+
task.unread = true;
|
|
1096
|
+
task.unreadVersion = (task.unreadVersion ?? 0) + 1;
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
c.unreadCount = c.unread ? 1 : 0;
|
|
1100
|
+
if (updateSummary && message.visible !== false && (message.content.trim() || message.attachments.length || message.browserCard && !previous?.browserCard || message.serviceWarnings?.length && !previous?.serviceWarnings?.length)) {
|
|
1101
|
+
c.updatedAt = Date.now();
|
|
1102
|
+
c.lastMessageAt = Math.max(c.lastMessageAt ?? 0, message.createdAt);
|
|
1103
|
+
c.preview = notificationPlainText(message.content, { maximum: 160, fallback: message.browserCard?.title || (message.browserCard ? '托管浏览器' : message.serviceWarnings?.length ? '部分服务暂时不可用' : '') });
|
|
1104
|
+
c.previewAgentId = message.role === 'assistant' ? message.agentId : undefined;
|
|
1105
|
+
}
|
|
1106
|
+
this.put(owner, 'message', message.id, message);
|
|
1107
|
+
if (updateSummary)
|
|
1108
|
+
this.put(owner, 'conversation', c.id, c);
|
|
1109
|
+
if (task && updateSummary) {
|
|
1110
|
+
const becameVisible = message.visible !== false && (!previous || previous.visible === false), becameHidden = Boolean(previous && previous.visible !== false && message.visible === false);
|
|
1111
|
+
if (becameVisible)
|
|
1112
|
+
task.messageCount += 1;
|
|
1113
|
+
if (becameHidden)
|
|
1114
|
+
task.messageCount = Math.max(0, task.messageCount - 1);
|
|
1115
|
+
task.lastSeq = Math.max(task.lastSeq, message.seq);
|
|
1116
|
+
task.unreadCount = task.unread ? 1 : 0;
|
|
1117
|
+
if (message.visible !== false && (message.content.trim() || message.attachments.length || message.browserCard && !previous?.browserCard || message.serviceWarnings?.length && !previous?.serviceWarnings?.length)) {
|
|
1118
|
+
if (message.role === 'user' && task.titleSource === 'automatic' && task.messageCount <= 1) {
|
|
1119
|
+
const source = notificationPlainText(message.content, { maximum: 48, fallback: message.attachments[0]?.name ?? '' }).trim();
|
|
1120
|
+
if (source)
|
|
1121
|
+
task.title = source;
|
|
1122
|
+
}
|
|
1123
|
+
task.lastMessageAt = Math.max(task.lastMessageAt ?? 0, message.createdAt);
|
|
1124
|
+
task.updatedAt = Date.now();
|
|
1125
|
+
}
|
|
1126
|
+
this.put(owner, 'conversation-task', task.id, task);
|
|
1127
|
+
this.event(owner, 'task.changed', task, c.id);
|
|
1128
|
+
}
|
|
1129
|
+
if (patch)
|
|
1130
|
+
this.event(owner, 'message.patch', patch, c.id, { type: 'message.changed', data: message });
|
|
1131
|
+
else
|
|
1132
|
+
this.event(owner, 'message.changed', message, c.id);
|
|
1133
|
+
if (updateSummary) {
|
|
1134
|
+
const key = `${owner}\0${c.id}`;
|
|
1135
|
+
clearTimeout(this.summaryTimers.get(key));
|
|
1136
|
+
this.summaryTimers.delete(key);
|
|
1137
|
+
this.event(owner, 'conversation.changed', c, c.id);
|
|
1138
|
+
}
|
|
1139
|
+
else
|
|
1140
|
+
this.scheduleSummary(owner, c);
|
|
1141
|
+
});
|
|
1142
|
+
}
|
|
1143
|
+
agentSummary(agent) {
|
|
1144
|
+
const policy = readHostTools(this.home);
|
|
1145
|
+
return { ...agent, execution: 'profile', canManageTeam: true, canCollaborate: true, approvalPolicy: policy.approvalPolicy, envs: { vm: policy.vm, cloud: policy.cloud, desktop: policy.scriptMachine || policy.serverComputer, browser: false }, avatar: agent.avatar || encodeAgentAvatar(defaultAgentIdentity(agent.id, agent.name)) };
|
|
1146
|
+
}
|
|
1147
|
+
conversationSummary(owner, conversation) {
|
|
1148
|
+
const member = conversation.kind === 'direct' ? this.get(owner, 'agent', conversation.memberIds[0] ?? '') : undefined;
|
|
1149
|
+
return {
|
|
1150
|
+
...conversation,
|
|
1151
|
+
unread: conversation.unread ?? false,
|
|
1152
|
+
unreadVersion: conversation.unreadVersion ?? 0,
|
|
1153
|
+
unreadCount: conversation.unread ? 1 : 0,
|
|
1154
|
+
...(member ? { avatar: this.agentSummary(member).avatar } : {}),
|
|
1155
|
+
lastMessageAt: conversation.lastMessageAt
|
|
1156
|
+
?? (conversation.lastSeq > 0 ? this.messages(owner, conversation.id, Number.MAX_SAFE_INTEGER, 1).at(-1)?.createdAt : undefined)
|
|
1157
|
+
?? conversation.createdAt,
|
|
1158
|
+
};
|
|
1159
|
+
}
|
|
1160
|
+
hiddenMessageIds(owner, conversationId, conversationTaskId) {
|
|
1161
|
+
this.require(owner, 'conversation', conversationId);
|
|
1162
|
+
if (conversationTaskId)
|
|
1163
|
+
this.requireTask(owner, conversationId, conversationTaskId);
|
|
1164
|
+
const taskClause = conversationTaskId ? "AND json_extract(data,'$.conversationTaskId')=?" : '';
|
|
1165
|
+
return this.db.prepare(`SELECT id FROM workspace_entities WHERE owner=? AND kind='message' AND json_extract(data,'$.conversationId')=? AND json_extract(data,'$.visible')=0 ${taskClause} ORDER BY json_extract(data,'$.seq') ASC`)
|
|
1166
|
+
.all(...(conversationTaskId ? [owner, conversationId, conversationTaskId] : [owner, conversationId])).map(row => String(row.id));
|
|
1167
|
+
}
|
|
1168
|
+
saveRun(owner, run) {
|
|
1169
|
+
this.atomic(() => {
|
|
1170
|
+
const c = this.require(owner, 'conversation', run.conversationId);
|
|
1171
|
+
run.updatedAt = Date.now();
|
|
1172
|
+
this.put(owner, 'run', run.id, run);
|
|
1173
|
+
if (run.conversationTaskId) {
|
|
1174
|
+
const task = this.requireTask(owner, c.id, run.conversationTaskId), activeRuns = this.list(owner, 'run')
|
|
1175
|
+
.filter(root => root.conversationTaskId === task.id && !['complete', 'failed', 'interrupted'].includes(root.status))
|
|
1176
|
+
.sort((a, b) => a.createdAt - b.createdAt || a.id.localeCompare(b.id)), active = activeRuns[0];
|
|
1177
|
+
task.activeRunId = active?.id;
|
|
1178
|
+
task.activeRunStatus = active?.status;
|
|
1179
|
+
this.put(owner, 'conversation-task', task.id, task);
|
|
1180
|
+
this.event(owner, 'task.changed', task, c.id);
|
|
1181
|
+
}
|
|
1182
|
+
this.projectConversationRuns(owner, c);
|
|
1183
|
+
this.put(owner, 'conversation', c.id, c);
|
|
1184
|
+
this.event(owner, 'run.changed', run, c.id);
|
|
1185
|
+
this.event(owner, 'conversation.changed', c, c.id);
|
|
1186
|
+
});
|
|
1187
|
+
}
|
|
1188
|
+
activeTaskCount(owner, conversationId) {
|
|
1189
|
+
return new Set(this.list(owner, 'run')
|
|
1190
|
+
.filter(run => run.conversationId === conversationId && run.conversationTaskId && !['complete', 'failed', 'interrupted'].includes(run.status))
|
|
1191
|
+
.map(run => run.conversationTaskId)).size;
|
|
1192
|
+
}
|
|
1193
|
+
projectConversationRuns(owner, conversation) {
|
|
1194
|
+
const roots = this.list(owner, 'run').filter(run => run.conversationId === conversation.id && !['complete', 'failed', 'interrupted'].includes(run.status))
|
|
1195
|
+
.sort((a, b) => this.require(owner, 'message', a.messageId).seq - this.require(owner, 'message', b.messageId).seq), current = roots[0];
|
|
1196
|
+
conversation.activeRunId = current?.id;
|
|
1197
|
+
conversation.activeAgentId = current?.activeAgentId;
|
|
1198
|
+
conversation.activeRunStatus = current?.status;
|
|
1199
|
+
const turns = this.db.prepare("SELECT data FROM workspace_entities WHERE owner=? AND kind='turn' AND json_extract(data,'$.conversationId')=? AND json_extract(data,'$.status') IN ('running','waiting','uncertain','queued') AND (json_extract(data,'$.status') != 'queued' OR json_extract(data,'$.planned')=1) ORDER BY CASE json_extract(data,'$.status') WHEN 'queued' THEN 0 WHEN 'running' THEN 1 ELSE 2 END").all(owner, conversation.id)
|
|
1200
|
+
.map(row => JSON.parse(String(row.data)));
|
|
1201
|
+
conversation.activeAgentStates = Object.fromEntries(turns.map(turn => [turn.agentId, turn.status]));
|
|
1202
|
+
const outcomes = this.db.prepare("SELECT data FROM workspace_entities WHERE owner=? AND kind='turn' AND json_extract(data,'$.conversationId')=? AND json_extract(data,'$.status') IN ('complete','failed') AND json_extract(data,'$.updatedAt')>=? ORDER BY json_extract(data,'$.updatedAt') ASC").all(owner, conversation.id, Date.now() - 2000)
|
|
1203
|
+
.map(row => JSON.parse(String(row.data)));
|
|
1204
|
+
conversation.avatarSignals = Object.fromEntries(outcomes.filter(turn => Date.now() - turn.updatedAt < 2000).map(turn => [turn.agentId, { id: turn.id, state: turn.status === 'failed' ? 'failure' : 'success', at: turn.updatedAt }]));
|
|
1205
|
+
conversation.queuedMessageCount = roots.filter(run => run.status === 'queued').length;
|
|
1206
|
+
}
|
|
1207
|
+
ownsUpstream(id) {
|
|
1208
|
+
return Boolean(this.db
|
|
1209
|
+
.prepare(`SELECT 1 FROM workspace_entities WHERE kind='binding' AND (json_extract(data,'$.storedId')=? OR json_extract(data,'$.runtimeId')=? OR EXISTS(SELECT 1 FROM json_each(json_extract(data,'$.aliases')) WHERE value=?)) LIMIT 1`)
|
|
1210
|
+
.get(id, id, id));
|
|
1211
|
+
}
|
|
1212
|
+
close() {
|
|
1213
|
+
for (const timer of this.summaryTimers.values())
|
|
1214
|
+
clearTimeout(timer);
|
|
1215
|
+
this.summaryTimers.clear();
|
|
1216
|
+
this.changes.emit('workspace.close');
|
|
1217
|
+
this.changes.removeAllListeners();
|
|
1218
|
+
this.db.close();
|
|
1219
|
+
}
|
|
1220
|
+
}
|