@hashgraphonline/conversational-agent 0.2.215 → 0.2.217
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/cli/readme.md +181 -0
- package/dist/cjs/index.cjs +1 -1
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/index.d.ts +1 -0
- package/dist/cjs/plugins/community/swarm/SwarmPlugin.d.ts +17 -0
- package/dist/cjs/plugins/community/swarm/__tests__/SwarmPlugin.mocks.d.ts +1 -0
- package/dist/cjs/plugins/community/swarm/__tests__/SwarmPlugin.test.d.ts +1 -0
- package/dist/cjs/plugins/community/swarm/__tests__/tools/CreatePostageStampTool.test.d.ts +1 -0
- package/dist/cjs/plugins/community/swarm/__tests__/tools/DownloadDataTool.test.d.ts +1 -0
- package/dist/cjs/plugins/community/swarm/__tests__/tools/DownloadFilesTool.test.d.ts +1 -0
- package/dist/cjs/plugins/community/swarm/__tests__/tools/ExtendPostageStampTool.test.d.ts +1 -0
- package/dist/cjs/plugins/community/swarm/__tests__/tools/GetPostageStampTool.test.d.ts +1 -0
- package/dist/cjs/plugins/community/swarm/__tests__/tools/ListPostageStampsTool.test.d.ts +1 -0
- package/dist/cjs/plugins/community/swarm/__tests__/tools/QueryUploadProgressTool.test.d.ts +1 -0
- package/dist/cjs/plugins/community/swarm/__tests__/tools/ReadFeedTool.test.d.ts +1 -0
- package/dist/cjs/plugins/community/swarm/__tests__/tools/SwarmTool.mocks.d.ts +14 -0
- package/dist/cjs/plugins/community/swarm/__tests__/tools/UpdateFeedTool.test.d.ts +1 -0
- package/dist/cjs/plugins/community/swarm/__tests__/tools/UploadDataTool.test.d.ts +1 -0
- package/dist/cjs/plugins/community/swarm/__tests__/tools/UploadFileTool.test.d.ts +1 -0
- package/dist/cjs/plugins/community/swarm/__tests__/tools/UploadFolderTool.test.d.ts +1 -0
- package/dist/cjs/plugins/community/swarm/config.d.ts +6 -0
- package/dist/cjs/plugins/community/swarm/constants.d.ts +8 -0
- package/dist/cjs/plugins/community/swarm/index.d.ts +2 -0
- package/dist/cjs/plugins/community/swarm/model.d.ts +23 -0
- package/dist/cjs/plugins/community/swarm/tools/CreatePostageStampTool.d.ts +47 -0
- package/dist/cjs/plugins/community/swarm/tools/DownloadDataTool.d.ts +35 -0
- package/dist/cjs/plugins/community/swarm/tools/DownloadFilesTool.d.ts +41 -0
- package/dist/cjs/plugins/community/swarm/tools/ExtendPostageStampTool.d.ts +47 -0
- package/dist/cjs/plugins/community/swarm/tools/GetPostageStampTool.d.ts +35 -0
- package/dist/cjs/plugins/community/swarm/tools/ListPostageStampsTool.d.ts +53 -0
- package/dist/cjs/plugins/community/swarm/tools/QueryUploadProgressTool.d.ts +35 -0
- package/dist/cjs/plugins/community/swarm/tools/ReadFeedTool.d.ts +41 -0
- package/dist/cjs/plugins/community/swarm/tools/UpdateFeedTool.d.ts +47 -0
- package/dist/cjs/plugins/community/swarm/tools/UploadDataTool.d.ts +47 -0
- package/dist/cjs/plugins/community/swarm/tools/UploadFileTool.d.ts +53 -0
- package/dist/cjs/plugins/community/swarm/tools/UploadFolderTool.d.ts +47 -0
- package/dist/cjs/plugins/community/swarm/utils.d.ts +22 -0
- package/dist/cjs/plugins/index.d.ts +1 -0
- package/dist/esm/index.js +33 -31
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/index10.js +13 -677
- package/dist/esm/index10.js.map +1 -1
- package/dist/esm/index11.js +601 -234
- package/dist/esm/index11.js.map +1 -1
- package/dist/esm/index12.js +296 -136
- package/dist/esm/index12.js.map +1 -1
- package/dist/esm/index13.js +127 -235
- package/dist/esm/index13.js.map +1 -1
- package/dist/esm/index14.js +247 -84
- package/dist/esm/index14.js.map +1 -1
- package/dist/esm/index15.js +81 -159
- package/dist/esm/index15.js.map +1 -1
- package/dist/esm/index16.js +155 -229
- package/dist/esm/index16.js.map +1 -1
- package/dist/esm/index17.js +238 -140
- package/dist/esm/index17.js.map +1 -1
- package/dist/esm/index18.js +139 -493
- package/dist/esm/index18.js.map +1 -1
- package/dist/esm/index19.js +479 -91
- package/dist/esm/index19.js.map +1 -1
- package/dist/esm/index20.js +88 -147
- package/dist/esm/index20.js.map +1 -1
- package/dist/esm/index21.js +127 -666
- package/dist/esm/index21.js.map +1 -1
- package/dist/esm/index22.js +698 -44
- package/dist/esm/index22.js.map +1 -1
- package/dist/esm/index23.js +45 -304
- package/dist/esm/index23.js.map +1 -1
- package/dist/esm/index24.js +303 -153
- package/dist/esm/index24.js.map +1 -1
- package/dist/esm/index25.js +150 -117
- package/dist/esm/index25.js.map +1 -1
- package/dist/esm/index26.js +154 -18
- package/dist/esm/index26.js.map +1 -1
- package/dist/esm/index27.js +18 -22
- package/dist/esm/index27.js.map +1 -1
- package/dist/esm/index28.js +15 -74
- package/dist/esm/index28.js.map +1 -1
- package/dist/esm/index29.js +70 -295
- package/dist/esm/index29.js.map +1 -1
- package/dist/esm/index30.js +279 -100
- package/dist/esm/index30.js.map +1 -1
- package/dist/esm/index31.js +86 -922
- package/dist/esm/index31.js.map +1 -1
- package/dist/esm/index32.js +904 -189
- package/dist/esm/index32.js.map +1 -1
- package/dist/esm/index33.js +185 -1169
- package/dist/esm/index33.js.map +1 -1
- package/dist/esm/index34.js +1218 -112
- package/dist/esm/index34.js.map +1 -1
- package/dist/esm/index35.js +111 -99
- package/dist/esm/index35.js.map +1 -1
- package/dist/esm/index36.js +113 -8
- package/dist/esm/index36.js.map +1 -1
- package/dist/esm/index37.js +8 -45
- package/dist/esm/index37.js.map +1 -1
- package/dist/esm/index38.js +41 -102
- package/dist/esm/index38.js.map +1 -1
- package/dist/esm/index39.js +96 -55
- package/dist/esm/index39.js.map +1 -1
- package/dist/esm/index4.js +1 -1
- package/dist/esm/index40.js +58 -71
- package/dist/esm/index40.js.map +1 -1
- package/dist/esm/index41.js +79 -21
- package/dist/esm/index41.js.map +1 -1
- package/dist/esm/index42.js +21 -5
- package/dist/esm/index42.js.map +1 -1
- package/dist/esm/index43.js +4 -11
- package/dist/esm/index43.js.map +1 -1
- package/dist/esm/index44.js +12 -322
- package/dist/esm/index44.js.map +1 -1
- package/dist/esm/index45.js +280 -142
- package/dist/esm/index45.js.map +1 -1
- package/dist/esm/index46.js +181 -24
- package/dist/esm/index46.js.map +1 -1
- package/dist/esm/index48.js +67 -85
- package/dist/esm/index48.js.map +1 -1
- package/dist/esm/index49.js +75 -0
- package/dist/esm/index49.js.map +1 -0
- package/dist/esm/index5.js +2 -2
- package/dist/esm/index50.js +57 -0
- package/dist/esm/index50.js.map +1 -0
- package/dist/esm/index51.js +103 -0
- package/dist/esm/index51.js.map +1 -0
- package/dist/esm/index52.js +79 -0
- package/dist/esm/index52.js.map +1 -0
- package/dist/esm/index53.js +75 -0
- package/dist/esm/index53.js.map +1 -0
- package/dist/esm/index54.js +124 -0
- package/dist/esm/index54.js.map +1 -0
- package/dist/esm/index55.js +58 -0
- package/dist/esm/index55.js.map +1 -0
- package/dist/esm/index56.js +83 -0
- package/dist/esm/index56.js.map +1 -0
- package/dist/esm/index57.js +100 -0
- package/dist/esm/index57.js.map +1 -0
- package/dist/esm/index58.js +118 -0
- package/dist/esm/index58.js.map +1 -0
- package/dist/esm/index59.js +108 -0
- package/dist/esm/index59.js.map +1 -0
- package/dist/esm/index6.js +132 -833
- package/dist/esm/index6.js.map +1 -1
- package/dist/esm/index60.js +30 -0
- package/dist/esm/index60.js.map +1 -0
- package/dist/esm/index61.js +98 -0
- package/dist/esm/index61.js.map +1 -0
- package/dist/esm/index62.js +131 -0
- package/dist/esm/index62.js.map +1 -0
- package/dist/esm/index63.js +19 -0
- package/dist/esm/index63.js.map +1 -0
- package/dist/esm/index7.js +826 -75
- package/dist/esm/index7.js.map +1 -1
- package/dist/esm/index8.js +91 -13
- package/dist/esm/index8.js.map +1 -1
- package/dist/esm/index9.js +13 -17
- package/dist/esm/index9.js.map +1 -1
- package/dist/types/index.d.ts +1 -0
- package/dist/types/plugins/community/swarm/SwarmPlugin.d.ts +17 -0
- package/dist/types/plugins/community/swarm/__tests__/SwarmPlugin.mocks.d.ts +1 -0
- package/dist/types/plugins/community/swarm/__tests__/SwarmPlugin.test.d.ts +1 -0
- package/dist/types/plugins/community/swarm/__tests__/tools/CreatePostageStampTool.test.d.ts +1 -0
- package/dist/types/plugins/community/swarm/__tests__/tools/DownloadDataTool.test.d.ts +1 -0
- package/dist/types/plugins/community/swarm/__tests__/tools/DownloadFilesTool.test.d.ts +1 -0
- package/dist/types/plugins/community/swarm/__tests__/tools/ExtendPostageStampTool.test.d.ts +1 -0
- package/dist/types/plugins/community/swarm/__tests__/tools/GetPostageStampTool.test.d.ts +1 -0
- package/dist/types/plugins/community/swarm/__tests__/tools/ListPostageStampsTool.test.d.ts +1 -0
- package/dist/types/plugins/community/swarm/__tests__/tools/QueryUploadProgressTool.test.d.ts +1 -0
- package/dist/types/plugins/community/swarm/__tests__/tools/ReadFeedTool.test.d.ts +1 -0
- package/dist/types/plugins/community/swarm/__tests__/tools/SwarmTool.mocks.d.ts +14 -0
- package/dist/types/plugins/community/swarm/__tests__/tools/UpdateFeedTool.test.d.ts +1 -0
- package/dist/types/plugins/community/swarm/__tests__/tools/UploadDataTool.test.d.ts +1 -0
- package/dist/types/plugins/community/swarm/__tests__/tools/UploadFileTool.test.d.ts +1 -0
- package/dist/types/plugins/community/swarm/__tests__/tools/UploadFolderTool.test.d.ts +1 -0
- package/dist/types/plugins/community/swarm/config.d.ts +6 -0
- package/dist/types/plugins/community/swarm/constants.d.ts +8 -0
- package/dist/types/plugins/community/swarm/index.d.ts +2 -0
- package/dist/types/plugins/community/swarm/model.d.ts +23 -0
- package/dist/types/plugins/community/swarm/tools/CreatePostageStampTool.d.ts +47 -0
- package/dist/types/plugins/community/swarm/tools/DownloadDataTool.d.ts +35 -0
- package/dist/types/plugins/community/swarm/tools/DownloadFilesTool.d.ts +41 -0
- package/dist/types/plugins/community/swarm/tools/ExtendPostageStampTool.d.ts +47 -0
- package/dist/types/plugins/community/swarm/tools/GetPostageStampTool.d.ts +35 -0
- package/dist/types/plugins/community/swarm/tools/ListPostageStampsTool.d.ts +53 -0
- package/dist/types/plugins/community/swarm/tools/QueryUploadProgressTool.d.ts +35 -0
- package/dist/types/plugins/community/swarm/tools/ReadFeedTool.d.ts +41 -0
- package/dist/types/plugins/community/swarm/tools/UpdateFeedTool.d.ts +47 -0
- package/dist/types/plugins/community/swarm/tools/UploadDataTool.d.ts +47 -0
- package/dist/types/plugins/community/swarm/tools/UploadFileTool.d.ts +53 -0
- package/dist/types/plugins/community/swarm/tools/UploadFolderTool.d.ts +47 -0
- package/dist/types/plugins/community/swarm/utils.d.ts +22 -0
- package/dist/types/plugins/index.d.ts +1 -0
- package/package.json +37 -27
- package/src/index.ts +1 -0
- package/src/plugins/community/swarm/README.md +279 -0
- package/src/plugins/community/swarm/SwarmPlugin.ts +178 -0
- package/src/plugins/community/swarm/__tests__/SwarmPlugin.mocks.ts +105 -0
- package/src/plugins/community/swarm/__tests__/SwarmPlugin.test.ts +93 -0
- package/src/plugins/community/swarm/__tests__/tools/CreatePostageStampTool.test.ts +152 -0
- package/src/plugins/community/swarm/__tests__/tools/DownloadDataTool.test.ts +93 -0
- package/src/plugins/community/swarm/__tests__/tools/DownloadFilesTool.test.ts +163 -0
- package/src/plugins/community/swarm/__tests__/tools/ExtendPostageStampTool.test.ts +132 -0
- package/src/plugins/community/swarm/__tests__/tools/GetPostageStampTool.test.ts +83 -0
- package/src/plugins/community/swarm/__tests__/tools/ListPostageStampsTool.test.ts +219 -0
- package/src/plugins/community/swarm/__tests__/tools/QueryUploadProgressTool.test.ts +169 -0
- package/src/plugins/community/swarm/__tests__/tools/ReadFeedTool.test.ts +133 -0
- package/src/plugins/community/swarm/__tests__/tools/SwarmTool.mocks.ts +67 -0
- package/src/plugins/community/swarm/__tests__/tools/UpdateFeedTool.test.ts +148 -0
- package/src/plugins/community/swarm/__tests__/tools/UploadDataTool.test.ts +125 -0
- package/src/plugins/community/swarm/__tests__/tools/UploadFileTool.test.ts +194 -0
- package/src/plugins/community/swarm/__tests__/tools/UploadFolderTool.test.ts +118 -0
- package/src/plugins/community/swarm/config.ts +6 -0
- package/src/plugins/community/swarm/constants.ts +12 -0
- package/src/plugins/community/swarm/index.ts +2 -0
- package/src/plugins/community/swarm/model.ts +23 -0
- package/src/plugins/community/swarm/tools/CreatePostageStampTool.ts +137 -0
- package/src/plugins/community/swarm/tools/DownloadDataTool.ts +79 -0
- package/src/plugins/community/swarm/tools/DownloadFilesTool.ts +155 -0
- package/src/plugins/community/swarm/tools/ExtendPostageStampTool.ts +112 -0
- package/src/plugins/community/swarm/tools/GetPostageStampTool.ts +92 -0
- package/src/plugins/community/swarm/tools/ListPostageStampsTool.ts +124 -0
- package/src/plugins/community/swarm/tools/QueryUploadProgressTool.ts +109 -0
- package/src/plugins/community/swarm/tools/ReadFeedTool.ts +110 -0
- package/src/plugins/community/swarm/tools/UpdateFeedTool.ts +149 -0
- package/src/plugins/community/swarm/tools/UploadDataTool.ts +109 -0
- package/src/plugins/community/swarm/tools/UploadFileTool.ts +163 -0
- package/src/plugins/community/swarm/tools/UploadFolderTool.ts +150 -0
- package/src/plugins/community/swarm/utils.ts +172 -0
- package/src/plugins/index.ts +1 -0
- package/cli/dist/CLIApp.d.ts +0 -11
- package/cli/dist/CLIApp.d.ts.map +0 -1
- package/cli/dist/CLIApp.js +0 -128
- package/cli/dist/CLIApp.js.map +0 -1
- package/cli/dist/LocalConversationalAgent.d.ts +0 -37
- package/cli/dist/LocalConversationalAgent.js +0 -58
- package/cli/dist/app.d.ts +0 -18
- package/cli/dist/app.d.ts.map +0 -1
- package/cli/dist/app.js +0 -14
- package/cli/dist/app.js.map +0 -1
- package/cli/dist/cli.d.ts +0 -3
- package/cli/dist/cli.d.ts.map +0 -1
- package/cli/dist/cli.js +0 -87
- package/cli/dist/cli.js.map +0 -1
- package/cli/dist/components/AppContainer.d.ts +0 -16
- package/cli/dist/components/AppContainer.js +0 -24
- package/cli/dist/components/AppScreens.d.ts +0 -2
- package/cli/dist/components/AppScreens.js +0 -259
- package/cli/dist/components/ChatScreen.d.ts +0 -21
- package/cli/dist/components/ChatScreen.d.ts.map +0 -1
- package/cli/dist/components/ChatScreen.js +0 -40
- package/cli/dist/components/ChatScreen.js.map +0 -1
- package/cli/dist/components/DebugLoadingScreen.d.ts +0 -5
- package/cli/dist/components/DebugLoadingScreen.js +0 -31
- package/cli/dist/components/LoadingScreen.d.ts +0 -3
- package/cli/dist/components/LoadingScreen.d.ts.map +0 -1
- package/cli/dist/components/LoadingScreen.js +0 -17
- package/cli/dist/components/LoadingScreen.js.map +0 -1
- package/cli/dist/components/LoadingScreenDebug.d.ts +0 -5
- package/cli/dist/components/LoadingScreenDebug.js +0 -27
- package/cli/dist/components/MCPConfigScreen.d.ts +0 -28
- package/cli/dist/components/MCPConfigScreen.d.ts.map +0 -1
- package/cli/dist/components/MCPConfigScreen.js +0 -186
- package/cli/dist/components/MCPConfigScreen.js.map +0 -1
- package/cli/dist/components/ScreenRouter.d.ts +0 -13
- package/cli/dist/components/ScreenRouter.d.ts.map +0 -1
- package/cli/dist/components/ScreenRouter.js +0 -23
- package/cli/dist/components/ScreenRouter.js.map +0 -1
- package/cli/dist/components/SetupScreen.d.ts +0 -16
- package/cli/dist/components/SetupScreen.d.ts.map +0 -1
- package/cli/dist/components/SetupScreen.js +0 -67
- package/cli/dist/components/SetupScreen.js.map +0 -1
- package/cli/dist/components/SingleLoadingScreen.d.ts +0 -5
- package/cli/dist/components/SingleLoadingScreen.js +0 -27
- package/cli/dist/components/StatusBadge.d.ts +0 -10
- package/cli/dist/components/StatusBadge.d.ts.map +0 -1
- package/cli/dist/components/StatusBadge.js +0 -24
- package/cli/dist/components/StatusBadge.js.map +0 -1
- package/cli/dist/components/TerminalWindow.d.ts +0 -9
- package/cli/dist/components/TerminalWindow.d.ts.map +0 -1
- package/cli/dist/components/TerminalWindow.js +0 -19
- package/cli/dist/components/TerminalWindow.js.map +0 -1
- package/cli/dist/components/WelcomeScreen.d.ts +0 -12
- package/cli/dist/components/WelcomeScreen.d.ts.map +0 -1
- package/cli/dist/components/WelcomeScreen.js +0 -47
- package/cli/dist/components/WelcomeScreen.js.map +0 -1
- package/cli/dist/context/AppContext.d.ts +0 -68
- package/cli/dist/context/AppContext.js +0 -363
- package/cli/dist/headless-runner.d.ts +0 -17
- package/cli/dist/headless-runner.d.ts.map +0 -1
- package/cli/dist/headless-runner.js +0 -128
- package/cli/dist/headless-runner.js.map +0 -1
- package/cli/dist/hooks/useInitializeAgent.d.ts +0 -19
- package/cli/dist/hooks/useInitializeAgent.d.ts.map +0 -1
- package/cli/dist/hooks/useInitializeAgent.js +0 -29
- package/cli/dist/hooks/useInitializeAgent.js.map +0 -1
- package/cli/dist/hooks/useStableState.d.ts +0 -38
- package/cli/dist/hooks/useStableState.d.ts.map +0 -1
- package/cli/dist/hooks/useStableState.js +0 -69
- package/cli/dist/hooks/useStableState.js.map +0 -1
- package/cli/dist/managers/AgentManager.d.ts +0 -58
- package/cli/dist/managers/AgentManager.d.ts.map +0 -1
- package/cli/dist/managers/AgentManager.js +0 -121
- package/cli/dist/managers/AgentManager.js.map +0 -1
- package/cli/dist/managers/ConfigManager.d.ts +0 -54
- package/cli/dist/managers/ConfigManager.d.ts.map +0 -1
- package/cli/dist/managers/ConfigManager.js +0 -188
- package/cli/dist/managers/ConfigManager.js.map +0 -1
- package/cli/dist/types.d.ts +0 -52
- package/cli/dist/types.d.ts.map +0 -1
- package/cli/dist/types.js +0 -34
- package/cli/dist/types.js.map +0 -1
package/dist/esm/index22.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index22.js","sources":["../../src/memory/reference-id-generator.ts"],"sourcesContent":["import { createHash } from 'crypto';\nimport { ReferenceId } from '../types/content-reference';\n\n/**\n * Content-based reference ID generator using SHA-256 (HCS-1 style)\n * \n * Generates deterministic reference IDs based on content hashing.\n * Same content always produces the same reference ID.\n */\nexport class ReferenceIdGenerator {\n /**\n * Generate a content-based reference ID using SHA-256 hashing\n * \n * @param content The content to generate a reference ID for\n * @returns Deterministic reference ID based on content hash\n */\n static generateId(content: Buffer): ReferenceId {\n const hash = createHash('sha256');\n hash.update(content);\n return hash.digest('hex');\n }\n \n /**\n * Validate that a string is a properly formatted reference ID\n * \n * @param id The ID to validate\n * @returns true if the ID is valid format\n */\n static isValidReferenceId(id: string): id is ReferenceId {\n if (!id || typeof id !== 'string') {\n return false;\n }\n \n if (id.length !== 64) {\n return false;\n }\n \n return /^[a-f0-9]+$/.test(id);\n }\n \n /**\n * Extract reference ID from ref:// format\n * \n * @param input Input string that may contain a reference ID\n * @returns Extracted reference ID or null if not found\n */\n static extractReferenceId(input: string): ReferenceId | null {\n if (!input || typeof input !== 'string') {\n return null;\n }\n \n const refFormatMatch = input.match(/^ref:\\/\\/([a-f0-9]{64})$/);\n if (refFormatMatch) {\n return refFormatMatch[1] as ReferenceId;\n }\n \n return this.isValidReferenceId(input) ? input : null;\n }\n \n /**\n * Format a reference ID in the standard ref:// format\n * \n * @param referenceId The reference ID to format\n * @returns Formatted reference string\n */\n static formatReference(referenceId: ReferenceId): string {\n return `ref://${referenceId}`;\n }\n \n /**\n * Generate a test reference ID (for testing purposes only)\n * \n * @param testSeed A test seed to generate a fake but valid ID format\n * @returns A valid format reference ID for testing\n */\n static generateTestId(testSeed: string): ReferenceId {\n const content = Buffer.from(`test-${testSeed}-${Date.now()}`);\n return this.generateId(content);\n }\n}"],"names":[],"mappings":";AASO,MAAM,qBAAqB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOhC,OAAO,WAAW,SAA8B;AAC9C,UAAM,OAAO,WAAW,QAAQ;AAChC,SAAK,OAAO,OAAO;AACnB,WAAO,KAAK,OAAO,KAAK;AAAA,EAC1B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,OAAO,mBAAmB,IAA+B;AACvD,QAAI,CAAC,MAAM,OAAO,OAAO,UAAU;AACjC,aAAO;AAAA,IACT;AAEA,QAAI,GAAG,WAAW,IAAI;AACpB,aAAO;AAAA,IACT;AAEA,WAAO,cAAc,KAAK,EAAE;AAAA,EAC9B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,OAAO,mBAAmB,OAAmC;AAC3D,QAAI,CAAC,SAAS,OAAO,UAAU,UAAU;AACvC,aAAO;AAAA,IACT;AAEA,UAAM,iBAAiB,MAAM,MAAM,0BAA0B;AAC7D,QAAI,gBAAgB;AAClB,aAAO,eAAe,CAAC;AAAA,IACzB;AAEA,WAAO,KAAK,mBAAmB,KAAK,IAAI,QAAQ;AAAA,EAClD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,OAAO,gBAAgB,aAAkC;AACvD,WAAO,SAAS,WAAW;AAAA,EAC7B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,OAAO,eAAe,UAA+B;AACnD,UAAM,UAAU,OAAO,KAAK,QAAQ,QAAQ,IAAI,KAAK,IAAA,CAAK,EAAE;AAC5D,WAAO,KAAK,WAAW,OAAO;AAAA,EAChC;AACF;"}
|
|
1
|
+
{"version":3,"file":"index22.js","sources":["../../src/memory/content-storage.ts"],"sourcesContent":["import type { BaseMessage } from '@langchain/core/messages';\nimport { ReferenceIdGenerator } from './reference-id-generator';\nimport {\n ReferenceId,\n ContentReference,\n ContentMetadata,\n ReferenceResolutionResult,\n ContentReferenceConfig,\n ContentReferenceStore,\n ContentReferenceStats,\n ContentReferenceError,\n ContentType,\n ContentSource,\n ReferenceLifecycleState,\n DEFAULT_CONTENT_REFERENCE_CONFIG,\n} from '../types/content-reference';\n\n/**\n * Stored message with metadata\n */\ninterface StoredMessage {\n message: BaseMessage;\n storedAt: Date;\n id: string;\n}\n\n/**\n * Search options for message queries\n */\ninterface SearchOptions {\n /** Whether to perform case-sensitive search */\n caseSensitive?: boolean;\n /** Maximum number of results to return */\n limit?: number;\n /** Whether to use regex pattern matching */\n useRegex?: boolean;\n}\n\n/**\n * Result of storing messages\n */\ninterface StoreResult {\n /** Number of messages successfully stored */\n stored: number;\n /** Number of old messages dropped to make room */\n dropped: number;\n}\n\n/**\n * Storage statistics\n */\nexport interface StorageStats {\n /** Total number of messages currently stored */\n totalMessages: number;\n /** Maximum storage capacity */\n maxStorageLimit: number;\n /** Percentage of storage used */\n usagePercentage: number;\n /** Timestamp of oldest message */\n oldestMessageTime: Date | undefined;\n /** Timestamp of newest message */\n newestMessageTime: Date | undefined;\n}\n\n/**\n * Stored content with reference metadata\n */\ninterface StoredContent {\n /** The actual content buffer */\n content: Buffer;\n\n /** Complete metadata */\n metadata: ContentMetadata;\n\n /** Current lifecycle state */\n state: ReferenceLifecycleState;\n\n /** When this reference expires (if applicable) */\n expiresAt?: Date;\n}\n\n/**\n * Content storage for managing pruned conversation messages and large content references\n * Provides searchable storage with time-based querying and automatic cleanup.\n *\n * Extended to support reference-based storage for large content to optimize context window usage.\n */\nexport class ContentStorage implements ContentReferenceStore {\n private messages: StoredMessage[] = [];\n private maxStorage: number;\n private idCounter: number = 0;\n\n private contentStore: Map<ReferenceId, StoredContent> = new Map();\n private referenceConfig: ContentReferenceConfig;\n private cleanupTimer?: NodeJS.Timeout;\n private referenceStats: Omit<ContentReferenceStats, 'performanceMetrics'> & {\n performanceMetrics: ContentReferenceStats['performanceMetrics'] & {\n creationTimes: number[];\n resolutionTimes: number[];\n cleanupTimes: number[];\n };\n };\n\n public static readonly DEFAULT_MAX_STORAGE = 1000;\n\n constructor(\n maxStorage: number = ContentStorage.DEFAULT_MAX_STORAGE,\n referenceConfig?: Partial<ContentReferenceConfig>\n ) {\n this.maxStorage = maxStorage;\n\n this.referenceConfig = {\n ...DEFAULT_CONTENT_REFERENCE_CONFIG,\n ...referenceConfig,\n };\n this.referenceStats = {\n activeReferences: 0,\n totalStorageBytes: 0,\n recentlyCleanedUp: 0,\n totalResolutions: 0,\n failedResolutions: 0,\n averageContentSize: 0,\n storageUtilization: 0,\n performanceMetrics: {\n averageCreationTimeMs: 0,\n averageResolutionTimeMs: 0,\n averageCleanupTimeMs: 0,\n creationTimes: [],\n resolutionTimes: [],\n cleanupTimes: [],\n },\n };\n\n if (this.referenceConfig.enableAutoCleanup) {\n this.startReferenceCleanupTimer();\n }\n }\n\n /**\n * Store messages in the content storage\n * Automatically drops oldest messages if storage limit is exceeded\n * @param messages - Messages to store\n * @returns Result indicating how many messages were stored and dropped\n */\n storeMessages(messages: BaseMessage[]): StoreResult {\n if (messages.length === 0) {\n return { stored: 0, dropped: 0 };\n }\n\n const now = new Date();\n let dropped = 0;\n\n const storedMessages: StoredMessage[] = messages.map((message) => ({\n message,\n storedAt: now,\n id: this.generateId(),\n }));\n\n this.messages.push(...storedMessages);\n\n while (this.messages.length > this.maxStorage) {\n this.messages.shift();\n dropped++;\n }\n\n return {\n stored: storedMessages.length,\n dropped,\n };\n }\n\n /**\n * Get the most recent messages from storage\n * @param count - Number of recent messages to retrieve\n * @returns Array of recent messages in chronological order\n */\n getRecentMessages(count: number): BaseMessage[] {\n if (count <= 0 || this.messages.length === 0) {\n return [];\n }\n\n const startIndex = Math.max(0, this.messages.length - count);\n return this.messages.slice(startIndex).map((stored) => stored.message);\n }\n\n /**\n * Search for messages containing specific text or patterns\n * @param query - Search term or regex pattern\n * @param options - Search configuration options\n * @returns Array of matching messages\n */\n searchMessages(query: string, options: SearchOptions = {}): BaseMessage[] {\n if (!query || this.messages.length === 0) {\n return [];\n }\n\n const { caseSensitive = false, limit, useRegex = false } = options;\n\n let matches: BaseMessage[] = [];\n\n if (useRegex) {\n try {\n const regex = new RegExp(query, caseSensitive ? 'g' : 'gi');\n matches = this.messages\n .filter((stored) => regex.test(stored.message.content as string))\n .map((stored) => stored.message);\n } catch {\n return [];\n }\n } else {\n const searchTerm = caseSensitive ? query : query.toLowerCase();\n matches = this.messages\n .filter((stored) => {\n const content = stored.message.content as string;\n const searchContent = caseSensitive ? content : content.toLowerCase();\n return searchContent.includes(searchTerm);\n })\n .map((stored) => stored.message);\n }\n\n return limit ? matches.slice(0, limit) : matches;\n }\n\n /**\n * Get messages from a specific time range\n * @param startTime - Start of time range (inclusive)\n * @param endTime - End of time range (inclusive)\n * @returns Array of messages within the time range\n */\n getMessagesFromTimeRange(startTime: Date, endTime: Date): BaseMessage[] {\n if (startTime > endTime || this.messages.length === 0) {\n return [];\n }\n\n return this.messages\n .filter(\n (stored) => stored.storedAt >= startTime && stored.storedAt <= endTime\n )\n .map((stored) => stored.message);\n }\n\n /**\n * Get storage statistics and usage information\n * @returns Current storage statistics\n */\n getStorageStats(): StorageStats {\n const totalMessages = this.messages.length;\n const usagePercentage =\n totalMessages > 0\n ? Math.round((totalMessages / this.maxStorage) * 100)\n : 0;\n\n let oldestMessageTime: Date | undefined;\n let newestMessageTime: Date | undefined;\n\n if (totalMessages > 0) {\n oldestMessageTime = this.messages[0].storedAt;\n newestMessageTime = this.messages[totalMessages - 1].storedAt;\n }\n\n return {\n totalMessages,\n maxStorageLimit: this.maxStorage,\n usagePercentage,\n oldestMessageTime,\n newestMessageTime,\n };\n }\n\n /**\n * Clear all stored messages\n */\n clear(): void {\n this.messages = [];\n this.idCounter = 0;\n }\n\n /**\n * Get total number of stored messages\n * @returns Number of messages currently in storage\n */\n getTotalStoredMessages(): number {\n return this.messages.length;\n }\n\n /**\n * Update the maximum storage limit\n * @param newLimit - New maximum storage limit\n */\n updateStorageLimit(newLimit: number): void {\n if (newLimit <= 0) {\n throw new Error('Storage limit must be greater than 0');\n }\n\n this.maxStorage = newLimit;\n\n while (this.messages.length > this.maxStorage) {\n this.messages.shift();\n }\n }\n\n /**\n * Get messages by message type\n * @param messageType - Type of messages to retrieve ('human', 'ai', 'system', etc.)\n * @param limit - Maximum number of messages to return\n * @returns Array of messages of the specified type\n */\n getMessagesByType(messageType: string, limit?: number): BaseMessage[] {\n const filtered = this.messages\n .filter((stored) => stored.message._getType() === messageType)\n .map((stored) => stored.message);\n\n return limit ? filtered.slice(0, limit) : filtered;\n }\n\n /**\n * Get the current storage configuration\n * @returns Storage configuration object\n */\n getConfig(): {\n maxStorage: number;\n currentUsage: number;\n utilizationPercentage: number;\n } {\n return {\n maxStorage: this.maxStorage,\n currentUsage: this.messages.length,\n utilizationPercentage: (this.messages.length / this.maxStorage) * 100,\n };\n }\n\n /**\n * Generate a unique ID for stored messages\n * @returns Unique string identifier\n */\n private generateId(): string {\n return `msg_${++this.idCounter}_${Date.now()}`;\n }\n\n /**\n * Get messages stored within the last N minutes\n * @param minutes - Number of minutes to look back\n * @returns Array of messages from the last N minutes\n */\n getRecentMessagesByTime(minutes: number): BaseMessage[] {\n if (minutes <= 0 || this.messages.length === 0) {\n return [];\n }\n\n const cutoffTime = new Date(Date.now() - minutes * 60 * 1000);\n\n return this.messages\n .filter((stored) => stored.storedAt >= cutoffTime)\n .map((stored) => stored.message);\n }\n\n /**\n * Export messages to a JSON-serializable format\n * @returns Serializable representation of stored messages\n */\n exportMessages(): Array<{\n content: string;\n type: string;\n storedAt: string;\n id: string;\n }> {\n return this.messages.map((stored) => ({\n content:\n typeof stored.message.content === 'string'\n ? stored.message.content\n : JSON.stringify(stored.message.content),\n type: stored.message._getType(),\n storedAt: stored.storedAt.toISOString(),\n id: stored.id,\n }));\n }\n\n /**\n * Determine if content should be stored as a reference based on size\n */\n shouldUseReference(content: Buffer | string): boolean {\n const size = Buffer.isBuffer(content)\n ? content.length\n : Buffer.byteLength(content, 'utf8');\n return size > this.referenceConfig.sizeThresholdBytes;\n }\n\n /**\n * Store content and return a reference if it exceeds the size threshold\n * Otherwise returns null to indicate direct content should be used\n *\n * Special case: Image files are ALWAYS stored as references regardless of size\n * because they need special handling for inscription tools\n */\n async storeContentIfLarge(\n content: Buffer | string,\n metadata: {\n contentType?: ContentType;\n mimeType?: string;\n source: ContentSource;\n mcpToolName?: string;\n fileName?: string;\n tags?: string[];\n customMetadata?: Record<string, unknown>;\n }\n ): Promise<ContentReference | null> {\n const buffer = Buffer.isBuffer(content)\n ? content\n : Buffer.from(content, 'utf8');\n\n const isImageFile = this.isImageContent(\n metadata.mimeType,\n metadata.fileName\n );\n\n if (!isImageFile && !this.shouldUseReference(buffer)) {\n return null;\n }\n\n const storeMetadata: Omit<\n ContentMetadata,\n 'createdAt' | 'lastAccessedAt' | 'accessCount'\n > = {\n contentType:\n metadata.contentType ||\n this.detectContentType(buffer, metadata.mimeType),\n sizeBytes: buffer.length,\n source: metadata.source,\n tags: [],\n };\n\n if (metadata.mimeType !== undefined) {\n storeMetadata.mimeType = metadata.mimeType;\n }\n if (metadata.mcpToolName !== undefined) {\n storeMetadata.mcpToolName = metadata.mcpToolName;\n }\n if (metadata.fileName !== undefined) {\n storeMetadata.fileName = metadata.fileName;\n }\n if (metadata.tags !== undefined) {\n storeMetadata.tags = metadata.tags;\n }\n if (metadata.customMetadata !== undefined) {\n storeMetadata.customMetadata = metadata.customMetadata;\n }\n\n return await this.storeContent(buffer, storeMetadata);\n }\n\n /**\n * Store content and return a reference (implements ContentReferenceStore)\n */\n async storeContent(\n content: Buffer,\n metadata: Omit<\n ContentMetadata,\n 'createdAt' | 'lastAccessedAt' | 'accessCount'\n >\n ): Promise<ContentReference> {\n const startTime = Date.now();\n\n try {\n const now = new Date();\n const referenceId = ReferenceIdGenerator.generateId(content);\n\n const fullMetadata: ContentMetadata = {\n ...metadata,\n createdAt: now,\n lastAccessedAt: now,\n accessCount: 0,\n };\n\n const storedContent: StoredContent = {\n content,\n metadata: fullMetadata,\n state: 'active',\n };\n\n const expirationTime = this.calculateExpirationTime(metadata.source);\n if (expirationTime !== undefined) {\n storedContent.expiresAt = expirationTime;\n }\n\n this.contentStore.set(referenceId, storedContent);\n\n this.updateStatsAfterStore(content.length);\n\n await this.enforceReferenceStorageLimits();\n\n const preview = this.createContentPreview(\n content,\n fullMetadata.contentType\n );\n\n const referenceMetadata: Pick<\n ContentMetadata,\n 'contentType' | 'sizeBytes' | 'source' | 'fileName' | 'mimeType'\n > = {\n contentType: fullMetadata.contentType,\n sizeBytes: fullMetadata.sizeBytes,\n source: fullMetadata.source,\n };\n\n if (fullMetadata.fileName !== undefined) {\n referenceMetadata.fileName = fullMetadata.fileName;\n }\n if (fullMetadata.mimeType !== undefined) {\n referenceMetadata.mimeType = fullMetadata.mimeType;\n }\n\n const reference: ContentReference = {\n referenceId,\n state: 'active',\n preview,\n metadata: referenceMetadata,\n createdAt: now,\n format: 'ref://{id}' as const,\n };\n\n const duration = Date.now() - startTime;\n this.recordPerformanceMetric('creation', duration);\n\n return reference;\n } catch (error) {\n const duration = Date.now() - startTime;\n this.recordPerformanceMetric('creation', duration);\n\n throw new ContentReferenceError(\n `Failed to store content: ${\n error instanceof Error ? error.message : 'Unknown error'\n }`,\n 'system_error',\n undefined,\n ['Try again', 'Check storage limits', 'Contact administrator']\n );\n }\n }\n\n /**\n * Resolve a reference to its content (implements ContentReferenceStore)\n */\n async resolveReference(\n referenceId: ReferenceId\n ): Promise<ReferenceResolutionResult> {\n const startTime = Date.now();\n\n try {\n if (!ReferenceIdGenerator.isValidReferenceId(referenceId)) {\n this.referenceStats.failedResolutions++;\n return {\n success: false,\n error: 'Invalid reference ID format',\n errorType: 'not_found',\n suggestedActions: [\n 'Check the reference ID format',\n 'Ensure the reference ID is complete',\n ],\n };\n }\n\n const storedContent = this.contentStore.get(referenceId);\n\n if (!storedContent) {\n this.referenceStats.failedResolutions++;\n return {\n success: false,\n error: 'Reference not found',\n errorType: 'not_found',\n suggestedActions: [\n 'Verify the reference ID',\n 'Check if the content has expired',\n 'Request fresh content',\n ],\n };\n }\n\n if (storedContent.expiresAt && storedContent.expiresAt < new Date()) {\n storedContent.state = 'expired';\n this.referenceStats.failedResolutions++;\n return {\n success: false,\n error: 'Reference has expired',\n errorType: 'expired',\n suggestedActions: [\n 'Request fresh content',\n 'Use alternative content source',\n ],\n };\n }\n\n if (storedContent.state !== 'active') {\n this.referenceStats.failedResolutions++;\n return {\n success: false,\n error: `Reference is ${storedContent.state}`,\n errorType:\n storedContent.state === 'expired' ? 'expired' : 'corrupted',\n suggestedActions: [\n 'Request fresh content',\n 'Check reference validity',\n ],\n };\n }\n\n storedContent.metadata.lastAccessedAt = new Date();\n storedContent.metadata.accessCount++;\n\n this.referenceStats.totalResolutions++;\n\n const duration = Date.now() - startTime;\n this.recordPerformanceMetric('resolution', duration);\n\n return {\n success: true,\n content: storedContent.content,\n metadata: storedContent.metadata,\n };\n } catch (error) {\n const duration = Date.now() - startTime;\n this.recordPerformanceMetric('resolution', duration);\n\n this.referenceStats.failedResolutions++;\n\n return {\n success: false,\n error: `System error resolving reference: ${\n error instanceof Error ? error.message : 'Unknown error'\n }`,\n errorType: 'system_error',\n suggestedActions: ['Try again', 'Contact administrator'],\n };\n }\n }\n\n /**\n * Check if a reference exists and is valid\n */\n async hasReference(referenceId: ReferenceId): Promise<boolean> {\n if (!ReferenceIdGenerator.isValidReferenceId(referenceId)) {\n return false;\n }\n\n const storedContent = this.contentStore.get(referenceId);\n if (!storedContent) {\n return false;\n }\n\n if (storedContent.expiresAt && storedContent.expiresAt < new Date()) {\n storedContent.state = 'expired';\n return false;\n }\n\n return storedContent.state === 'active';\n }\n\n /**\n * Mark a reference for cleanup\n */\n async cleanupReference(referenceId: ReferenceId): Promise<boolean> {\n const storedContent = this.contentStore.get(referenceId);\n if (!storedContent) {\n return false;\n }\n\n this.referenceStats.totalStorageBytes -= storedContent.content.length;\n this.referenceStats.activeReferences--;\n this.referenceStats.recentlyCleanedUp++;\n\n this.contentStore.delete(referenceId);\n\n return true;\n }\n\n /**\n * Get current reference storage statistics (implements ContentReferenceStore)\n */\n async getStats(): Promise<ContentReferenceStats> {\n this.updateReferenceStorageStats();\n\n return {\n ...this.referenceStats,\n performanceMetrics: {\n averageCreationTimeMs: this.calculateAverage(\n this.referenceStats.performanceMetrics.creationTimes\n ),\n averageResolutionTimeMs: this.calculateAverage(\n this.referenceStats.performanceMetrics.resolutionTimes\n ),\n averageCleanupTimeMs: this.calculateAverage(\n this.referenceStats.performanceMetrics.cleanupTimes\n ),\n },\n };\n }\n\n /**\n * Update reference configuration\n */\n async updateConfig(config: Partial<ContentReferenceConfig>): Promise<void> {\n this.referenceConfig = { ...this.referenceConfig, ...config };\n\n if (this.cleanupTimer) {\n clearInterval(this.cleanupTimer);\n delete this.cleanupTimer;\n }\n\n if (this.referenceConfig.enableAutoCleanup) {\n this.startReferenceCleanupTimer();\n }\n }\n\n /**\n * Perform cleanup based on current policies (implements ContentReferenceStore)\n */\n async performCleanup(): Promise<{ cleanedUp: number; errors: string[] }> {\n const startTime = Date.now();\n const errors: string[] = [];\n let cleanedUp = 0;\n\n try {\n const now = new Date();\n const toCleanup: ReferenceId[] = [];\n\n for (const [referenceId, storedContent] of this.contentStore.entries()) {\n let shouldCleanup = false;\n\n if (storedContent.expiresAt && storedContent.expiresAt < now) {\n shouldCleanup = true;\n storedContent.state = 'expired';\n }\n\n const ageMs =\n now.getTime() - storedContent.metadata.createdAt.getTime();\n const policy = this.getCleanupPolicy(storedContent.metadata.source);\n\n if (ageMs > policy.maxAgeMs) {\n shouldCleanup = true;\n }\n\n if (storedContent.state === 'cleanup_pending') {\n shouldCleanup = true;\n }\n\n if (shouldCleanup) {\n toCleanup.push(referenceId);\n }\n }\n\n toCleanup.sort((a, b) => {\n const aContent = this.contentStore.get(a)!;\n const bContent = this.contentStore.get(b)!;\n const aPriority = this.getCleanupPolicy(\n aContent.metadata.source\n ).priority;\n const bPriority = this.getCleanupPolicy(\n bContent.metadata.source\n ).priority;\n return bPriority - aPriority;\n });\n\n for (const referenceId of toCleanup) {\n try {\n const success = await this.cleanupReference(referenceId);\n if (success) {\n cleanedUp++;\n }\n } catch (error) {\n errors.push(\n `Failed to cleanup ${referenceId}: ${\n error instanceof Error ? error.message : 'Unknown error'\n }`\n );\n }\n }\n\n if (this.contentStore.size > this.referenceConfig.maxReferences) {\n const sortedByAge = Array.from(this.contentStore.entries()).sort(\n ([, a], [, b]) =>\n a.metadata.lastAccessedAt.getTime() -\n b.metadata.lastAccessedAt.getTime()\n );\n\n const excessCount =\n this.contentStore.size - this.referenceConfig.maxReferences;\n for (let i = 0; i < excessCount && i < sortedByAge.length; i++) {\n const [referenceId] = sortedByAge[i];\n try {\n const success = await this.cleanupReference(referenceId);\n if (success) {\n cleanedUp++;\n }\n } catch (error) {\n errors.push(\n `Failed to cleanup excess reference ${referenceId}: ${\n error instanceof Error ? error.message : 'Unknown error'\n }`\n );\n }\n }\n }\n\n const duration = Date.now() - startTime;\n this.recordPerformanceMetric('cleanup', duration);\n\n return { cleanedUp, errors };\n } catch (error) {\n const duration = Date.now() - startTime;\n this.recordPerformanceMetric('cleanup', duration);\n\n const errorMessage = `Cleanup process failed: ${\n error instanceof Error ? error.message : 'Unknown error'\n }`;\n errors.push(errorMessage);\n\n return { cleanedUp, errors };\n }\n }\n\n /**\n * Get reference configuration for debugging\n */\n getReferenceConfig(): ContentReferenceConfig {\n return { ...this.referenceConfig };\n }\n\n private async enforceReferenceStorageLimits(): Promise<void> {\n if (this.contentStore.size >= this.referenceConfig.maxReferences) {\n await this.performCleanup();\n }\n\n if (\n this.referenceStats.totalStorageBytes >=\n this.referenceConfig.maxTotalStorageBytes\n ) {\n await this.performCleanup();\n }\n }\n\n private calculateExpirationTime(source: ContentSource): Date | undefined {\n const policy = this.getCleanupPolicy(source);\n return new Date(Date.now() + policy.maxAgeMs);\n }\n\n private getCleanupPolicy(source: ContentSource): {\n maxAgeMs: number;\n priority: number;\n } {\n switch (source) {\n case 'mcp_tool':\n return this.referenceConfig.cleanupPolicies.recent;\n case 'user_upload':\n return this.referenceConfig.cleanupPolicies.userContent;\n case 'agent_generated':\n return this.referenceConfig.cleanupPolicies.agentGenerated;\n default:\n return this.referenceConfig.cleanupPolicies.default;\n }\n }\n\n private detectContentType(content: Buffer, mimeType?: string): ContentType {\n if (mimeType) {\n if (mimeType === 'text/html') return 'html';\n if (mimeType === 'text/markdown') return 'markdown';\n if (mimeType === 'application/json') return 'json';\n if (mimeType.startsWith('text/')) return 'text';\n return 'binary';\n }\n\n const contentStr = content.toString(\n 'utf8',\n 0,\n Math.min(content.length, 1000)\n );\n if (contentStr.startsWith('{') || contentStr.startsWith('[')) return 'json';\n if (contentStr.includes('<html>') || contentStr.includes('<!DOCTYPE'))\n return 'html';\n if (contentStr.includes('#') && contentStr.includes('\\n'))\n return 'markdown';\n\n return 'text';\n }\n\n private createContentPreview(\n content: Buffer,\n contentType: ContentType\n ): string {\n const maxLength = 200;\n let preview = content.toString(\n 'utf8',\n 0,\n Math.min(content.length, maxLength * 2)\n );\n\n if (contentType === 'html') {\n preview = preview\n .replace(/<[^>]*>/g, '')\n .replace(/\\s+/g, ' ')\n .trim();\n } else if (contentType === 'json') {\n try {\n const parsed = JSON.parse(preview);\n preview = JSON.stringify(parsed, null, 0);\n } catch {}\n }\n\n preview = preview.trim();\n if (preview.length > maxLength) {\n preview = preview.substring(0, maxLength) + '...';\n }\n\n return preview || '[Binary content]';\n }\n\n private updateStatsAfterStore(sizeBytes: number): void {\n this.referenceStats.activeReferences++;\n this.referenceStats.totalStorageBytes += sizeBytes;\n this.updateReferenceStorageStats();\n }\n\n private updateReferenceStorageStats(): void {\n if (this.referenceStats.activeReferences > 0) {\n this.referenceStats.averageContentSize =\n this.referenceStats.totalStorageBytes /\n this.referenceStats.activeReferences;\n }\n\n this.referenceStats.storageUtilization =\n (this.referenceStats.totalStorageBytes /\n this.referenceConfig.maxTotalStorageBytes) *\n 100;\n\n let mostAccessedId: ReferenceId | undefined;\n let maxAccess = 0;\n\n for (const [referenceId, storedContent] of this.contentStore.entries()) {\n if (storedContent.metadata.accessCount > maxAccess) {\n maxAccess = storedContent.metadata.accessCount;\n mostAccessedId = referenceId;\n }\n }\n\n if (mostAccessedId !== undefined) {\n this.referenceStats.mostAccessedReferenceId = mostAccessedId;\n } else {\n delete this.referenceStats.mostAccessedReferenceId;\n }\n }\n\n /**\n * Check if content is an image file based on MIME type or filename\n */\n private isImageContent(mimeType?: string, fileName?: string): boolean {\n if (mimeType && mimeType.startsWith('image/')) {\n return true;\n }\n\n if (fileName) {\n const lowerFileName = fileName.toLowerCase();\n const imageExtensions = [\n '.png',\n '.jpg',\n '.jpeg',\n '.gif',\n '.bmp',\n '.webp',\n '.svg',\n '.tiff',\n '.ico',\n ];\n return imageExtensions.some((ext) => lowerFileName.endsWith(ext));\n }\n\n return false;\n }\n\n private recordPerformanceMetric(\n type: 'creation' | 'resolution' | 'cleanup',\n timeMs: number\n ): void {\n const metrics = this.referenceStats.performanceMetrics;\n const maxRecords = 100;\n\n switch (type) {\n case 'creation':\n metrics.creationTimes.push(timeMs);\n if (metrics.creationTimes.length > maxRecords) {\n metrics.creationTimes.shift();\n }\n break;\n case 'resolution':\n metrics.resolutionTimes.push(timeMs);\n if (metrics.resolutionTimes.length > maxRecords) {\n metrics.resolutionTimes.shift();\n }\n break;\n case 'cleanup':\n metrics.cleanupTimes.push(timeMs);\n if (metrics.cleanupTimes.length > maxRecords) {\n metrics.cleanupTimes.shift();\n }\n break;\n }\n }\n\n private calculateAverage(times: number[]): number {\n if (times.length === 0) return 0;\n return times.reduce((sum, time) => sum + time, 0) / times.length;\n }\n\n private startReferenceCleanupTimer(): void {\n this.cleanupTimer = setInterval(async () => {\n try {\n await this.performCleanup();\n } catch {}\n }, this.referenceConfig.cleanupIntervalMs);\n }\n\n /**\n * Clean up resources (enhanced to include reference cleanup)\n */\n async dispose(): Promise<void> {\n if (this.cleanupTimer) {\n clearInterval(this.cleanupTimer);\n delete this.cleanupTimer;\n }\n\n this.contentStore.clear();\n\n this.clear();\n }\n}\n"],"names":[],"mappings":";;AAuFO,MAAM,kBAAN,MAAM,gBAAgD;AAAA,EAkB3D,YACE,aAAqB,gBAAe,qBACpC,iBACA;AApBF,SAAQ,WAA4B,CAAA;AAEpC,SAAQ,YAAoB;AAE5B,SAAQ,mCAAoD,IAAA;AAiB1D,SAAK,aAAa;AAElB,SAAK,kBAAkB;AAAA,MACrB,GAAG;AAAA,MACH,GAAG;AAAA,IAAA;AAEL,SAAK,iBAAiB;AAAA,MACpB,kBAAkB;AAAA,MAClB,mBA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aAAa,KAAK,MAAM;AAChC,YAAI,QAAQ,aAAa,SAAS,YAAY;AAC5C,kBAAQ,aAAa,MAAA;AAAA,QACvB;AACA;AAAA,IAAA;AAAA,EAEN;AAAA,EAEQ,iBAAiB,OAAyB;AAChD,QAAI,MAAM,WAAW,EAAG,QAAO;AAC/B,WAAO,MAAM,OAAO,CAAC,KAAK,SAAS,MAAM,MAAM,CAAC,IAAI,MAAM;AAAA,EAC5D;AAAA,EAEQ,6BAAmC;AACzC,SAAK,eAAe,YAAY,YAAY;AAC1C,UAAI;AACF,cAAM,KAAK,eAAA;AAAA,MACb,QAAQ;AAAA,MAAC;AAAA,IACX,GAAG,KAAK,gBAAgB,iBAAiB;AAAA,EAC3C;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,UAAyB;AAC7B,QAAI,KAAK,cAAc;AACrB,oBAAc,KAAK,YAAY;AAC/B,aAAO,KAAK;AAAA,IACd;AAEA,SAAK,aAAa,MAAA;AAElB,SAAK,MAAA;AAAA,EACP;AACF;AAh6BE,gBAAuB,sBAAsB;AAhBxC,IAAM,iBAAN;"}
|
package/dist/esm/index23.js
CHANGED
|
@@ -1,327 +1,68 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
import { ENTITY_PATTERNS } from "./index43.js";
|
|
4
|
-
import "hedera-agent-kit";
|
|
5
|
-
import "@hashgraphonline/standards-agent-kit";
|
|
6
|
-
import "./index13.js";
|
|
7
|
-
import "./index37.js";
|
|
8
|
-
import "@langchain/core/tools";
|
|
9
|
-
import "zod";
|
|
10
|
-
import "./index6.js";
|
|
11
|
-
import "langchain/agents";
|
|
12
|
-
import "zod-to-json-schema";
|
|
13
|
-
import "./index12.js";
|
|
14
|
-
import "@langchain/core/prompts";
|
|
15
|
-
import "@modelcontextprotocol/sdk/client/index.js";
|
|
16
|
-
import "@modelcontextprotocol/sdk/client/stdio.js";
|
|
17
|
-
import "./index18.js";
|
|
18
|
-
import "@langchain/core/messages";
|
|
19
|
-
import "./index19.js";
|
|
20
|
-
import "./index20.js";
|
|
21
|
-
import "./index21.js";
|
|
22
|
-
import "crypto";
|
|
23
|
-
import { EntityFormat } from "./index26.js";
|
|
24
|
-
import "./index28.js";
|
|
25
|
-
import "./index34.js";
|
|
26
|
-
class EntityResolver {
|
|
27
|
-
constructor(config) {
|
|
28
|
-
this.llm = new ChatOpenAI({
|
|
29
|
-
apiKey: config.apiKey,
|
|
30
|
-
modelName: config.modelName || "gpt-4o-mini",
|
|
31
|
-
temperature: 0
|
|
32
|
-
});
|
|
33
|
-
this.logger = new Logger({ module: "EntityResolver" });
|
|
34
|
-
}
|
|
1
|
+
import { createHash } from "crypto";
|
|
2
|
+
class ReferenceIdGenerator {
|
|
35
3
|
/**
|
|
36
|
-
*
|
|
4
|
+
* Generate a content-based reference ID using SHA-256 hashing
|
|
5
|
+
*
|
|
6
|
+
* @param content The content to generate a reference ID for
|
|
7
|
+
* @returns Deterministic reference ID based on content hash
|
|
37
8
|
*/
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
const byType = entities.reduce((acc, e) => {
|
|
43
|
-
if (!acc[e.entityType]) acc[e.entityType] = [];
|
|
44
|
-
acc[e.entityType].push(e);
|
|
45
|
-
return acc;
|
|
46
|
-
}, {});
|
|
47
|
-
try {
|
|
48
|
-
const stats = Object.fromEntries(
|
|
49
|
-
Object.entries(byType).map(([type, list]) => [
|
|
50
|
-
type,
|
|
51
|
-
{
|
|
52
|
-
count: list.length,
|
|
53
|
-
mostRecent: list[0]?.entityId
|
|
54
|
-
}
|
|
55
|
-
])
|
|
56
|
-
);
|
|
57
|
-
this.logger.info("resolveReferences: input summary", {
|
|
58
|
-
messagePreview: message.substring(0, 200),
|
|
59
|
-
entityStats: stats
|
|
60
|
-
});
|
|
61
|
-
} catch {
|
|
62
|
-
}
|
|
63
|
-
let context = "Available entities in memory:\n";
|
|
64
|
-
for (const [type, list] of Object.entries(byType)) {
|
|
65
|
-
const recent = list[0];
|
|
66
|
-
context += `Most recent ${type}: "${recent.entityName}" = ${recent.entityId}
|
|
67
|
-
`;
|
|
68
|
-
if (list.length > 1) {
|
|
69
|
-
context += ` (${list.length - 1} other ${type}s in memory)
|
|
70
|
-
`;
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
const prompt = `Task: Replace entity references with their IDs from memory. STRICT TYPE RULES:
|
|
74
|
-
|
|
75
|
-
- For phrases referring to "${ENTITY_PATTERNS.TOKEN_REFERENCE}" or actions that clearly require a token (create/mint/airdrop/associate/etc.), resolve to the most recent TOKEN entity ID (never a topic or account).
|
|
76
|
-
- For phrases referring to "${ENTITY_PATTERNS.TOPIC_REFERENCE}" or actions that clearly require a topic (inscribe/publish/consensus/etc.), resolve to the most recent TOPIC entity ID (never a token or account).
|
|
77
|
-
- Do not infer or invent entity IDs. Only use those present in the provided context.
|
|
78
|
-
|
|
79
|
-
${context}
|
|
80
|
-
|
|
81
|
-
User message: "${message}"
|
|
82
|
-
|
|
83
|
-
Instructions:
|
|
84
|
-
- If the user says "${ENTITY_PATTERNS.TOPIC_REFERENCE}" or "that topic" → replace with the most recent topic ID
|
|
85
|
-
- If the user says "${ENTITY_PATTERNS.TOKEN_REFERENCE}" or "that token" → replace with the most recent token ID (never a topic)
|
|
86
|
-
- If the user says "it" or "that" after an action verb → replace with the most recent entity ID
|
|
87
|
-
- Examples:
|
|
88
|
-
* "submit on ${ENTITY_PATTERNS.TOPIC_REFERENCE}" → "submit on 0.0.6543472"
|
|
89
|
-
* "airdrop ${ENTITY_PATTERNS.TOKEN_REFERENCE}" → "airdrop 0.0.123456"
|
|
90
|
-
* "send a message to it" → "send a message to 0.0.6543472"
|
|
91
|
-
|
|
92
|
-
Return ONLY the message with replacements made. Do not add any explanations.
|
|
93
|
-
Resolved message:`;
|
|
94
|
-
try {
|
|
95
|
-
const response = await this.llm.invoke(prompt);
|
|
96
|
-
const resolved = response.content.trim();
|
|
97
|
-
const changed = resolved !== message;
|
|
98
|
-
try {
|
|
99
|
-
this.logger.info("resolveReferences: resolution result", {
|
|
100
|
-
changed,
|
|
101
|
-
hasEntityId: /\b0\.0\.\d+\b/.test(resolved),
|
|
102
|
-
resolvedPreview: resolved.substring(0, 200)
|
|
103
|
-
});
|
|
104
|
-
} catch {
|
|
105
|
-
}
|
|
106
|
-
if (changed && resolved.includes("0.0.")) {
|
|
107
|
-
return resolved;
|
|
108
|
-
}
|
|
109
|
-
return message;
|
|
110
|
-
} catch {
|
|
111
|
-
return message;
|
|
112
|
-
}
|
|
9
|
+
static generateId(content) {
|
|
10
|
+
const hash = createHash("sha256");
|
|
11
|
+
hash.update(content);
|
|
12
|
+
return hash.digest("hex");
|
|
113
13
|
}
|
|
114
14
|
/**
|
|
115
|
-
*
|
|
15
|
+
* Validate that a string is a properly formatted reference ID
|
|
16
|
+
*
|
|
17
|
+
* @param id The ID to validate
|
|
18
|
+
* @returns true if the ID is valid format
|
|
116
19
|
*/
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
return receiptEntities;
|
|
121
|
-
}
|
|
122
|
-
return this.extractWithLLM(response, userMessage);
|
|
123
|
-
}
|
|
124
|
-
/**
|
|
125
|
-
* Extract entities from transaction receipt data (primary method)
|
|
126
|
-
*/
|
|
127
|
-
extractFromReceipt(response, userMessage) {
|
|
128
|
-
const entities = [];
|
|
129
|
-
let parsedResponse;
|
|
130
|
-
try {
|
|
131
|
-
parsedResponse = typeof response === "string" ? JSON.parse(response) : response;
|
|
132
|
-
} catch {
|
|
133
|
-
parsedResponse = response;
|
|
134
|
-
}
|
|
135
|
-
if (!parsedResponse || parsedResponse.success === false) {
|
|
136
|
-
return entities;
|
|
137
|
-
}
|
|
138
|
-
const receipt = parsedResponse.receipt || parsedResponse.result?.receipt || parsedResponse.data?.receipt;
|
|
139
|
-
if (!receipt) {
|
|
140
|
-
return entities;
|
|
141
|
-
}
|
|
142
|
-
const entityName = this.extractNameFromMessage(userMessage);
|
|
143
|
-
const transactionId = parsedResponse.transactionId || parsedResponse.result?.transactionId || void 0;
|
|
144
|
-
const extractEntityId = (entityId) => {
|
|
145
|
-
if (typeof entityId === "string") {
|
|
146
|
-
return entityId;
|
|
147
|
-
}
|
|
148
|
-
if (entityId && typeof entityId === "object" && typeof entityId.toString === "function") {
|
|
149
|
-
if (entityId.toString !== Object.prototype.toString) {
|
|
150
|
-
return entityId.toString();
|
|
151
|
-
}
|
|
152
|
-
}
|
|
153
|
-
return String(entityId);
|
|
154
|
-
};
|
|
155
|
-
if (receipt.tokenId) {
|
|
156
|
-
const entity = {
|
|
157
|
-
id: extractEntityId(receipt.tokenId),
|
|
158
|
-
name: entityName,
|
|
159
|
-
type: EntityFormat.TOKEN_ID
|
|
160
|
-
};
|
|
161
|
-
if (transactionId) {
|
|
162
|
-
entity.transactionId = transactionId;
|
|
163
|
-
}
|
|
164
|
-
entities.push(entity);
|
|
165
|
-
}
|
|
166
|
-
if (receipt.topicId) {
|
|
167
|
-
const entity = {
|
|
168
|
-
id: extractEntityId(receipt.topicId),
|
|
169
|
-
name: entityName,
|
|
170
|
-
type: EntityFormat.TOPIC_ID
|
|
171
|
-
};
|
|
172
|
-
if (transactionId) {
|
|
173
|
-
entity.transactionId = transactionId;
|
|
174
|
-
}
|
|
175
|
-
entities.push(entity);
|
|
20
|
+
static isValidReferenceId(id) {
|
|
21
|
+
if (!id || typeof id !== "string") {
|
|
22
|
+
return false;
|
|
176
23
|
}
|
|
177
|
-
if (
|
|
178
|
-
|
|
179
|
-
id: extractEntityId(receipt.accountId),
|
|
180
|
-
name: entityName,
|
|
181
|
-
type: EntityFormat.ACCOUNT_ID
|
|
182
|
-
};
|
|
183
|
-
if (transactionId) {
|
|
184
|
-
entity.transactionId = transactionId;
|
|
185
|
-
}
|
|
186
|
-
entities.push(entity);
|
|
24
|
+
if (id.length !== 64) {
|
|
25
|
+
return false;
|
|
187
26
|
}
|
|
188
|
-
|
|
189
|
-
const entity = {
|
|
190
|
-
id: extractEntityId(receipt.contractId),
|
|
191
|
-
name: entityName,
|
|
192
|
-
type: EntityFormat.CONTRACT_ID
|
|
193
|
-
};
|
|
194
|
-
if (transactionId) {
|
|
195
|
-
entity.transactionId = transactionId;
|
|
196
|
-
}
|
|
197
|
-
entities.push(entity);
|
|
198
|
-
}
|
|
199
|
-
if (receipt.fileId) {
|
|
200
|
-
const entity = {
|
|
201
|
-
id: extractEntityId(receipt.fileId),
|
|
202
|
-
name: entityName,
|
|
203
|
-
type: EntityFormat.FILE_ID
|
|
204
|
-
};
|
|
205
|
-
if (transactionId) {
|
|
206
|
-
entity.transactionId = transactionId;
|
|
207
|
-
}
|
|
208
|
-
entities.push(entity);
|
|
209
|
-
}
|
|
210
|
-
if (receipt.scheduleId) {
|
|
211
|
-
const entity = {
|
|
212
|
-
id: extractEntityId(receipt.scheduleId),
|
|
213
|
-
name: entityName,
|
|
214
|
-
type: EntityFormat.SCHEDULE_ID
|
|
215
|
-
};
|
|
216
|
-
if (transactionId) {
|
|
217
|
-
entity.transactionId = transactionId;
|
|
218
|
-
}
|
|
219
|
-
entities.push(entity);
|
|
220
|
-
}
|
|
221
|
-
return entities;
|
|
222
|
-
}
|
|
223
|
-
/**
|
|
224
|
-
* Extract entity name from user message
|
|
225
|
-
*/
|
|
226
|
-
extractNameFromMessage(message) {
|
|
227
|
-
const quotedMatch = message.match(/"([^"]+)"/);
|
|
228
|
-
if (quotedMatch) return quotedMatch[1];
|
|
229
|
-
const calledMatch = message.match(/called\s+([A-Za-z0-9#\s_-]+?)(?:\s|$)/i);
|
|
230
|
-
if (calledMatch) return calledMatch[1].trim();
|
|
231
|
-
const forMatch = message.match(/for\s+([A-Za-z0-9#\s_-]+)/i);
|
|
232
|
-
if (forMatch) return forMatch[1].trim();
|
|
233
|
-
const namedMatch = message.match(
|
|
234
|
-
/(?:token|topic|account|contract)\s+([A-Za-z0-9#_-]+)/i
|
|
235
|
-
);
|
|
236
|
-
if (namedMatch) return namedMatch[1].trim();
|
|
237
|
-
if (message.includes("new account")) return "new account";
|
|
238
|
-
return "unnamed_entity";
|
|
27
|
+
return /^[a-f0-9]+$/.test(id);
|
|
239
28
|
}
|
|
240
29
|
/**
|
|
241
|
-
* Extract
|
|
30
|
+
* Extract reference ID from ref:// format
|
|
31
|
+
*
|
|
32
|
+
* @param input Input string that may contain a reference ID
|
|
33
|
+
* @returns Extracted reference ID or null if not found
|
|
242
34
|
*/
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
User asked: "${userMessage.substring(0, 200)}"
|
|
248
|
-
|
|
249
|
-
Agent response: ${text.substring(0, 3e3)}
|
|
250
|
-
|
|
251
|
-
CRITICAL: Only extract Hedera entity IDs in the format 0.0.XXXXX (shard.realm.number).
|
|
252
|
-
DO NOT extract:
|
|
253
|
-
- Token symbols (e.g., "FOREV", "USDC", "HBAR")
|
|
254
|
-
- Token names (e.g., "Forever", "My Token")
|
|
255
|
-
- Transaction IDs (format: 0.0.XXX@timestamp)
|
|
256
|
-
- Account aliases or mnemonics
|
|
257
|
-
|
|
258
|
-
Look for:
|
|
259
|
-
1. Success messages with entity IDs (e.g., "Successfully created topic 0.0.6543472")
|
|
260
|
-
2. Transaction confirmations that created new entities
|
|
261
|
-
3. Entity IDs that appear after words like "created", "new", "successfully"
|
|
262
|
-
|
|
263
|
-
DO NOT include:
|
|
264
|
-
- Token symbols or names (these are NOT entity IDs)
|
|
265
|
-
- Account IDs that already existed (like sender/receiver accounts)
|
|
266
|
-
- Entity IDs that were parameters to the operation
|
|
267
|
-
- Failed operations
|
|
268
|
-
- Anything that doesn't match the 0.0.XXXXX format
|
|
269
|
-
|
|
270
|
-
Return a JSON array of newly created entities:
|
|
271
|
-
[{"id": "0.0.XXX", "name": "descriptive_name", "type": "topic|token|account"}]
|
|
272
|
-
|
|
273
|
-
If no entities were created, return: []
|
|
274
|
-
|
|
275
|
-
JSON:`;
|
|
276
|
-
try {
|
|
277
|
-
const response2 = await this.llm.invoke(prompt);
|
|
278
|
-
const content = response2.content;
|
|
279
|
-
const match = content.match(/\[[\s\S]*?\]/);
|
|
280
|
-
if (match) {
|
|
281
|
-
const entities = JSON.parse(match[0]);
|
|
282
|
-
return entities;
|
|
283
|
-
}
|
|
284
|
-
} catch {
|
|
35
|
+
static extractReferenceId(input) {
|
|
36
|
+
if (!input || typeof input !== "string") {
|
|
37
|
+
return null;
|
|
285
38
|
}
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
* Validate that an entity matches the expected type
|
|
290
|
-
*/
|
|
291
|
-
validateEntityType(entityId, expectedType, entities) {
|
|
292
|
-
const stored = entities.find((e) => e.entityId === entityId);
|
|
293
|
-
return !!stored && stored.entityType === expectedType;
|
|
294
|
-
}
|
|
295
|
-
/**
|
|
296
|
-
* Resolve entity references with type validation
|
|
297
|
-
*/
|
|
298
|
-
async resolveWithTypeValidation(query, entities, expectedType) {
|
|
299
|
-
await this.resolveReferences(query, entities);
|
|
300
|
-
if (!expectedType) {
|
|
301
|
-
return entities;
|
|
39
|
+
const refFormatMatch = input.match(/^ref:\/\/([a-f0-9]{64})$/);
|
|
40
|
+
if (refFormatMatch) {
|
|
41
|
+
return refFormatMatch[1];
|
|
302
42
|
}
|
|
303
|
-
return
|
|
43
|
+
return this.isValidReferenceId(input) ? input : null;
|
|
304
44
|
}
|
|
305
45
|
/**
|
|
306
|
-
*
|
|
46
|
+
* Format a reference ID in the standard ref:// format
|
|
47
|
+
*
|
|
48
|
+
* @param referenceId The reference ID to format
|
|
49
|
+
* @returns Formatted reference string
|
|
307
50
|
*/
|
|
308
|
-
|
|
309
|
-
return
|
|
51
|
+
static formatReference(referenceId) {
|
|
52
|
+
return `ref://${referenceId}`;
|
|
310
53
|
}
|
|
311
54
|
/**
|
|
312
|
-
*
|
|
55
|
+
* Generate a test reference ID (for testing purposes only)
|
|
56
|
+
*
|
|
57
|
+
* @param testSeed A test seed to generate a fake but valid ID format
|
|
58
|
+
* @returns A valid format reference ID for testing
|
|
313
59
|
*/
|
|
314
|
-
|
|
315
|
-
const
|
|
316
|
-
|
|
317
|
-
);
|
|
318
|
-
if (filtered.length === 0) return null;
|
|
319
|
-
return filtered.reduce(
|
|
320
|
-
(most, current) => current.createdAt > most.createdAt ? current : most
|
|
321
|
-
);
|
|
60
|
+
static generateTestId(testSeed) {
|
|
61
|
+
const content = Buffer.from(`test-${testSeed}-${Date.now()}`);
|
|
62
|
+
return this.generateId(content);
|
|
322
63
|
}
|
|
323
64
|
}
|
|
324
65
|
export {
|
|
325
|
-
|
|
66
|
+
ReferenceIdGenerator
|
|
326
67
|
};
|
|
327
68
|
//# sourceMappingURL=index23.js.map
|
package/dist/esm/index23.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index23.js","sources":["../../src/services/entity-resolver.ts"],"sourcesContent":["import { ChatOpenAI } from '@langchain/openai';\nimport { Logger } from '@hashgraphonline/standards-sdk';\nimport type { EntityAssociation } from '../memory/smart-memory-manager';\nimport { ENTITY_PATTERNS } from '../constants';\nimport { EntityFormat } from '..';\n\nexport interface EntityResolverConfig {\n apiKey: string;\n modelName?: string;\n}\n\ninterface EntityIdValue {\n toString(): string;\n}\n\ninterface TransactionReceipt {\n tokenId?: EntityIdValue | string;\n topicId?: EntityIdValue | string;\n accountId?: EntityIdValue | string;\n contractId?: EntityIdValue | string;\n fileId?: EntityIdValue | string;\n scheduleId?: EntityIdValue | string;\n}\n\ninterface TransactionResponse {\n success?: boolean;\n receipt?: TransactionReceipt;\n result?: {\n receipt?: TransactionReceipt;\n transactionId?: string;\n };\n data?: {\n receipt?: TransactionReceipt;\n };\n transactionId?: string;\n}\n\ninterface ExtractedEntity {\n id: string;\n name: string;\n type: EntityFormat;\n transactionId?: string;\n}\n\n/**\n * LLM-based entity resolver that replaces brittle regex patterns\n */\nexport class EntityResolver {\n private llm: ChatOpenAI;\n private logger: Logger;\n\n constructor(config: EntityResolverConfig) {\n this.llm = new ChatOpenAI({\n apiKey: config.apiKey,\n modelName: config.modelName || 'gpt-4o-mini',\n temperature: 0,\n });\n this.logger = new Logger({ module: 'EntityResolver' });\n }\n\n /**\n * Resolve entity references using LLM instead of regex\n */\n async resolveReferences(\n message: string,\n entities: EntityAssociation[]\n ): Promise<string> {\n if (!entities || entities.length === 0) {\n return message;\n }\n\n const byType = entities.reduce((acc, e) => {\n if (!acc[e.entityType]) acc[e.entityType] = [];\n acc[e.entityType].push(e);\n return acc;\n }, {} as Record<string, EntityAssociation[]>);\n\n try {\n const stats = Object.fromEntries(\n Object.entries(byType).map(([type, list]) => [\n type,\n {\n count: list.length,\n mostRecent: list[0]?.entityId,\n },\n ])\n );\n this.logger.info('resolveReferences: input summary', {\n messagePreview: message.substring(0, 200),\n entityStats: stats,\n });\n } catch {}\n\n let context = 'Available entities in memory:\\n';\n for (const [type, list] of Object.entries(byType)) {\n const recent = list[0];\n context += `Most recent ${type}: \"${recent.entityName}\" = ${recent.entityId}\\n`;\n if (list.length > 1) {\n context += ` (${list.length - 1} other ${type}s in memory)\\n`;\n }\n }\n\n const prompt = `Task: Replace entity references with their IDs from memory. STRICT TYPE RULES:\n\n- For phrases referring to \"${ENTITY_PATTERNS.TOKEN_REFERENCE}\" or actions that clearly require a token (create/mint/airdrop/associate/etc.), resolve to the most recent TOKEN entity ID (never a topic or account).\n- For phrases referring to \"${ENTITY_PATTERNS.TOPIC_REFERENCE}\" or actions that clearly require a topic (inscribe/publish/consensus/etc.), resolve to the most recent TOPIC entity ID (never a token or account).\n- Do not infer or invent entity IDs. Only use those present in the provided context.\n\n${context}\n\nUser message: \"${message}\"\n\nInstructions:\n- If the user says \"${ENTITY_PATTERNS.TOPIC_REFERENCE}\" or \"that topic\" → replace with the most recent topic ID\n- If the user says \"${ENTITY_PATTERNS.TOKEN_REFERENCE}\" or \"that token\" → replace with the most recent token ID (never a topic)\n- If the user says \"it\" or \"that\" after an action verb → replace with the most recent entity ID\n- Examples:\n * \"submit on ${ENTITY_PATTERNS.TOPIC_REFERENCE}\" → \"submit on 0.0.6543472\"\n * \"airdrop ${ENTITY_PATTERNS.TOKEN_REFERENCE}\" → \"airdrop 0.0.123456\"\n * \"send a message to it\" → \"send a message to 0.0.6543472\"\n\nReturn ONLY the message with replacements made. Do not add any explanations.\nResolved message:`;\n\n try {\n const response = await this.llm.invoke(prompt);\n const resolved = (response.content as string).trim();\n\n const changed = resolved !== message;\n try {\n this.logger.info('resolveReferences: resolution result', {\n changed,\n hasEntityId: /\\b0\\.0\\.\\d+\\b/.test(resolved),\n resolvedPreview: resolved.substring(0, 200),\n });\n } catch {}\n\n if (changed && resolved.includes('0.0.')) {\n return resolved;\n }\n\n return message;\n } catch {\n return message;\n }\n }\n\n /**\n * Extract entities from agent response using receipt data (preferred) or LLM fallback\n */\n async extractEntities(\n response: unknown,\n userMessage: string\n ): Promise<ExtractedEntity[]> {\n const receiptEntities = this.extractFromReceipt(response, userMessage);\n if (receiptEntities.length > 0) {\n return receiptEntities;\n }\n\n return this.extractWithLLM(response, userMessage);\n }\n\n /**\n * Extract entities from transaction receipt data (primary method)\n */\n private extractFromReceipt(\n response: unknown,\n userMessage: string\n ): ExtractedEntity[] {\n const entities: ExtractedEntity[] = [];\n\n let parsedResponse: TransactionResponse;\n try {\n parsedResponse =\n typeof response === 'string'\n ? JSON.parse(response)\n : (response as TransactionResponse);\n } catch {\n parsedResponse = response as TransactionResponse;\n }\n\n if (!parsedResponse || parsedResponse.success === false) {\n return entities;\n }\n\n const receipt =\n parsedResponse.receipt ||\n parsedResponse.result?.receipt ||\n parsedResponse.data?.receipt;\n\n if (!receipt) {\n return entities;\n }\n\n const entityName = this.extractNameFromMessage(userMessage);\n\n const transactionId =\n parsedResponse.transactionId ||\n parsedResponse.result?.transactionId ||\n undefined;\n\n const extractEntityId = (entityId: EntityIdValue | string): string => {\n if (typeof entityId === 'string') {\n return entityId;\n }\n if (\n entityId &&\n typeof entityId === 'object' &&\n typeof entityId.toString === 'function'\n ) {\n if (entityId.toString !== Object.prototype.toString) {\n return entityId.toString();\n }\n }\n return String(entityId);\n };\n\n if (receipt.tokenId) {\n const entity: ExtractedEntity = {\n id: extractEntityId(receipt.tokenId),\n name: entityName,\n type: EntityFormat.TOKEN_ID,\n };\n if (transactionId) {\n entity.transactionId = transactionId;\n }\n entities.push(entity);\n }\n\n if (receipt.topicId) {\n const entity: ExtractedEntity = {\n id: extractEntityId(receipt.topicId),\n name: entityName,\n type: EntityFormat.TOPIC_ID,\n };\n if (transactionId) {\n entity.transactionId = transactionId;\n }\n entities.push(entity);\n }\n\n if (receipt.accountId) {\n const entity: ExtractedEntity = {\n id: extractEntityId(receipt.accountId),\n name: entityName,\n type: EntityFormat.ACCOUNT_ID,\n };\n if (transactionId) {\n entity.transactionId = transactionId;\n }\n entities.push(entity);\n }\n\n if (receipt.contractId) {\n const entity: ExtractedEntity = {\n id: extractEntityId(receipt.contractId),\n name: entityName,\n type: EntityFormat.CONTRACT_ID,\n };\n if (transactionId) {\n entity.transactionId = transactionId;\n }\n entities.push(entity);\n }\n\n if (receipt.fileId) {\n const entity: ExtractedEntity = {\n id: extractEntityId(receipt.fileId),\n name: entityName,\n type: EntityFormat.FILE_ID,\n };\n if (transactionId) {\n entity.transactionId = transactionId;\n }\n entities.push(entity);\n }\n\n if (receipt.scheduleId) {\n const entity: ExtractedEntity = {\n id: extractEntityId(receipt.scheduleId),\n name: entityName,\n type: EntityFormat.SCHEDULE_ID,\n };\n if (transactionId) {\n entity.transactionId = transactionId;\n }\n entities.push(entity);\n }\n\n return entities;\n }\n\n /**\n * Extract entity name from user message\n */\n private extractNameFromMessage(message: string): string {\n const quotedMatch = message.match(/\"([^\"]+)\"/);\n if (quotedMatch) return quotedMatch[1];\n\n const calledMatch = message.match(/called\\s+([A-Za-z0-9#\\s_-]+?)(?:\\s|$)/i);\n if (calledMatch) return calledMatch[1].trim();\n\n const forMatch = message.match(/for\\s+([A-Za-z0-9#\\s_-]+)/i);\n if (forMatch) return forMatch[1].trim();\n\n const namedMatch = message.match(\n /(?:token|topic|account|contract)\\s+([A-Za-z0-9#_-]+)/i\n );\n if (namedMatch) return namedMatch[1].trim();\n\n if (message.includes('new account')) return 'new account';\n\n return 'unnamed_entity';\n }\n\n /**\n * Extract entities using LLM (fallback method)\n */\n private async extractWithLLM(\n response: unknown,\n userMessage: string\n ): Promise<ExtractedEntity[]> {\n const text =\n typeof response === 'string' ? response : JSON.stringify(response);\n\n const prompt = `Analyze this agent response and extract ONLY newly created entities.\n\nUser asked: \"${userMessage.substring(0, 200)}\"\n\nAgent response: ${text.substring(0, 3000)}\n\nCRITICAL: Only extract Hedera entity IDs in the format 0.0.XXXXX (shard.realm.number).\nDO NOT extract:\n- Token symbols (e.g., \"FOREV\", \"USDC\", \"HBAR\")\n- Token names (e.g., \"Forever\", \"My Token\")\n- Transaction IDs (format: 0.0.XXX@timestamp)\n- Account aliases or mnemonics\n\nLook for:\n1. Success messages with entity IDs (e.g., \"Successfully created topic 0.0.6543472\")\n2. Transaction confirmations that created new entities\n3. Entity IDs that appear after words like \"created\", \"new\", \"successfully\"\n\nDO NOT include:\n- Token symbols or names (these are NOT entity IDs)\n- Account IDs that already existed (like sender/receiver accounts)\n- Entity IDs that were parameters to the operation\n- Failed operations\n- Anything that doesn't match the 0.0.XXXXX format\n\nReturn a JSON array of newly created entities:\n[{\"id\": \"0.0.XXX\", \"name\": \"descriptive_name\", \"type\": \"topic|token|account\"}]\n\nIf no entities were created, return: []\n\nJSON:`;\n\n try {\n const response = await this.llm.invoke(prompt);\n const content = response.content as string;\n const match = content.match(/\\[[\\s\\S]*?\\]/);\n if (match) {\n const entities = JSON.parse(match[0]);\n return entities;\n }\n } catch {}\n return [];\n }\n\n /**\n * Validate that an entity matches the expected type\n */\n validateEntityType(\n entityId: string,\n expectedType: string,\n entities: EntityAssociation[]\n ): boolean {\n const stored = entities.find((e) => e.entityId === entityId);\n return !!stored && stored.entityType === expectedType;\n }\n\n /**\n * Resolve entity references with type validation\n */\n async resolveWithTypeValidation(\n query: string,\n entities: EntityAssociation[],\n expectedType?: string\n ): Promise<EntityAssociation[]> {\n await this.resolveReferences(query, entities);\n\n if (!expectedType) {\n return entities;\n }\n\n return entities.filter((entity) => entity.entityType === expectedType);\n }\n\n /**\n * Get entities filtered by type\n */\n getEntitiesByType(\n entities: EntityAssociation[],\n entityType: string\n ): EntityAssociation[] {\n return entities.filter((entity) => entity.entityType === entityType);\n }\n\n /**\n * Find the most recent entity of a specific type\n */\n getMostRecentEntityByType(\n entities: EntityAssociation[],\n entityType: string\n ): EntityAssociation | null {\n const filtered = entities.filter(\n (entity) => entity.entityType === entityType\n );\n if (filtered.length === 0) return null;\n\n return filtered.reduce((most, current) =>\n current.createdAt > most.createdAt ? current : most\n );\n }\n}\n"],"names":["response"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA+CO,MAAM,eAAe;AAAA,EAI1B,YAAY,QAA8B;AACxC,SAAK,MAAM,IAAI,WAAW;AAAA,MACxB,QAAQ,OAAO;AAAA,MACf,WAAW,OAAO,aAAa;AAAA,MAC/B,aAAa;AAAA,IAAA,CACd;AACD,SAAK,SAAS,IAAI,OAAO,EAAE,QAAQ,kBAAkB;AAAA,EACvD;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,kBACJ,SACA,UACiB;AACjB,QAAI,CAAC,YAAY,SAAS,WAAW,GAAG;AACtC,aAAO;AAAA,IACT;AAEA,UAAM,SAAS,SAAS,OAAO,CAAC,KAAK,MAAM;AACzC,UAAI,CAAC,IAAI,EAAE,UAAU,EAAG,KAAI,EAAE,UAAU,IAAI,CAAA;AAC5C,UAAI,EAAE,UAAU,EAAE,KAAK,CAAC;AACxB,aAAO;AAAA,IACT,GAAG,CAAA,CAAyC;AAE5C,QAAI;AACF,YAAM,QAAQ,OAAO;AAAA,QACnB,OAAO,QAAQ,MAAM,EAAE,IAAI,CAAC,CAAC,MAAM,IAAI,MAAM;AAAA,UAC3C;AAAA,UACA;AAAA,YACE,OAAO,KAAK;AAAA,YACZ,YAAY,KAAK,CAAC,GAAG;AAAA,UAAA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Ac;AACjB,aAAO;AAAA,IACT;AAEA,WAAO,SAAS,OAAO,CAAC,WAAW,OAAO,eAAe,YAAY;AAAA,EACvE;AAAA;AAAA;AAAA;AAAA,EAKA,kBACE,UACA,YACqB;AACrB,WAAO,SAAS,OAAO,CAAC,WAAW,OAAO,eAAe,UAAU;AAAA,EACrE;AAAA;AAAA;AAAA;AAAA,EAKA,0BACE,UACA,YAC0B;AAC1B,UAAM,WAAW,SAAS;AAAA,MACxB,CAAC,WAAW,OAAO,eAAe;AAAA,IAAA;AAEpC,QAAI,SAAS,WAAW,EAAG,QAAO;AAElC,WAAO,SAAS;AAAA,MAAO,CAAC,MAAM,YAC5B,QAAQ,YAAY,KAAK,YAAY,UAAU;AAAA,IAAA;AAAA,EAEnD;AACF;"}
|
|
1
|
+
{"version":3,"file":"index23.js","sources":["../../src/memory/reference-id-generator.ts"],"sourcesContent":["import { createHash } from 'crypto';\nimport { ReferenceId } from '../types/content-reference';\n\n/**\n * Content-based reference ID generator using SHA-256 (HCS-1 style)\n * \n * Generates deterministic reference IDs based on content hashing.\n * Same content always produces the same reference ID.\n */\nexport class ReferenceIdGenerator {\n /**\n * Generate a content-based reference ID using SHA-256 hashing\n * \n * @param content The content to generate a reference ID for\n * @returns Deterministic reference ID based on content hash\n */\n static generateId(content: Buffer): ReferenceId {\n const hash = createHash('sha256');\n hash.update(content);\n return hash.digest('hex');\n }\n \n /**\n * Validate that a string is a properly formatted reference ID\n * \n * @param id The ID to validate\n * @returns true if the ID is valid format\n */\n static isValidReferenceId(id: string): id is ReferenceId {\n if (!id || typeof id !== 'string') {\n return false;\n }\n \n if (id.length !== 64) {\n return false;\n }\n \n return /^[a-f0-9]+$/.test(id);\n }\n \n /**\n * Extract reference ID from ref:// format\n * \n * @param input Input string that may contain a reference ID\n * @returns Extracted reference ID or null if not found\n */\n static extractReferenceId(input: string): ReferenceId | null {\n if (!input || typeof input !== 'string') {\n return null;\n }\n \n const refFormatMatch = input.match(/^ref:\\/\\/([a-f0-9]{64})$/);\n if (refFormatMatch) {\n return refFormatMatch[1] as ReferenceId;\n }\n \n return this.isValidReferenceId(input) ? input : null;\n }\n \n /**\n * Format a reference ID in the standard ref:// format\n * \n * @param referenceId The reference ID to format\n * @returns Formatted reference string\n */\n static formatReference(referenceId: ReferenceId): string {\n return `ref://${referenceId}`;\n }\n \n /**\n * Generate a test reference ID (for testing purposes only)\n * \n * @param testSeed A test seed to generate a fake but valid ID format\n * @returns A valid format reference ID for testing\n */\n static generateTestId(testSeed: string): ReferenceId {\n const content = Buffer.from(`test-${testSeed}-${Date.now()}`);\n return this.generateId(content);\n }\n}"],"names":[],"mappings":";AASO,MAAM,qBAAqB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOhC,OAAO,WAAW,SAA8B;AAC9C,UAAM,OAAO,WAAW,QAAQ;AAChC,SAAK,OAAO,OAAO;AACnB,WAAO,KAAK,OAAO,KAAK;AAAA,EAC1B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,OAAO,mBAAmB,IAA+B;AACvD,QAAI,CAAC,MAAM,OAAO,OAAO,UAAU;AACjC,aAAO;AAAA,IACT;AAEA,QAAI,GAAG,WAAW,IAAI;AACpB,aAAO;AAAA,IACT;AAEA,WAAO,cAAc,KAAK,EAAE;AAAA,EAC9B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,OAAO,mBAAmB,OAAmC;AAC3D,QAAI,CAAC,SAAS,OAAO,UAAU,UAAU;AACvC,aAAO;AAAA,IACT;AAEA,UAAM,iBAAiB,MAAM,MAAM,0BAA0B;AAC7D,QAAI,gBAAgB;AAClB,aAAO,eAAe,CAAC;AAAA,IACzB;AAEA,WAAO,KAAK,mBAAmB,KAAK,IAAI,QAAQ;AAAA,EAClD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,OAAO,gBAAgB,aAAkC;AACvD,WAAO,SAAS,WAAW;AAAA,EAC7B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,OAAO,eAAe,UAA+B;AACnD,UAAM,UAAU,OAAO,KAAK,QAAQ,QAAQ,IAAI,KAAK,IAAA,CAAK,EAAE;AAC5D,WAAO,KAAK,WAAW,OAAO;AAAA,EAChC;AACF;"}
|