@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,125 @@
|
|
|
1
|
+
import { basename } from 'node:path';
|
|
2
|
+
import MarkdownIt from 'markdown-it';
|
|
3
|
+
const MAXIMUM_SOURCE_CHARACTERS = 16 * 1_024;
|
|
4
|
+
const markdown = new MarkdownIt({
|
|
5
|
+
html: false,
|
|
6
|
+
breaks: false,
|
|
7
|
+
linkify: false,
|
|
8
|
+
typographer: false,
|
|
9
|
+
});
|
|
10
|
+
markdown.disable('smartquotes');
|
|
11
|
+
const graphemeSegmenter = new Intl.Segmenter('zh-CN', { granularity: 'grapheme' });
|
|
12
|
+
function sourcePrefix(value) {
|
|
13
|
+
if (value.length <= MAXIMUM_SOURCE_CHARACTERS)
|
|
14
|
+
return value;
|
|
15
|
+
let result = value.slice(0, MAXIMUM_SOURCE_CHARACTERS);
|
|
16
|
+
const last = result.charCodeAt(result.length - 1);
|
|
17
|
+
if (last >= 0xD800 && last <= 0xDBFF)
|
|
18
|
+
result = result.slice(0, -1);
|
|
19
|
+
return result;
|
|
20
|
+
}
|
|
21
|
+
function inlineText(tokens) {
|
|
22
|
+
const result = [];
|
|
23
|
+
for (const token of tokens) {
|
|
24
|
+
if (token.type === 'text')
|
|
25
|
+
result.push(token.content);
|
|
26
|
+
else if (token.type === 'code_inline')
|
|
27
|
+
result.push(token.content);
|
|
28
|
+
else if (token.type === 'softbreak' || token.type === 'hardbreak')
|
|
29
|
+
result.push(' ');
|
|
30
|
+
else if (token.type === 'image') {
|
|
31
|
+
const alt = inlineText(token.children ?? []).trim() || token.content.trim() || '图片';
|
|
32
|
+
result.push(`🖼️ ${alt}`);
|
|
33
|
+
}
|
|
34
|
+
else if (token.type !== 'html_inline' && token.children?.length) {
|
|
35
|
+
result.push(inlineText(token.children));
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
return result.join('');
|
|
39
|
+
}
|
|
40
|
+
function markdownText(value) {
|
|
41
|
+
const result = [];
|
|
42
|
+
for (const token of markdown.parse(value, {})) {
|
|
43
|
+
if (token.type === 'inline') {
|
|
44
|
+
const text = inlineText(token.children ?? []).trim();
|
|
45
|
+
if (text)
|
|
46
|
+
result.push(text);
|
|
47
|
+
}
|
|
48
|
+
else if (token.type === 'fence' || token.type === 'code_block') {
|
|
49
|
+
result.push('💻 代码片段');
|
|
50
|
+
}
|
|
51
|
+
else if (token.type === 'list_item_open') {
|
|
52
|
+
result.push('•');
|
|
53
|
+
}
|
|
54
|
+
else if (token.type === 'th_open' || token.type === 'td_open') {
|
|
55
|
+
result.push('•');
|
|
56
|
+
}
|
|
57
|
+
else if (token.type === 'hr') {
|
|
58
|
+
result.push('•');
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return result.join(' ');
|
|
62
|
+
}
|
|
63
|
+
function visibleBasename(value) {
|
|
64
|
+
const unwrapped = value.replace(/^<|>$/g, '').replace(/[\])}>,.;,。;:]+$/u, '');
|
|
65
|
+
try {
|
|
66
|
+
const decoded = decodeURIComponent(unwrapped);
|
|
67
|
+
return basename(decoded) || '附件';
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
return basename(unwrapped) || '附件';
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
function replaceHermesReferences(value) {
|
|
74
|
+
return value
|
|
75
|
+
.replace(/@(terminal|tool):[^\r\n]*/giu, (_match, kind) => (kind.toLowerCase() === 'terminal' ? '💻 终端信息' : '🛠️ 工具信息'))
|
|
76
|
+
.replace(/@(file|folder|image):\s*([^\s]+)/giu, (_match, kind, target) => {
|
|
77
|
+
const icon = kind.toLowerCase() === 'image' ? '🖼️' : kind.toLowerCase() === 'folder' ? '📁' : '📎';
|
|
78
|
+
return `${icon} ${visibleBasename(target)}`;
|
|
79
|
+
})
|
|
80
|
+
.replace(/@url:\s*[^\s]+/giu, '🔗 链接');
|
|
81
|
+
}
|
|
82
|
+
function stripUnsafeTechnicalText(value) {
|
|
83
|
+
return value
|
|
84
|
+
.replace(/\u001B(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007]*(?:\u0007|\u001B\\))/gu, '')
|
|
85
|
+
.split(/\r?\n/u)
|
|
86
|
+
.filter(line => !/^\s*at\s+(?:async\s+)?[^\s]+.*(?:\([^)]*:\d+:\d+\)|:\d+:\d+)\s*$/u.test(line)
|
|
87
|
+
&& !/^\s*File\s+"[^"]+",\s+line\s+\d+/u.test(line))
|
|
88
|
+
.join('\n');
|
|
89
|
+
}
|
|
90
|
+
function redactRawLocations(value) {
|
|
91
|
+
return value
|
|
92
|
+
.replace(/\bhttps?:\/\/[^\s<>()]+/giu, '🔗 链接')
|
|
93
|
+
.replace(/\bdata:[^\s]+/giu, '🖼️ 图片')
|
|
94
|
+
.replace(/(^|[\s((::])((?:\/[^\s/]+){2,})/gu, (_match, prefix, target) => (`${prefix}📎 ${visibleBasename(target)}`))
|
|
95
|
+
.replace(/\[图片:([^\]]+)\]/gu, '🖼️ $1')
|
|
96
|
+
.replace(/\[文件:([^\]]+)\]/gu, '📎 $1');
|
|
97
|
+
}
|
|
98
|
+
function normalizeVisibleText(value) {
|
|
99
|
+
return value
|
|
100
|
+
.normalize('NFC')
|
|
101
|
+
.replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F]/gu, '')
|
|
102
|
+
.replace(/[\u200B\u202A-\u202E\u2060\u2066-\u2069\uFEFF]/gu, '')
|
|
103
|
+
.replace(/<\/?[A-Za-z][^>]*>/gu, ' ')
|
|
104
|
+
.replace(/(?:\s*•\s*){2,}/gu, ' • ')
|
|
105
|
+
.replace(/\s+/gu, ' ')
|
|
106
|
+
.trim();
|
|
107
|
+
}
|
|
108
|
+
function truncateGraphemes(value, maximum) {
|
|
109
|
+
const segments = [...graphemeSegmenter.segment(value)].map(segment => segment.segment);
|
|
110
|
+
if (segments.length <= maximum)
|
|
111
|
+
return value;
|
|
112
|
+
return `${segments.slice(0, Math.max(0, maximum - 1)).join('')}…`;
|
|
113
|
+
}
|
|
114
|
+
/** Converts model-authored Markdown into one safe, visible notification line. */
|
|
115
|
+
export function notificationPlainText(raw, options) {
|
|
116
|
+
const source = typeof raw === 'string' ? sourcePrefix(raw).trim() : '';
|
|
117
|
+
if (!source)
|
|
118
|
+
return options.fallback;
|
|
119
|
+
const prepared = replaceHermesReferences(stripUnsafeTechnicalText(source));
|
|
120
|
+
const rendered = markdownText(prepared);
|
|
121
|
+
const normalized = normalizeVisibleText(redactRawLocations(rendered));
|
|
122
|
+
if (!normalized)
|
|
123
|
+
return options.fallback;
|
|
124
|
+
return truncateGraphemes(normalized, options.maximum);
|
|
125
|
+
}
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';
|
|
2
|
+
import { chmodSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { dirname, join } from 'node:path';
|
|
4
|
+
import { HttpError } from './errors.js';
|
|
5
|
+
export const DEFAULT_OPENVIKING_URL = 'http://127.0.0.1:1933';
|
|
6
|
+
export function openVikingConfigurationPath(home) {
|
|
7
|
+
return join(home, 'openviking', 'config.json');
|
|
8
|
+
}
|
|
9
|
+
export function openVikingKeyPath(home) {
|
|
10
|
+
return join(home, 'openviking', 'master.key');
|
|
11
|
+
}
|
|
12
|
+
function canonicalInput(value) {
|
|
13
|
+
const url = new URL(typeof value.url === 'string' && value.url.trim() ? value.url.trim() : DEFAULT_OPENVIKING_URL);
|
|
14
|
+
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.pathname !== '/') {
|
|
15
|
+
throw new HttpError(400, 'OpenViking 服务地址无效', 'invalid_openviking_url');
|
|
16
|
+
}
|
|
17
|
+
const accountId = typeof value.accountId === 'string' ? value.accountId.trim() : '';
|
|
18
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/.test(accountId))
|
|
19
|
+
throw new HttpError(400, 'OpenViking Account ID 无效', 'invalid_openviking_account');
|
|
20
|
+
const adminKey = typeof value.adminKey === 'string' ? value.adminKey.trim() : '';
|
|
21
|
+
if (!adminKey || adminKey.length > 4096)
|
|
22
|
+
throw new HttpError(400, 'OpenViking 管理员 Key 无效', 'invalid_openviking_admin_key');
|
|
23
|
+
return { enabled: value.enabled !== false, url: url.toString().replace(/\/$/, ''), accountId, adminKey };
|
|
24
|
+
}
|
|
25
|
+
function encodeEncrypted(value) {
|
|
26
|
+
return ['v1', value.iv.toString('base64url'), value.tag.toString('base64url'), value.value.toString('base64url')].join('.');
|
|
27
|
+
}
|
|
28
|
+
function decodeEncrypted(value) {
|
|
29
|
+
const parts = value.split('.');
|
|
30
|
+
if (parts.length !== 4 || parts[0] !== 'v1')
|
|
31
|
+
throw new Error('unsupported ciphertext');
|
|
32
|
+
return { iv: Buffer.from(parts[1], 'base64url'), tag: Buffer.from(parts[2], 'base64url'), value: Buffer.from(parts[3], 'base64url') };
|
|
33
|
+
}
|
|
34
|
+
function masterKey(path) {
|
|
35
|
+
try {
|
|
36
|
+
const key = readFileSync(path);
|
|
37
|
+
if (key.byteLength === 32) {
|
|
38
|
+
chmodSync(path, 0o600);
|
|
39
|
+
return key;
|
|
40
|
+
}
|
|
41
|
+
throw new Error('OpenViking master key must contain 32 bytes');
|
|
42
|
+
}
|
|
43
|
+
catch (error) {
|
|
44
|
+
if (error.code !== 'ENOENT')
|
|
45
|
+
throw error;
|
|
46
|
+
}
|
|
47
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
48
|
+
chmodSync(dirname(path), 0o700);
|
|
49
|
+
const key = randomBytes(32);
|
|
50
|
+
const descriptor = openSync(path, 'wx', 0o600);
|
|
51
|
+
try {
|
|
52
|
+
writeFileSync(descriptor, key);
|
|
53
|
+
fsyncSync(descriptor);
|
|
54
|
+
}
|
|
55
|
+
finally {
|
|
56
|
+
closeSync(descriptor);
|
|
57
|
+
}
|
|
58
|
+
return key;
|
|
59
|
+
}
|
|
60
|
+
export function encryptOpenVikingSecret(home, plainText) {
|
|
61
|
+
const iv = randomBytes(12), cipher = createCipheriv('aes-256-gcm', masterKey(openVikingKeyPath(home)), iv);
|
|
62
|
+
const value = Buffer.concat([cipher.update(plainText, 'utf8'), cipher.final()]);
|
|
63
|
+
return encodeEncrypted({ iv, tag: cipher.getAuthTag(), value });
|
|
64
|
+
}
|
|
65
|
+
export function decryptOpenVikingSecret(home, encoded) {
|
|
66
|
+
const parts = decodeEncrypted(encoded);
|
|
67
|
+
const decipher = createDecipheriv('aes-256-gcm', masterKey(openVikingKeyPath(home)), parts.iv);
|
|
68
|
+
decipher.setAuthTag(parts.tag);
|
|
69
|
+
return Buffer.concat([decipher.update(parts.value), decipher.final()]).toString('utf8');
|
|
70
|
+
}
|
|
71
|
+
function readConfiguration(home) {
|
|
72
|
+
const path = openVikingConfigurationPath(home);
|
|
73
|
+
const descriptor = openSync(path, 'r');
|
|
74
|
+
try {
|
|
75
|
+
const details = statSync(path);
|
|
76
|
+
if (!details.isFile() || details.size > 64 * 1024)
|
|
77
|
+
throw new Error('invalid OpenViking configuration file');
|
|
78
|
+
const value = JSON.parse(readFileSync(descriptor, 'utf8'));
|
|
79
|
+
if (value.schemaVersion !== 1 || typeof value.encryptedAdminKey !== 'string')
|
|
80
|
+
throw new Error('invalid OpenViking configuration file');
|
|
81
|
+
chmodSync(path, 0o600);
|
|
82
|
+
return value;
|
|
83
|
+
}
|
|
84
|
+
finally {
|
|
85
|
+
closeSync(descriptor);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
function writeAtomic(path, value) {
|
|
89
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
90
|
+
chmodSync(dirname(path), 0o700);
|
|
91
|
+
const temporary = `${path}.${process.pid}.${randomBytes(8).toString('hex')}.tmp`;
|
|
92
|
+
let descriptor;
|
|
93
|
+
try {
|
|
94
|
+
descriptor = openSync(temporary, 'wx', 0o600);
|
|
95
|
+
writeFileSync(descriptor, value);
|
|
96
|
+
fsyncSync(descriptor);
|
|
97
|
+
closeSync(descriptor);
|
|
98
|
+
descriptor = undefined;
|
|
99
|
+
renameSync(temporary, path);
|
|
100
|
+
chmodSync(path, 0o600);
|
|
101
|
+
}
|
|
102
|
+
catch (error) {
|
|
103
|
+
if (descriptor !== undefined)
|
|
104
|
+
closeSync(descriptor);
|
|
105
|
+
try {
|
|
106
|
+
unlinkSync(temporary);
|
|
107
|
+
}
|
|
108
|
+
catch { /* absent */ }
|
|
109
|
+
throw error;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
function environmentConfiguration(env) {
|
|
113
|
+
const url = env.HERMES_YAOYAO_OPENVIKING_URL?.trim();
|
|
114
|
+
const accountId = env.HERMES_YAOYAO_OPENVIKING_ACCOUNT_ID?.trim();
|
|
115
|
+
const adminKey = env.HERMES_YAOYAO_OPENVIKING_ADMIN_KEY?.trim();
|
|
116
|
+
if (!url && !accountId && !adminKey)
|
|
117
|
+
return undefined;
|
|
118
|
+
return canonicalInput({ enabled: true, url, accountId, adminKey });
|
|
119
|
+
}
|
|
120
|
+
function storedConfiguration(home) {
|
|
121
|
+
if (!existsSync(openVikingConfigurationPath(home)))
|
|
122
|
+
return undefined;
|
|
123
|
+
const stored = readConfiguration(home);
|
|
124
|
+
return { enabled: stored.enabled, url: stored.url, accountId: stored.accountId, adminKey: decryptOpenVikingSecret(home, stored.encryptedAdminKey) };
|
|
125
|
+
}
|
|
126
|
+
function snapshot(config, source, error) {
|
|
127
|
+
return {
|
|
128
|
+
enabled: config.enabled, url: config.url, accountId: config.accountId, keyConfigured: Boolean(config.adminKey),
|
|
129
|
+
source, status: !config.enabled ? 'disabled' : error ? 'error' : 'ready', ...(error ? { error } : {}),
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
export function loadOpenVikingConfiguration(home, env = process.env) {
|
|
133
|
+
const fromEnvironment = environmentConfiguration(env);
|
|
134
|
+
if (fromEnvironment)
|
|
135
|
+
return snapshot(fromEnvironment, 'environment');
|
|
136
|
+
try {
|
|
137
|
+
const stored = storedConfiguration(home);
|
|
138
|
+
return stored ? snapshot(stored, 'file') : { enabled: false, url: DEFAULT_OPENVIKING_URL, accountId: '', keyConfigured: false, source: 'none', status: 'disabled' };
|
|
139
|
+
}
|
|
140
|
+
catch (cause) {
|
|
141
|
+
return { enabled: false, url: DEFAULT_OPENVIKING_URL, accountId: '', keyConfigured: false, source: 'file', status: 'error', error: cause instanceof Error ? cause.message : 'OpenViking 配置文件无效' };
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
async function defaultProbe(config) {
|
|
145
|
+
const url = new URL(`/api/v1/admin/accounts/${encodeURIComponent(config.accountId)}/users`, config.url);
|
|
146
|
+
url.searchParams.set('limit', '1');
|
|
147
|
+
const response = await fetch(url, {
|
|
148
|
+
headers: { 'X-API-Key': config.adminKey, 'X-OpenViking-Account': config.accountId },
|
|
149
|
+
signal: AbortSignal.timeout(5000),
|
|
150
|
+
});
|
|
151
|
+
if (!response.ok)
|
|
152
|
+
throw new Error(`OpenViking returned HTTP ${response.status}`);
|
|
153
|
+
await response.json();
|
|
154
|
+
}
|
|
155
|
+
export class OpenVikingConfigurationManager {
|
|
156
|
+
home;
|
|
157
|
+
path;
|
|
158
|
+
#snapshot;
|
|
159
|
+
#operation = Promise.resolve();
|
|
160
|
+
#probe;
|
|
161
|
+
constructor(home, initial, probe) {
|
|
162
|
+
this.home = home;
|
|
163
|
+
this.path = openVikingConfigurationPath(home);
|
|
164
|
+
this.#snapshot = initial ?? loadOpenVikingConfiguration(home);
|
|
165
|
+
this.#probe = probe ?? defaultProbe;
|
|
166
|
+
}
|
|
167
|
+
snapshot() { return { ...this.#snapshot }; }
|
|
168
|
+
configuration() {
|
|
169
|
+
const value = this.#snapshot;
|
|
170
|
+
if (!value.enabled || value.status !== 'ready')
|
|
171
|
+
return undefined;
|
|
172
|
+
if (value.source === 'environment')
|
|
173
|
+
return environmentConfiguration(process.env);
|
|
174
|
+
return storedConfiguration(this.home);
|
|
175
|
+
}
|
|
176
|
+
update(input, apply) {
|
|
177
|
+
const operation = this.#operation.then(() => this.#update(input, apply));
|
|
178
|
+
this.#operation = operation.then(() => undefined, () => undefined);
|
|
179
|
+
return operation;
|
|
180
|
+
}
|
|
181
|
+
async #update(input, apply) {
|
|
182
|
+
if (this.#snapshot.source === 'environment')
|
|
183
|
+
throw new HttpError(409, 'OpenViking 配置由环境变量管理', 'openviking_environment_managed');
|
|
184
|
+
const previousFile = existsSync(this.path) ? readFileSync(this.path) : undefined;
|
|
185
|
+
const previous = storedConfiguration(this.home);
|
|
186
|
+
const requested = canonicalInput({
|
|
187
|
+
enabled: input.enabled ?? previous?.enabled ?? false,
|
|
188
|
+
url: input.url ?? previous?.url ?? DEFAULT_OPENVIKING_URL,
|
|
189
|
+
accountId: input.accountId ?? previous?.accountId ?? '',
|
|
190
|
+
adminKey: input.adminKey ?? previous?.adminKey ?? '',
|
|
191
|
+
});
|
|
192
|
+
if (requested.enabled) {
|
|
193
|
+
try {
|
|
194
|
+
await this.#probe(requested);
|
|
195
|
+
}
|
|
196
|
+
catch (cause) {
|
|
197
|
+
throw new HttpError(422, `OpenViking 连接验证失败:${cause instanceof Error ? cause.message : '未知错误'}`, 'openviking_unavailable');
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
const stored = {
|
|
201
|
+
schemaVersion: 1, enabled: requested.enabled, url: requested.url, accountId: requested.accountId,
|
|
202
|
+
encryptedAdminKey: encryptOpenVikingSecret(this.home, requested.adminKey), updatedAt: new Date().toISOString(),
|
|
203
|
+
};
|
|
204
|
+
try {
|
|
205
|
+
writeAtomic(this.path, `${JSON.stringify(stored, null, 2)}\n`);
|
|
206
|
+
await apply?.(requested.enabled ? requested : undefined);
|
|
207
|
+
}
|
|
208
|
+
catch (cause) {
|
|
209
|
+
try {
|
|
210
|
+
if (previousFile)
|
|
211
|
+
writeAtomic(this.path, previousFile.toString('utf8'));
|
|
212
|
+
else if (existsSync(this.path))
|
|
213
|
+
unlinkSync(this.path);
|
|
214
|
+
await apply?.(previous?.enabled ? previous : undefined);
|
|
215
|
+
}
|
|
216
|
+
catch { /* preserve the original error */ }
|
|
217
|
+
throw cause;
|
|
218
|
+
}
|
|
219
|
+
this.#snapshot = snapshot(requested, 'file');
|
|
220
|
+
return this.snapshot();
|
|
221
|
+
}
|
|
222
|
+
}
|
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { OpenVikingError } from '@openviking/sdk';
|
|
3
|
+
import { HttpError } from './errors.js';
|
|
4
|
+
const sha = (value) => createHash('sha256').update(value).digest('hex');
|
|
5
|
+
const normalize = (value) => value.normalize('NFC').replace(/\s+/gu, ' ').trim();
|
|
6
|
+
const json = (value) => `${JSON.stringify(value, null, 2)}\n`;
|
|
7
|
+
const isUuid = (value) => /^[0-9a-f]{32}$/.test(value);
|
|
8
|
+
const memoryId = (requestId) => requestId.replaceAll('-', '');
|
|
9
|
+
const MEMORY_TAG = 'yaoyao_memory=true';
|
|
10
|
+
const activeUri = (scope, id) => `viking://~/memories/yaoyao/${scope.scope}/${id}.json`;
|
|
11
|
+
const revisionsUri = (scope, id, revision) => `viking://resources/yaoyao/${scope.scope}/${id}/revisions/${revision}.json`;
|
|
12
|
+
const tombstoneUri = (scope, fingerprint) => `viking://resources/yaoyao/${scope.scope}/tombstones/${fingerprint}.json`;
|
|
13
|
+
const requestUri = (requestId) => `viking://resources/yaoyao/requests/${requestId.replaceAll('-', '')}.json`;
|
|
14
|
+
const fingerprintUri = (scope, fingerprint) => `viking://resources/yaoyao/${scope.scope}/fingerprints/${fingerprint}.json`;
|
|
15
|
+
const forgottenSourcesUri = (scope) => `viking://resources/yaoyao/${scope.scope}/forgotten-sources.json`;
|
|
16
|
+
function assertScope(scope) {
|
|
17
|
+
if (scope.scope === 'project' && !/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/.test(scope.projectId ?? ''))
|
|
18
|
+
throw new HttpError(400, '需要选择项目', 'project_required');
|
|
19
|
+
}
|
|
20
|
+
async function notFoundAsUndefined(operation) {
|
|
21
|
+
try {
|
|
22
|
+
return await operation();
|
|
23
|
+
}
|
|
24
|
+
catch (error) {
|
|
25
|
+
if (error instanceof HttpError && error.status === 404)
|
|
26
|
+
return undefined;
|
|
27
|
+
if (error instanceof OpenVikingError && (error.statusCode === 404 || error.code === 'NOT_FOUND' || error.code === 'ENOENT'))
|
|
28
|
+
return undefined;
|
|
29
|
+
throw error;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
function uriName(value) {
|
|
33
|
+
if (typeof value === 'string')
|
|
34
|
+
return value;
|
|
35
|
+
if (value && typeof value === 'object') {
|
|
36
|
+
const record = value;
|
|
37
|
+
for (const key of ['uri', 'path', 'name', 'id'])
|
|
38
|
+
if (typeof record[key] === 'string')
|
|
39
|
+
return record[key];
|
|
40
|
+
}
|
|
41
|
+
return undefined;
|
|
42
|
+
}
|
|
43
|
+
export class OpenVikingMemoryProvider {
|
|
44
|
+
service;
|
|
45
|
+
knowledge;
|
|
46
|
+
#locks = new Map();
|
|
47
|
+
constructor(service, knowledge) {
|
|
48
|
+
this.service = service;
|
|
49
|
+
this.knowledge = knowledge;
|
|
50
|
+
}
|
|
51
|
+
async withLock(owner, agentId, operation) {
|
|
52
|
+
const key = `${owner}\0${agentId}`;
|
|
53
|
+
const previous = this.#locks.get(key) ?? Promise.resolve();
|
|
54
|
+
const next = previous.catch(() => undefined).then(operation);
|
|
55
|
+
this.#locks.set(key, next);
|
|
56
|
+
try {
|
|
57
|
+
await next;
|
|
58
|
+
}
|
|
59
|
+
finally {
|
|
60
|
+
if (this.#locks.get(key) === next)
|
|
61
|
+
this.#locks.delete(key);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
async ensure(owner, agentId) {
|
|
65
|
+
if (!this.service.enabled)
|
|
66
|
+
return;
|
|
67
|
+
const agent = this.knowledge.agent(owner, agentId);
|
|
68
|
+
await this.service.ensureUser(owner, agent);
|
|
69
|
+
}
|
|
70
|
+
async readRecord(owner, scope, id) {
|
|
71
|
+
assertScope(scope);
|
|
72
|
+
const raw = await notFoundAsUndefined(() => this.service.userClient(owner, scope.agentId).read(activeUri(scope, id)));
|
|
73
|
+
if (!raw)
|
|
74
|
+
return undefined;
|
|
75
|
+
try {
|
|
76
|
+
const value = JSON.parse(raw);
|
|
77
|
+
if (value.schemaVersion !== 1 || !value.memory || !Array.isArray(value.revisions))
|
|
78
|
+
throw new Error('invalid');
|
|
79
|
+
return value;
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
throw new HttpError(409, 'OpenViking 记忆文件损坏', 'openviking_memory_corrupt');
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
async readJson(owner, agentId, uri, fallback) {
|
|
86
|
+
const raw = await notFoundAsUndefined(() => this.service.userClient(owner, agentId).read(uri));
|
|
87
|
+
if (!raw)
|
|
88
|
+
return fallback;
|
|
89
|
+
try {
|
|
90
|
+
return JSON.parse(raw);
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
throw new HttpError(409, 'OpenViking 记忆审计文件损坏', 'openviking_memory_corrupt');
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
async listScope(owner, scope) {
|
|
97
|
+
assertScope(scope);
|
|
98
|
+
const client = this.service.userClient(owner, scope.agentId);
|
|
99
|
+
const directory = `viking://~/memories/yaoyao/${scope.scope}`;
|
|
100
|
+
const entries = await notFoundAsUndefined(() => client.list(directory, { recursive: true })) ?? [];
|
|
101
|
+
const records = [];
|
|
102
|
+
for (const entry of entries) {
|
|
103
|
+
const name = uriName(entry);
|
|
104
|
+
const match = /([0-9a-f]{32})\.json$/.exec(name ?? '');
|
|
105
|
+
if (!match)
|
|
106
|
+
continue;
|
|
107
|
+
const record = await this.readRecord(owner, scope, match[1]);
|
|
108
|
+
if (record && record.memory.scope === scope.scope && record.memory.agentId === scope.agentId
|
|
109
|
+
&& record.memory.projectId === scope.projectId)
|
|
110
|
+
records.push(record.memory);
|
|
111
|
+
}
|
|
112
|
+
return records;
|
|
113
|
+
}
|
|
114
|
+
async list(owner, scopes) {
|
|
115
|
+
const result = [];
|
|
116
|
+
for (const scope of scopes) {
|
|
117
|
+
await this.ensure(owner, scope.agentId);
|
|
118
|
+
result.push(...await this.listScope(owner, scope));
|
|
119
|
+
}
|
|
120
|
+
return result;
|
|
121
|
+
}
|
|
122
|
+
async writeWithResult(owner, input, actor = {}) {
|
|
123
|
+
assertScope(input);
|
|
124
|
+
this.knowledge.authorizeMemory(owner, input, actor, true);
|
|
125
|
+
if (input.scope === 'project')
|
|
126
|
+
this.knowledge.requireProjectMember(owner, input.projectId, input.agentId);
|
|
127
|
+
let output;
|
|
128
|
+
let outcome = 'replayed';
|
|
129
|
+
await this.withLock(owner, input.agentId, async () => {
|
|
130
|
+
await this.ensure(owner, input.agentId);
|
|
131
|
+
const client = this.service.userClient(owner, input.agentId);
|
|
132
|
+
const requestFingerprint = sha(JSON.stringify({ operation: 'memory.write', input, actor }));
|
|
133
|
+
const savedRequest = await this.readJson(owner, input.agentId, requestUri(input.requestId), undefined);
|
|
134
|
+
if (savedRequest) {
|
|
135
|
+
if (savedRequest.fingerprint !== requestFingerprint)
|
|
136
|
+
throw new HttpError(409, '请求标识已用于其他内容', 'idempotency_conflict');
|
|
137
|
+
output = savedRequest.memory;
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
const all = await this.listScope(owner, input), old = input.id ? all.find(memory => memory.id === input.id) : undefined;
|
|
141
|
+
if (input.id && !old)
|
|
142
|
+
throw new HttpError(404, '记忆不存在', 'memory_not_found');
|
|
143
|
+
if (old && old.revision !== input.expectedRevision)
|
|
144
|
+
throw new HttpError(409, '记忆已更新,请重新读取后保存;草稿已保留', 'memory_revision_conflict');
|
|
145
|
+
if (actor.agentId && old?.origin === 'manual')
|
|
146
|
+
throw new HttpError(403, '用户维护的记忆不能被机器人覆盖', 'memory_manual_protected');
|
|
147
|
+
if (input.automatic && old && old.origin !== 'synthesis')
|
|
148
|
+
throw new HttpError(403, '自动整理不能覆盖明确记忆', 'memory_explicit_protected');
|
|
149
|
+
const content = normalize(input.content);
|
|
150
|
+
if (!content || content.length > 2000)
|
|
151
|
+
throw new HttpError(400, '每条记忆需要 1 至 2000 个字符', 'memory_content_invalid');
|
|
152
|
+
const duplicate = all.find(memory => memory.id !== old?.id && memory.content.toLowerCase() === content.toLowerCase());
|
|
153
|
+
if (duplicate) {
|
|
154
|
+
output = duplicate;
|
|
155
|
+
outcome = 'duplicate';
|
|
156
|
+
}
|
|
157
|
+
else {
|
|
158
|
+
const fingerprint = sha(content.toLowerCase());
|
|
159
|
+
const tombstone = await this.readJson(owner, input.agentId, tombstoneUri(input, fingerprint), undefined);
|
|
160
|
+
const forgottenSources = await this.readJson(owner, input.agentId, forgottenSourcesUri(input), []);
|
|
161
|
+
if (input.automatic && (tombstone || input.sources?.some(source => forgottenSources.includes(source.messageId))))
|
|
162
|
+
throw new HttpError(409, '此记忆或其旧来源已被遗忘', 'memory_forgotten');
|
|
163
|
+
const sources = input.sources ?? old?.sources ?? [];
|
|
164
|
+
if (actor.agentId && !sources.length)
|
|
165
|
+
throw new HttpError(400, '保存记忆需要来源消息', 'memory_source_required');
|
|
166
|
+
for (const source of sources) {
|
|
167
|
+
const message = this.knowledge.store.require(owner, 'message', source.messageId);
|
|
168
|
+
if (message.conversationId !== source.conversationId || message.visible === false || (source.quote && !message.content.includes(source.quote)))
|
|
169
|
+
throw new HttpError(400, '记忆来源无效', 'memory_source_invalid');
|
|
170
|
+
if (actor.agentId && input.scope === 'user' && (message.role !== 'user' || !source.quote?.trim()))
|
|
171
|
+
throw new HttpError(400, '用户共享记忆需要用户原话依据', 'memory_user_evidence_required');
|
|
172
|
+
}
|
|
173
|
+
const now = Date.now();
|
|
174
|
+
const memory = {
|
|
175
|
+
id: old?.id ?? memoryId(input.requestId), scope: input.scope, agentId: input.agentId,
|
|
176
|
+
...(input.projectId ? { projectId: input.projectId } : {}), content, tier: input.tier,
|
|
177
|
+
origin: actor.agentId ? input.automatic ? 'synthesis' : 'explicit' : 'manual', sources,
|
|
178
|
+
revision: (old?.revision ?? 0) + 1, createdAt: old?.createdAt ?? now, updatedAt: now,
|
|
179
|
+
};
|
|
180
|
+
if (input.topic || old?.topic)
|
|
181
|
+
memory.topic = normalize(input.topic ?? old.topic).slice(0, 100);
|
|
182
|
+
const revision = { id: memoryId(`${input.requestId}-${memory.revision}`), memoryId: memory.id, revision: memory.revision, operation: 'write', actor: actor.agentId ?? 'user', at: now, before: old, after: memory };
|
|
183
|
+
const previous = await this.readRecord(owner, input, memory.id);
|
|
184
|
+
const record = { schemaVersion: 1, memory, revisions: [...(previous?.revisions ?? []), revision], requestFingerprint };
|
|
185
|
+
const uri = activeUri(input, memory.id);
|
|
186
|
+
await client.write(uri, json(record), { wait: true });
|
|
187
|
+
await client.setTags(uri, [MEMORY_TAG, `yaoyao_scope=${input.scope}`, `yaoyao_memory_id=${memory.id}`, ...(input.projectId ? [`yaoyao_project=${input.projectId}`] : [])]);
|
|
188
|
+
await client.write(revisionsUri(input, memory.id, memory.revision), json(revision), { wait: true });
|
|
189
|
+
await client.write(requestUri(input.requestId), json({ fingerprint: requestFingerprint, memory }), { wait: true });
|
|
190
|
+
await client.write(fingerprintUri(input, fingerprint), json({ id: memory.id, revision: memory.revision }), { wait: true });
|
|
191
|
+
if (old && old.content.toLowerCase() !== content.toLowerCase() && memory.origin !== 'synthesis') {
|
|
192
|
+
const oldFingerprint = sha(old.content.toLowerCase());
|
|
193
|
+
await client.write(tombstoneUri(input, oldFingerprint), json({ at: now }), { wait: true });
|
|
194
|
+
await client.write(forgottenSourcesUri(input), json([...new Set([...forgottenSources, ...old.sources.map(source => source.messageId)])]), { wait: true });
|
|
195
|
+
}
|
|
196
|
+
if (!input.automatic)
|
|
197
|
+
await client.remove(tombstoneUri(input, fingerprint), { wait: true }).catch(() => undefined);
|
|
198
|
+
output = memory;
|
|
199
|
+
outcome = 'written';
|
|
200
|
+
}
|
|
201
|
+
await client.write(requestUri(input.requestId), json({ fingerprint: requestFingerprint, memory: output }), { wait: true });
|
|
202
|
+
});
|
|
203
|
+
this.knowledge.emitMemoryChanged(owner);
|
|
204
|
+
return { memory: output, outcome };
|
|
205
|
+
}
|
|
206
|
+
async forget(owner, input, actor = {}) {
|
|
207
|
+
assertScope(input);
|
|
208
|
+
this.knowledge.authorizeMemory(owner, input, actor, true);
|
|
209
|
+
let output;
|
|
210
|
+
const requestFingerprint = sha(JSON.stringify({ operation: 'memory.forget', input, actor }));
|
|
211
|
+
await this.withLock(owner, input.agentId, async () => {
|
|
212
|
+
await this.ensure(owner, input.agentId);
|
|
213
|
+
const savedRequest = await this.readJson(owner, input.agentId, requestUri(input.requestId), undefined);
|
|
214
|
+
if (savedRequest?.result) {
|
|
215
|
+
if (savedRequest.fingerprint !== requestFingerprint)
|
|
216
|
+
throw new HttpError(409, '请求标识已用于其他内容', 'idempotency_conflict');
|
|
217
|
+
output = savedRequest.result;
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
const old = await this.readRecord(owner, input, input.id);
|
|
221
|
+
if (!old)
|
|
222
|
+
throw new HttpError(404, '记忆不存在', 'memory_not_found');
|
|
223
|
+
if (old.memory.revision !== input.expectedRevision)
|
|
224
|
+
throw new HttpError(409, '记忆已更新,请重新读取后操作', 'memory_revision_conflict');
|
|
225
|
+
if (actor.agentId && old.memory.origin === 'manual')
|
|
226
|
+
throw new HttpError(403, '用户维护的记忆不能被机器人删除', 'memory_manual_protected');
|
|
227
|
+
const client = this.service.userClient(owner, input.agentId), now = Date.now(), fingerprint = sha(old.memory.content.toLowerCase());
|
|
228
|
+
const revision = { id: memoryId(`${input.requestId}-${old.memory.revision + 1}`), memoryId: old.memory.id, revision: old.memory.revision + 1, operation: 'forget', actor: actor.agentId ?? 'user', at: now, before: old.memory };
|
|
229
|
+
await client.remove(activeUri(input, old.memory.id), { wait: true });
|
|
230
|
+
await client.write(revisionsUri(input, old.memory.id, revision.revision), json(revision), { wait: true });
|
|
231
|
+
await client.write(tombstoneUri(input, fingerprint), json({ at: now }), { wait: true });
|
|
232
|
+
await client.write(forgottenSourcesUri(input), json([...new Set([...await this.readJson(owner, input.agentId, forgottenSourcesUri(input), []), ...old.memory.sources.map(source => source.messageId)])]), { wait: true });
|
|
233
|
+
output = { id: old.memory.id, scope: old.memory.scope, agentId: old.memory.agentId, ...(old.memory.projectId ? { projectId: old.memory.projectId } : {}) };
|
|
234
|
+
await client.write(requestUri(input.requestId), json({ fingerprint: requestFingerprint, result: output }), { wait: true });
|
|
235
|
+
});
|
|
236
|
+
this.knowledge.emitMemoryChanged(owner);
|
|
237
|
+
return output;
|
|
238
|
+
}
|
|
239
|
+
async revisions(owner, scope, id) {
|
|
240
|
+
assertScope(scope);
|
|
241
|
+
this.knowledge.authorizeMemory(owner, scope, {});
|
|
242
|
+
await this.ensure(owner, scope.agentId);
|
|
243
|
+
if (!isUuid(id))
|
|
244
|
+
return [];
|
|
245
|
+
const directory = `viking://resources/yaoyao/${scope.scope}/${id}/revisions`;
|
|
246
|
+
const entries = await notFoundAsUndefined(() => this.service.userClient(owner, scope.agentId).list(directory, { recursive: true })) ?? [];
|
|
247
|
+
const revisions = [];
|
|
248
|
+
for (const entry of entries) {
|
|
249
|
+
const name = uriName(entry), match = /(\d+)\.json$/.exec(name ?? '');
|
|
250
|
+
if (match) {
|
|
251
|
+
const revision = await this.readJson(owner, scope.agentId, revisionsUri(scope, id, Number(match[1])), {});
|
|
252
|
+
if (revision.id)
|
|
253
|
+
revisions.push(revision);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
return revisions.sort((left, right) => right.revision - left.revision);
|
|
257
|
+
}
|
|
258
|
+
async search(owner, query, scopes, actor = {}) {
|
|
259
|
+
const exact = await this.list(owner, scopes.filter(scope => {
|
|
260
|
+
this.knowledge.authorizeMemory(owner, scope, actor);
|
|
261
|
+
return true;
|
|
262
|
+
}));
|
|
263
|
+
if (!query.search)
|
|
264
|
+
return exact;
|
|
265
|
+
const wanted = new Set();
|
|
266
|
+
for (const scope of scopes) {
|
|
267
|
+
const found = await notFoundAsUndefined(() => this.service.userClient(owner, scope.agentId).find(query.search, { targetUri: `viking://~/memories/yaoyao/${query.scope}`, limit: 100, tags: [MEMORY_TAG] }));
|
|
268
|
+
if (!found)
|
|
269
|
+
continue;
|
|
270
|
+
for (const memory of Array.isArray(found.memories) ? found.memories : []) {
|
|
271
|
+
const uri = uriName(memory) ?? uriName(memory.source);
|
|
272
|
+
const match = /([0-9a-f]{32})\.json$/.exec(uri ?? '');
|
|
273
|
+
if (match)
|
|
274
|
+
wanted.add(match[1]);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
return exact.filter(memory => wanted.has(memory.id) || memory.content.toLowerCase().includes(query.search.toLowerCase()));
|
|
278
|
+
}
|
|
279
|
+
}
|