@hashgraphonline/conversational-agent 0.2.107 → 0.2.110

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.
Files changed (52) hide show
  1. package/README.md +64 -27
  2. package/dist/cjs/config/system-message.d.ts +1 -1
  3. package/dist/cjs/conversational-agent.d.ts +16 -0
  4. package/dist/cjs/core/tool-registry.d.ts +26 -0
  5. package/dist/cjs/index.cjs +1 -1
  6. package/dist/cjs/index.cjs.map +1 -1
  7. package/dist/cjs/mcp/types.d.ts +1 -1
  8. package/dist/cjs/services/attachment-processor.d.ts +1 -2
  9. package/dist/cjs/services/content-store-manager.d.ts +1 -1
  10. package/dist/cjs/services/formatters/types.d.ts +3 -1
  11. package/dist/cjs/services/index.d.ts +1 -1
  12. package/dist/esm/index15.js +2 -2
  13. package/dist/esm/index15.js.map +1 -1
  14. package/dist/esm/index2.js +33 -39
  15. package/dist/esm/index2.js.map +1 -1
  16. package/dist/esm/index21.js.map +1 -1
  17. package/dist/esm/index23.js +2 -2
  18. package/dist/esm/index24.js.map +1 -1
  19. package/dist/esm/index26.js.map +1 -1
  20. package/dist/esm/index30.js.map +1 -1
  21. package/dist/esm/index4.js +1 -1
  22. package/dist/esm/index4.js.map +1 -1
  23. package/dist/esm/index40.js +2 -2
  24. package/dist/esm/index40.js.map +1 -1
  25. package/dist/esm/index43.js +52 -1
  26. package/dist/esm/index43.js.map +1 -1
  27. package/dist/esm/index47.js +1 -1
  28. package/dist/esm/index47.js.map +1 -1
  29. package/dist/esm/index6.js +75 -17
  30. package/dist/esm/index6.js.map +1 -1
  31. package/dist/types/config/system-message.d.ts +1 -1
  32. package/dist/types/conversational-agent.d.ts +16 -0
  33. package/dist/types/core/tool-registry.d.ts +26 -0
  34. package/dist/types/mcp/types.d.ts +1 -1
  35. package/dist/types/services/attachment-processor.d.ts +1 -2
  36. package/dist/types/services/content-store-manager.d.ts +1 -1
  37. package/dist/types/services/formatters/types.d.ts +3 -1
  38. package/dist/types/services/index.d.ts +1 -1
  39. package/package.json +12 -10
  40. package/src/config/system-message.ts +3 -3
  41. package/src/conversational-agent.ts +164 -56
  42. package/src/core/tool-registry.ts +61 -0
  43. package/src/mcp/mcp-client-manager.ts +2 -2
  44. package/src/mcp/types.ts +1 -1
  45. package/src/memory/content-storage.ts +19 -6
  46. package/src/plugins/hbar/AccountBuilder.ts +1 -1
  47. package/src/plugins/hcs-10/HCS10Plugin.ts +50 -52
  48. package/src/plugins/inscribe/InscribePlugin.ts +1 -1
  49. package/src/services/attachment-processor.ts +1 -1
  50. package/src/services/content-store-manager.ts +1 -1
  51. package/src/services/formatters/types.ts +3 -1
  52. package/src/services/index.ts +1 -1
@@ -1,4 +1,4 @@
1
- import { Tool } from '@modelcontextprotocol/sdk/types.js';
1
+ import { Tool } from '@modelcontextprotocol/sdk/types';
2
2
 
3
3
  export interface MCPServerConfig {
4
4
  name: string;
@@ -6,7 +6,7 @@ export interface AttachmentData {
6
6
  type: string;
7
7
  size: number;
8
8
  }
9
- type ContentStoreManager = PackageContentStoreManager;
9
+ export type ContentStoreManager = PackageContentStoreManager;
10
10
  /**
11
11
  * Utility for processing file attachments and content references
12
12
  */
@@ -38,4 +38,3 @@ export declare class AttachmentProcessor {
38
38
  */
39
39
  private formatFileSize;
40
40
  }
41
- export {};
@@ -19,7 +19,7 @@ export declare class ContentStoreManager {
19
19
  private adapter;
20
20
  private resolver;
21
21
  private logger;
22
- private isRegistered;
22
+ protected isRegistered: boolean;
23
23
  constructor(maxMessageStorage?: number, referenceConfig?: Partial<ContentReferenceConfig>, logger?: Logger);
24
24
  /**
25
25
  * Initialize and register content storage for cross-package access
@@ -1,3 +1,5 @@
1
+ import { NetworkType } from '@hashgraphonline/standards-sdk';
2
+
1
3
  export declare enum EntityFormat {
2
4
  TOPIC_ID = "topicId",
3
5
  HRL = "hrl",
@@ -15,7 +17,7 @@ export declare enum EntityFormat {
15
17
  ANY = "any"
16
18
  }
17
19
  export interface ConversionContext {
18
- networkType?: string;
20
+ networkType?: NetworkType;
19
21
  sessionId?: string;
20
22
  toolName?: string;
21
23
  toolPreferences?: Record<string, string>;
@@ -2,4 +2,4 @@ export * from './entity-resolver';
2
2
  export * from './content-store-manager';
3
3
  export * from './formatters';
4
4
  export * from './parameter-service';
5
- export * from './attachment-processor';
5
+ export { AttachmentProcessor, type AttachmentData } from './attachment-processor';
@@ -1,5 +1,5 @@
1
- import { Client } from "@modelcontextprotocol/sdk/client/index.js";
2
- import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
1
+ import { Client } from "@modelcontextprotocol/sdk/client/index";
2
+ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio";
3
3
  import { MCPContentProcessor } from "./index16.js";
4
4
  class MCPClientManager {
5
5
  constructor(logger, contentStorage) {
@@ -1 +1 @@
1
- {"version":3,"file":"index15.js","sources":["../../src/mcp/mcp-client-manager.ts"],"sourcesContent":["import { Client } from '@modelcontextprotocol/sdk/client/index.js';\nimport { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';\nimport type { MCPServerConfig, MCPToolInfo, MCPConnectionStatus } from './types';\nimport { Logger } from '@hashgraphonline/standards-sdk';\nimport type { ContentStorage } from '../memory/content-storage';\nimport { MCPContentProcessor } from './content-processor';\n\n/**\n * Manages connections to MCP servers and tool discovery\n */\nexport class MCPClientManager {\n private clients: Map<string, Client> = new Map();\n private tools: Map<string, MCPToolInfo[]> = new Map();\n private logger: Logger;\n private contentProcessor?: MCPContentProcessor;\n\n constructor(logger: Logger, contentStorage?: ContentStorage) {\n this.logger = logger;\n if (contentStorage) {\n this.contentProcessor = new MCPContentProcessor(contentStorage, logger);\n }\n }\n\n /**\n * Connect to an MCP server and discover its tools\n */\n async connectServer(config: MCPServerConfig): Promise<MCPConnectionStatus> {\n try {\n if (this.isServerConnected(config.name)) {\n return {\n serverName: config.name,\n connected: false,\n error: `Server ${config.name} is already connected`,\n tools: [],\n };\n }\n\n if (config.transport && config.transport !== 'stdio') {\n throw new Error(`Transport ${config.transport} not yet supported`);\n }\n\n const transport = new StdioClientTransport({\n command: config.command,\n args: config.args,\n ...(config.env && { env: config.env }),\n });\n\n const client = new Client({\n name: `conversational-agent-${config.name}`,\n version: '1.0.0',\n }, {\n capabilities: {},\n });\n\n await client.connect(transport);\n this.clients.set(config.name, client);\n\n const toolsResponse = await client.listTools();\n const toolsWithServer: MCPToolInfo[] = toolsResponse.tools.map(tool => ({\n ...tool,\n serverName: config.name,\n }));\n\n this.tools.set(config.name, toolsWithServer);\n this.logger.info(`Connected to MCP server ${config.name} with ${toolsWithServer.length} tools`);\n\n return {\n serverName: config.name,\n connected: true,\n tools: toolsWithServer,\n };\n } catch (error) {\n this.logger.error(`Failed to connect to MCP server ${config.name}:`, error);\n return {\n serverName: config.name,\n connected: false,\n error: error instanceof Error ? error.message : 'Unknown error',\n tools: [],\n };\n }\n }\n\n /**\n * Execute a tool on a specific MCP server\n */\n async executeTool(serverName: string, toolName: string, args: Record<string, unknown>): Promise<unknown> {\n const client = this.clients.get(serverName);\n if (!client) {\n throw new Error(`MCP server ${serverName} not connected`);\n }\n\n this.logger.debug(`Executing MCP tool ${toolName} on server ${serverName}`, args);\n\n try {\n const result = await client.callTool({\n name: toolName,\n arguments: args,\n });\n\n if (this.contentProcessor) {\n const processed = await this.contentProcessor.processResponse(result, serverName, toolName);\n \n if (processed.wasProcessed) {\n this.logger.debug(\n `Processed MCP response from ${serverName}::${toolName}`,\n {\n referenceCreated: processed.referenceCreated,\n originalSize: processed.originalSize,\n errors: processed.errors\n }\n );\n\n if (processed.errors && processed.errors.length > 0) {\n this.logger.warn(`Content processing warnings for ${serverName}::${toolName}:`, processed.errors);\n }\n }\n\n return processed.content;\n }\n\n return result;\n } catch (error) {\n this.logger.error(`Error executing MCP tool ${toolName}:`, error);\n throw error;\n }\n }\n\n /**\n * Disconnect all MCP servers\n */\n async disconnectAll(): Promise<void> {\n for (const [name, client] of this.clients) {\n try {\n await client.close();\n this.logger.info(`Disconnected from MCP server ${name}`);\n } catch (error) {\n this.logger.error(`Error disconnecting MCP server ${name}:`, error);\n }\n }\n this.clients.clear();\n this.tools.clear();\n }\n\n /**\n * Get all discovered tools from all connected servers\n */\n getAllTools(): MCPToolInfo[] {\n const allTools: MCPToolInfo[] = [];\n for (const tools of this.tools.values()) {\n allTools.push(...tools);\n }\n return allTools;\n }\n\n /**\n * Get tools from a specific server\n */\n getServerTools(serverName: string): MCPToolInfo[] {\n return this.tools.get(serverName) || [];\n }\n\n /**\n * Check if a server is connected\n */\n isServerConnected(serverName: string): boolean {\n return this.clients.has(serverName);\n }\n\n /**\n * Get list of connected server names\n */\n getConnectedServers(): string[] {\n return Array.from(this.clients.keys());\n }\n\n /**\n * Enable content processing with content storage\n */\n enableContentProcessing(contentStorage: ContentStorage): void {\n this.contentProcessor = new MCPContentProcessor(contentStorage, this.logger);\n this.logger.info('Content processing enabled for MCP responses');\n }\n\n /**\n * Disable content processing\n */\n disableContentProcessing(): void {\n delete this.contentProcessor;\n this.logger.info('Content processing disabled for MCP responses');\n }\n\n /**\n * Check if content processing is enabled\n */\n isContentProcessingEnabled(): boolean {\n return this.contentProcessor !== undefined;\n }\n\n /**\n * Analyze a response without processing it (for testing/debugging)\n */\n analyzeResponseContent(response: unknown): unknown {\n if (!this.contentProcessor) {\n throw new Error('Content processing is not enabled');\n }\n return this.contentProcessor.analyzeResponse(response);\n }\n}"],"names":[],"mappings":";;;AAUO,MAAM,iBAAiB;AAAA,EAM5B,YAAY,QAAgB,gBAAiC;AAL7D,SAAQ,8BAAmC,IAAA;AAC3C,SAAQ,4BAAwC,IAAA;AAK9C,SAAK,SAAS;AACd,QAAI,gBAAgB;AAClB,WAAK,mBAAmB,IAAI,oBAAoB,gBAAgB,MAAM;AAAA,IACxE;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,cAAc,QAAuD;AACzE,QAAI;AACF,UAAI,KAAK,kBAAkB,OAAO,IAAI,GAAG;AACvC,eAAO;AAAA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EAKA,cAA6B;AAC3B,UAAM,WAA0B,CAAA;AAChC,eAAW,SAAS,KAAK,MAAM,OAAA,GAAU;AACvC,eAAS,KAAK,GAAG,KAAK;AAAA,IACxB;AACA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA,EAKA,eAAe,YAAmC;AAChD,WAAO,KAAK,MAAM,IAAI,UAAU,KAAK,CAAA;AAAA,EACvC;AAAA;AAAA;AAAA;AAAA,EAKA,kBAAkB,YAA6B;AAC7C,WAAO,KAAK,QAAQ,IAAI,UAAU;AAAA,EACpC;AAAA;AAAA;AAAA;AAAA,EAKA,sBAAgC;AAC9B,WAAO,MAAM,KAAK,KAAK,QAAQ,MAAM;AAAA,EACvC;AAAA;AAAA;AAAA;AAAA,EAKA,wBAAwB,gBAAsC;AAC5D,SAAK,mBAAmB,IAAI,oBAAoB,gBAAgB,KAAK,MAAM;AAC3E,SAAK,OAAO,KAAK,8CAA8C;AAAA,EACjE;AAAA;AAAA;AAAA;AAAA,EAKA,2BAAiC;AAC/B,WAAO,KAAK;AACZ,SAAK,OAAO,KAAK,+CAA+C;AAAA,EAClE;AAAA;AAAA;AAAA;AAAA,EAKA,6BAAsC;AACpC,WAAO,KAAK,qBAAqB;AAAA,EACnC;AAAA;AAAA;AAAA;AAAA,EAKA,uBAAuB,UAA4B;AACjD,QAAI,CAAC,KAAK,kBAAkB;AAC1B,YAAM,IAAI,MAAM,mCAAmC;AAAA,IACrD;AACA,WAAO,KAAK,iBAAiB,gBAAgB,QAAQ;AAAA,EACvD;AACF;"}
1
+ {"version":3,"file":"index15.js","sources":["../../src/mcp/mcp-client-manager.ts"],"sourcesContent":["import { Client } from '@modelcontextprotocol/sdk/client/index';\nimport { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio';\nimport type { MCPServerConfig, MCPToolInfo, MCPConnectionStatus } from './types';\nimport { Logger } from '@hashgraphonline/standards-sdk';\nimport type { ContentStorage } from '../memory/content-storage';\nimport { MCPContentProcessor } from './content-processor';\n\n/**\n * Manages connections to MCP servers and tool discovery\n */\nexport class MCPClientManager {\n private clients: Map<string, Client> = new Map();\n private tools: Map<string, MCPToolInfo[]> = new Map();\n private logger: Logger;\n private contentProcessor?: MCPContentProcessor;\n\n constructor(logger: Logger, contentStorage?: ContentStorage) {\n this.logger = logger;\n if (contentStorage) {\n this.contentProcessor = new MCPContentProcessor(contentStorage, logger);\n }\n }\n\n /**\n * Connect to an MCP server and discover its tools\n */\n async connectServer(config: MCPServerConfig): Promise<MCPConnectionStatus> {\n try {\n if (this.isServerConnected(config.name)) {\n return {\n serverName: config.name,\n connected: false,\n error: `Server ${config.name} is already connected`,\n tools: [],\n };\n }\n\n if (config.transport && config.transport !== 'stdio') {\n throw new Error(`Transport ${config.transport} not yet supported`);\n }\n\n const transport = new StdioClientTransport({\n command: config.command,\n args: config.args,\n ...(config.env && { env: config.env }),\n });\n\n const client = new Client({\n name: `conversational-agent-${config.name}`,\n version: '1.0.0',\n }, {\n capabilities: {},\n });\n\n await client.connect(transport);\n this.clients.set(config.name, client);\n\n const toolsResponse = await client.listTools();\n const toolsWithServer: MCPToolInfo[] = toolsResponse.tools.map(tool => ({\n ...tool,\n serverName: config.name,\n }));\n\n this.tools.set(config.name, toolsWithServer);\n this.logger.info(`Connected to MCP server ${config.name} with ${toolsWithServer.length} tools`);\n\n return {\n serverName: config.name,\n connected: true,\n tools: toolsWithServer,\n };\n } catch (error) {\n this.logger.error(`Failed to connect to MCP server ${config.name}:`, error);\n return {\n serverName: config.name,\n connected: false,\n error: error instanceof Error ? error.message : 'Unknown error',\n tools: [],\n };\n }\n }\n\n /**\n * Execute a tool on a specific MCP server\n */\n async executeTool(serverName: string, toolName: string, args: Record<string, unknown>): Promise<unknown> {\n const client = this.clients.get(serverName);\n if (!client) {\n throw new Error(`MCP server ${serverName} not connected`);\n }\n\n this.logger.debug(`Executing MCP tool ${toolName} on server ${serverName}`, args);\n\n try {\n const result = await client.callTool({\n name: toolName,\n arguments: args,\n });\n\n if (this.contentProcessor) {\n const processed = await this.contentProcessor.processResponse(result, serverName, toolName);\n \n if (processed.wasProcessed) {\n this.logger.debug(\n `Processed MCP response from ${serverName}::${toolName}`,\n {\n referenceCreated: processed.referenceCreated,\n originalSize: processed.originalSize,\n errors: processed.errors\n }\n );\n\n if (processed.errors && processed.errors.length > 0) {\n this.logger.warn(`Content processing warnings for ${serverName}::${toolName}:`, processed.errors);\n }\n }\n\n return processed.content;\n }\n\n return result;\n } catch (error) {\n this.logger.error(`Error executing MCP tool ${toolName}:`, error);\n throw error;\n }\n }\n\n /**\n * Disconnect all MCP servers\n */\n async disconnectAll(): Promise<void> {\n for (const [name, client] of this.clients) {\n try {\n await client.close();\n this.logger.info(`Disconnected from MCP server ${name}`);\n } catch (error) {\n this.logger.error(`Error disconnecting MCP server ${name}:`, error);\n }\n }\n this.clients.clear();\n this.tools.clear();\n }\n\n /**\n * Get all discovered tools from all connected servers\n */\n getAllTools(): MCPToolInfo[] {\n const allTools: MCPToolInfo[] = [];\n for (const tools of this.tools.values()) {\n allTools.push(...tools);\n }\n return allTools;\n }\n\n /**\n * Get tools from a specific server\n */\n getServerTools(serverName: string): MCPToolInfo[] {\n return this.tools.get(serverName) || [];\n }\n\n /**\n * Check if a server is connected\n */\n isServerConnected(serverName: string): boolean {\n return this.clients.has(serverName);\n }\n\n /**\n * Get list of connected server names\n */\n getConnectedServers(): string[] {\n return Array.from(this.clients.keys());\n }\n\n /**\n * Enable content processing with content storage\n */\n enableContentProcessing(contentStorage: ContentStorage): void {\n this.contentProcessor = new MCPContentProcessor(contentStorage, this.logger);\n this.logger.info('Content processing enabled for MCP responses');\n }\n\n /**\n * Disable content processing\n */\n disableContentProcessing(): void {\n delete this.contentProcessor;\n this.logger.info('Content processing disabled for MCP responses');\n }\n\n /**\n * Check if content processing is enabled\n */\n isContentProcessingEnabled(): boolean {\n return this.contentProcessor !== undefined;\n }\n\n /**\n * Analyze a response without processing it (for testing/debugging)\n */\n analyzeResponseContent(response: unknown): unknown {\n if (!this.contentProcessor) {\n throw new Error('Content processing is not enabled');\n }\n return this.contentProcessor.analyzeResponse(response);\n }\n}"],"names":[],"mappings":";;;AAUO,MAAM,iBAAiB;AAAA,EAM5B,YAAY,QAAgB,gBAAiC;AAL7D,SAAQ,8BAAmC,IAAA;AAC3C,SAAQ,4BAAwC,IAAA;AAK9C,SAAK,SAAS;AACd,QAAI,gBAAgB;AAClB,WAAK,mBAAmB,IAAI,oBAAoB,gBAAgB,MAAM;AAAA,IACxE;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,cAAc,QAAuD;AACzE,QAAI;AACF,UAAI,KAAK,kBAAkB,OAAO,IAAI,GAAG;AACvC,eAAO;AAAA,UACL,YAAY,OAAO;AAAA,UACnB,WAAW;AAAA,UACX,OAAO,UAAU,OAAO,IAAI;AAAA,UAC5B,OAAO,CAAA;AAAA,QAAC;AAAA,MAEZ;AAEA,UAAI,OAAO,aAAa,OAAO,cAAc,SAAS;AACpD,cAAM,IAAI,MAAM,aAAa,OAAO,SAAS,oBAAoB;AAAA,MACnE;AAEA,YAAM,YAAY,IAAI,qBAAqB;AAAA,QACzC,SAAS,OAAO;AAAA,QAChB,MAAM,OAAO;AAAA,QACb,GAAI,OAAO,OAAO,EAAE,KAAK,OAAO,IAAA;AAAA,MAAI,CACrC;AAED,YAAM,SAAS,IAAI,OAAO;AAAA,QACxB,MAAM,wBAAwB,OAAO,IAAI;AAAA,QACzC,SAAS;AAAA,MAAA,GACR;AAAA,QACD,cAAc,CAAA;AAAA,MAAC,CAChB;AAED,YAAM,OAAO,QAAQ,SAAS;AAC9B,WAAK,QAAQ,IAAI,OAAO,MAAM,MAAM;AAEpC,YAAM,gBAAgB,MAAM,OAAO,UAAA;AACnC,YAAM,kBAAiC,cAAc,MAAM,IAAI,CAAA,UAAS;AAAA,QACtE,GAAG;AAAA,QACH,YAAY,OAAO;AAAA,MAAA,EACnB;AAEF,WAAK,MAAM,IAAI,OAAO,MAAM,eAAe;AAC3C,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AKA,uBAAuB,UAA4B;AACjD,QAAI,CAAC,KAAK,kBAAkB;AAC1B,YAAM,IAAI,MAAM,mCAAmC;AAAA,IACrD;AACA,WAAO,KAAK,iBAAiB,gBAAgB,QAAQ;AAAA,EACvD;AACF;"}
@@ -1,16 +1,6 @@
1
1
  import { BasePlugin } from "hedera-agent-kit";
2
2
  import { OpenConvaiState, HCS10Builder, RegisterAgentTool, FindRegistrationsTool, RetrieveProfileTool, InitiateConnectionTool, ListConnectionsTool, SendMessageToConnectionTool, CheckMessagesTool, ConnectionMonitorTool, ManageConnectionRequestsTool, AcceptConnectionRequestTool, ListUnapprovedConnectionRequestsTool } from "@hashgraphonline/standards-agent-kit";
3
3
  import { HCS10Client } from "@hashgraphonline/standards-sdk";
4
- function extractPrivateKey(opKey) {
5
- const key = opKey;
6
- if (typeof key?.toStringRaw === "function") {
7
- return key.toStringRaw();
8
- }
9
- if (typeof key?.toString === "function") {
10
- return key.toString();
11
- }
12
- return String(key);
13
- }
14
4
  function hasInitializeConnectionsManager(stateManager) {
15
5
  return typeof stateManager === "object" && stateManager !== null && "initializeConnectionsManager" in stateManager && typeof stateManager.initializeConnectionsManager === "function";
16
6
  }
@@ -40,24 +30,27 @@ class HCS10Plugin extends BasePlugin {
40
30
  const isBytesMode = String(hederaKit.operationalMode || "returnBytes") === "returnBytes";
41
31
  let inboundTopicId = "";
42
32
  let outboundTopicId = "";
43
- if (!isBytesMode) {
44
- try {
45
- const opKey = hederaKit.signer.getOperatorPrivateKey();
46
- const privateKey = extractPrivateKey(opKey);
47
- const hcs10Client = new HCS10Client({
48
- network: hederaKit.network,
49
- operatorId: accountId,
50
- operatorPrivateKey: privateKey,
51
- logLevel: "error"
52
- });
53
- const profileResponse = await hcs10Client.retrieveProfile(accountId);
54
- if (profileResponse.success && profileResponse.topicInfo) {
55
- inboundTopicId = profileResponse.topicInfo.inboundTopic;
56
- outboundTopicId = profileResponse.topicInfo.outboundTopic;
57
- }
58
- } catch (profileError) {
59
- this.context.logger.warn("Skipping profile topic discovery", profileError);
33
+ let operatorPrivateKeyRef = hederaKit.signer.getOperatorPrivateKey();
34
+ let operatorPrivateKeySerialized;
35
+ try {
36
+ const resolved = typeof operatorPrivateKeyRef?.toString === "function" ? operatorPrivateKeyRef.toString() : "";
37
+ operatorPrivateKeySerialized = resolved;
38
+ const hcs10Client = new HCS10Client({
39
+ network: hederaKit.network,
40
+ operatorId: accountId,
41
+ operatorPrivateKey: operatorPrivateKeyRef,
42
+ logLevel: "error"
43
+ });
44
+ const profileResponse = await hcs10Client.retrieveProfile(accountId);
45
+ if (profileResponse.success && profileResponse.topicInfo) {
46
+ inboundTopicId = profileResponse.topicInfo.inboundTopic;
47
+ outboundTopicId = profileResponse.topicInfo.outboundTopic;
60
48
  }
49
+ } catch (profileError) {
50
+ this.context.logger.warn(
51
+ "Skipping profile topic discovery",
52
+ profileError
53
+ );
61
54
  }
62
55
  const agentRecord = {
63
56
  name: `Agent ${accountId}`,
@@ -65,37 +58,38 @@ class HCS10Plugin extends BasePlugin {
65
58
  inboundTopicId,
66
59
  outboundTopicId
67
60
  };
68
- if (!isBytesMode) {
69
- try {
70
- const opKey = hederaKit.signer.getOperatorPrivateKey();
71
- agentRecord.privateKey = extractPrivateKey(opKey);
72
- } catch {
73
- }
61
+ if (!isBytesMode && operatorPrivateKeySerialized) {
62
+ agentRecord.privateKey = operatorPrivateKeySerialized;
74
63
  }
75
- this.stateManager.setCurrentAgent(agentRecord);
64
+ this.stateManager.setCurrentAgent(
65
+ agentRecord
66
+ );
76
67
  this.context.logger.info(
77
68
  `Set current agent: ${accountId} with topics ${inboundTopicId}/${outboundTopicId}`
78
69
  );
79
70
  if (!isBytesMode && this.stateManager && !this.stateManager.getConnectionsManager()) {
80
71
  try {
81
- const opKey = hederaKit.signer.getOperatorPrivateKey();
82
- const privateKey = extractPrivateKey(opKey);
83
72
  const hcs10Client = new HCS10Client({
84
73
  network: hederaKit.network,
85
74
  operatorId: accountId,
86
- operatorPrivateKey: privateKey,
75
+ operatorPrivateKey: operatorPrivateKeyRef ?? "",
87
76
  logLevel: "error"
88
77
  });
89
78
  if (hasInitializeConnectionsManager(this.stateManager)) {
90
79
  this.stateManager.initializeConnectionsManager(hcs10Client);
91
80
  } else {
92
- this.context.logger.warn("StateManager does not support connection manager initialization");
81
+ this.context.logger.warn(
82
+ "StateManager does not support connection manager initialization"
83
+ );
93
84
  }
94
85
  this.context.logger.info(
95
86
  "ConnectionsManager initialized in HCS10Plugin"
96
87
  );
97
88
  } catch (cmError) {
98
- this.context.logger.warn("Could not initialize ConnectionsManager:", cmError);
89
+ this.context.logger.warn(
90
+ "Could not initialize ConnectionsManager:",
91
+ cmError
92
+ );
99
93
  }
100
94
  }
101
95
  this.initializeTools();
@@ -1 +1 @@
1
- {"version":3,"file":"index2.js","sources":["../../src/plugins/hcs-10/HCS10Plugin.ts"],"sourcesContent":["import {\n GenericPluginContext,\n HederaTool,\n BasePlugin,\n HederaAgentKit,\n} from 'hedera-agent-kit';\nimport {\n IStateManager,\n OpenConvaiState,\n HCS10Builder,\n RegisterAgentTool,\n FindRegistrationsTool,\n InitiateConnectionTool,\n ListConnectionsTool,\n SendMessageToConnectionTool,\n CheckMessagesTool,\n ConnectionMonitorTool,\n ManageConnectionRequestsTool,\n AcceptConnectionRequestTool,\n RetrieveProfileTool,\n ListUnapprovedConnectionRequestsTool,\n} from '@hashgraphonline/standards-agent-kit';\nimport { HCS10Client } from '@hashgraphonline/standards-sdk';\n\ninterface HCS10ClientManager {\n initializeConnectionsManager(client: HCS10Client): void;\n}\n\n/**\n * Extracts private key string from operator key\n */\nfunction extractPrivateKey(opKey: unknown): string {\n const key = opKey as {\n toString?: () => string;\n toStringRaw?: () => string;\n };\n \n if (typeof key?.toStringRaw === 'function') {\n return key.toStringRaw();\n }\n \n if (typeof key?.toString === 'function') {\n return key.toString();\n }\n \n return String(key);\n}\n\nfunction hasInitializeConnectionsManager(\n stateManager: IStateManager\n): stateManager is IStateManager & HCS10ClientManager {\n return (\n typeof stateManager === 'object' &&\n stateManager !== null &&\n 'initializeConnectionsManager' in stateManager &&\n typeof stateManager.initializeConnectionsManager === 'function'\n );\n}\n\nexport class HCS10Plugin extends BasePlugin {\n id = 'hcs-10';\n name = 'HCS-10 Plugin';\n description =\n 'HCS-10 agent tools for decentralized agent registration, connections, and messaging on Hedera';\n version = '1.0.0';\n author = 'Hashgraph Online';\n namespace = 'hcs10';\n\n private stateManager?: IStateManager;\n private tools: any[] = [];\n appConfig?: Record<string, unknown>;\n\n override async initialize(context: GenericPluginContext): Promise<void> {\n await super.initialize(context);\n\n const hederaKit = context.config.hederaKit as HederaAgentKit;\n if (!hederaKit) {\n this.context.logger.warn(\n 'HederaKit not found in context. HCS-10 tools will not be available.'\n );\n return;\n }\n\n try {\n this.stateManager =\n (context.stateManager as IStateManager) ||\n (context.config.stateManager as IStateManager) ||\n (this.appConfig?.stateManager as IStateManager) ||\n new OpenConvaiState();\n\n const accountId = hederaKit.signer.getAccountId().toString();\n const isBytesMode = String(hederaKit.operationalMode || 'returnBytes') === 'returnBytes';\n let inboundTopicId = '';\n let outboundTopicId = '';\n\n if (!isBytesMode) {\n try {\n const opKey = hederaKit.signer.getOperatorPrivateKey();\n const privateKey = extractPrivateKey(opKey);\n\n const hcs10Client = new HCS10Client({\n network: hederaKit.network as 'mainnet' | 'testnet',\n operatorId: accountId,\n operatorPrivateKey: privateKey,\n logLevel: 'error',\n });\n\n const profileResponse = await hcs10Client.retrieveProfile(accountId);\n if (profileResponse.success && profileResponse.topicInfo) {\n inboundTopicId = profileResponse.topicInfo.inboundTopic;\n outboundTopicId = profileResponse.topicInfo.outboundTopic;\n }\n } catch (profileError) {\n this.context.logger.warn('Skipping profile topic discovery', profileError);\n }\n }\n\n const agentRecord: Record<string, unknown> = {\n name: `Agent ${accountId}`,\n accountId: accountId,\n inboundTopicId,\n outboundTopicId,\n };\n if (!isBytesMode) {\n try {\n const opKey = hederaKit.signer.getOperatorPrivateKey();\n agentRecord.privateKey = extractPrivateKey(opKey);\n } catch {}\n }\n this.stateManager.setCurrentAgent(agentRecord as any);\n\n this.context.logger.info(\n `Set current agent: ${accountId} with topics ${inboundTopicId}/${outboundTopicId}`\n );\n\n if (!isBytesMode && this.stateManager && !this.stateManager.getConnectionsManager()) {\n try {\n const opKey = hederaKit.signer.getOperatorPrivateKey();\n const privateKey = extractPrivateKey(opKey);\n const hcs10Client = new HCS10Client({\n network: hederaKit.network as 'mainnet' | 'testnet',\n operatorId: accountId,\n operatorPrivateKey: privateKey,\n logLevel: 'error',\n });\n\n if (hasInitializeConnectionsManager(this.stateManager)) {\n this.stateManager.initializeConnectionsManager(hcs10Client);\n } else {\n this.context.logger.warn('StateManager does not support connection manager initialization');\n }\n this.context.logger.info(\n 'ConnectionsManager initialized in HCS10Plugin'\n );\n } catch (cmError) {\n this.context.logger.warn('Could not initialize ConnectionsManager:', cmError);\n }\n }\n\n this.initializeTools();\n this.context.logger.info('HCS-10 Plugin initialized successfully');\n } catch (error) {\n this.context.logger.error('Failed to initialize HCS-10 plugin:', error);\n }\n }\n\n private initializeTools(): void {\n if (!this.stateManager) {\n throw new Error('StateManager must be initialized before creating tools');\n }\n\n const hederaKit = this.context.config.hederaKit as HederaAgentKit;\n if (!hederaKit) {\n throw new Error('HederaKit not found in context config');\n }\n\n const hcs10Builder = new HCS10Builder(hederaKit, this.stateManager);\n\n this.tools = [\n new RegisterAgentTool({\n hederaKit: hederaKit,\n hcs10Builder: hcs10Builder,\n logger: this.context.logger,\n }),\n new FindRegistrationsTool({\n hederaKit: hederaKit,\n hcs10Builder: hcs10Builder,\n logger: this.context.logger,\n }),\n new RetrieveProfileTool({\n hederaKit: hederaKit,\n hcs10Builder: hcs10Builder,\n logger: this.context.logger,\n }),\n new InitiateConnectionTool({\n hederaKit: hederaKit,\n hcs10Builder: hcs10Builder,\n logger: this.context.logger,\n }),\n new ListConnectionsTool({\n hederaKit: hederaKit,\n hcs10Builder: hcs10Builder,\n logger: this.context.logger,\n }),\n new SendMessageToConnectionTool({\n hederaKit: hederaKit,\n hcs10Builder: hcs10Builder,\n logger: this.context.logger,\n }),\n new CheckMessagesTool({\n hederaKit: hederaKit,\n hcs10Builder: hcs10Builder,\n logger: this.context.logger,\n }),\n new ConnectionMonitorTool({\n hederaKit: hederaKit,\n hcs10Builder: hcs10Builder,\n logger: this.context.logger,\n }),\n new ManageConnectionRequestsTool({\n hederaKit: hederaKit,\n hcs10Builder: hcs10Builder,\n logger: this.context.logger,\n }),\n new AcceptConnectionRequestTool({\n hederaKit: hederaKit,\n hcs10Builder: hcs10Builder,\n logger: this.context.logger,\n }),\n new ListUnapprovedConnectionRequestsTool({\n hederaKit: hederaKit,\n hcs10Builder: hcs10Builder,\n logger: this.context.logger,\n }),\n ];\n }\n\n getTools(): HederaTool[] {\n return this.tools;\n }\n\n getStateManager(): IStateManager | undefined {\n return this.stateManager;\n }\n\n override async cleanup(): Promise<void> {\n this.tools = [];\n delete this.stateManager;\n if (this.context?.logger) {\n this.context.logger.info('HCS-10 Plugin cleaned up');\n }\n }\n}\n"],"names":[],"mappings":";;;AA+BA,SAAS,kBAAkB,OAAwB;AACjD,QAAM,MAAM;AAKZ,MAAI,OAAO,KAAK,gBAAgB,YAAY;AAC1C,WAAO,IAAI,YAAA;AAAA,EACb;AAEA,MAAI,OAAO,KAAK,aAAa,YAAY;AACvC,WAAO,IAAI,SAAA;AAAA,EACb;AAEA,SAAO,OAAO,GAAG;AACnB;AAEA,SAAS,gCACP,cACoD;AACpD,SACE,OAAO,iBAAiB,YACxB,iBAAiB,QACjB,kCAAkC,gBAClC,OAAO,aAAa,iCAAiC;AAEzD;AAEO,MAAM,oBAAoB,WAAW;AAAA,EAArC,cAAA;AAAA,UAAA,GAAA,SAAA;AACL,SAAA,KAAK;AACL,SAAA,OAAO;AACP,SAAA,cACE;AACF,SAAA,UAAU;AACV,SAAA,SAAS;AACT,SAAA,YAAY;AAGZ,SAAQ,QAAe,CAAA;AAAA,EAAC;AAAA,EAGxB,MAAe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GenericPluginContext,\n HederaTool,\n BasePlugin,\n HederaAgentKit,\n} from 'hedera-agent-kit';\nimport {\n IStateManager,\n OpenConvaiState,\n HCS10Builder,\n RegisterAgentTool,\n FindRegistrationsTool,\n InitiateConnectionTool,\n ListConnectionsTool,\n SendMessageToConnectionTool,\n CheckMessagesTool,\n ConnectionMonitorTool,\n ManageConnectionRequestsTool,\n AcceptConnectionRequestTool,\n RetrieveProfileTool,\n ListUnapprovedConnectionRequestsTool,\n RegisteredAgent,\n} from '@hashgraphonline/standards-agent-kit';\nimport { HCS10Client } from '@hashgraphonline/standards-sdk';\nimport { PrivateKey } from 'node_modules/@hashgraph/sdk/lib/Mnemonic';\n\ninterface HCS10ClientManager {\n initializeConnectionsManager(client: HCS10Client): void;\n}\n\nfunction hasInitializeConnectionsManager(\n stateManager: IStateManager\n): stateManager is IStateManager & HCS10ClientManager {\n return (\n typeof stateManager === 'object' &&\n stateManager !== null &&\n 'initializeConnectionsManager' in stateManager &&\n typeof stateManager.initializeConnectionsManager === 'function'\n );\n}\n\nexport class HCS10Plugin extends BasePlugin {\n id = 'hcs-10';\n name = 'HCS-10 Plugin';\n description =\n 'HCS-10 agent tools for decentralized agent registration, connections, and messaging on Hedera';\n version = '1.0.0';\n author = 'Hashgraph Online';\n namespace = 'hcs10';\n\n private stateManager?: IStateManager;\n private tools: any[] = [];\n appConfig?: Record<string, unknown>;\n\n override async initialize(context: GenericPluginContext): Promise<void> {\n await super.initialize(context);\n\n const hederaKit = context.config.hederaKit as HederaAgentKit;\n if (!hederaKit) {\n this.context.logger.warn(\n 'HederaKit not found in context. HCS-10 tools will not be available.'\n );\n return;\n }\n\n try {\n this.stateManager =\n (context.stateManager as IStateManager) ||\n (context.config.stateManager as IStateManager) ||\n (this.appConfig?.stateManager as IStateManager) ||\n new OpenConvaiState();\n\n const accountId = hederaKit.signer.getAccountId().toString();\n const isBytesMode =\n String(hederaKit.operationalMode || 'returnBytes') === 'returnBytes';\n let inboundTopicId = '';\n let outboundTopicId = '';\n\n let operatorPrivateKeyRef: PrivateKey =\n hederaKit.signer.getOperatorPrivateKey();\n let operatorPrivateKeySerialized: string | undefined;\n\n try {\n const resolved =\n typeof operatorPrivateKeyRef?.toString === 'function'\n ? operatorPrivateKeyRef.toString()\n : '';\n\n operatorPrivateKeySerialized = resolved;\n\n const hcs10Client = new HCS10Client({\n network: hederaKit.network as 'mainnet' | 'testnet',\n operatorId: accountId,\n operatorPrivateKey: operatorPrivateKeyRef,\n logLevel: 'error',\n });\n\n const profileResponse = await hcs10Client.retrieveProfile(accountId);\n if (profileResponse.success && profileResponse.topicInfo) {\n inboundTopicId = profileResponse.topicInfo.inboundTopic;\n outboundTopicId = profileResponse.topicInfo.outboundTopic;\n }\n } catch (profileError) {\n this.context.logger.warn(\n 'Skipping profile topic discovery',\n profileError\n );\n }\n\n const agentRecord: Record<string, unknown> = {\n name: `Agent ${accountId}`,\n accountId: accountId,\n inboundTopicId,\n outboundTopicId,\n };\n if (!isBytesMode && operatorPrivateKeySerialized) {\n agentRecord.privateKey = operatorPrivateKeySerialized;\n }\n this.stateManager.setCurrentAgent(\n agentRecord as unknown as RegisteredAgent\n );\n\n this.context.logger.info(\n `Set current agent: ${accountId} with topics ${inboundTopicId}/${outboundTopicId}`\n );\n\n if (\n !isBytesMode &&\n this.stateManager &&\n !this.stateManager.getConnectionsManager()\n ) {\n try {\n const hcs10Client = new HCS10Client({\n network: hederaKit.network as 'mainnet' | 'testnet',\n operatorId: accountId,\n operatorPrivateKey: operatorPrivateKeyRef ?? '',\n logLevel: 'error',\n });\n\n if (hasInitializeConnectionsManager(this.stateManager)) {\n this.stateManager.initializeConnectionsManager(hcs10Client);\n } else {\n this.context.logger.warn(\n 'StateManager does not support connection manager initialization'\n );\n }\n this.context.logger.info(\n 'ConnectionsManager initialized in HCS10Plugin'\n );\n } catch (cmError) {\n this.context.logger.warn(\n 'Could not initialize ConnectionsManager:',\n cmError\n );\n }\n }\n\n this.initializeTools();\n this.context.logger.info('HCS-10 Plugin initialized successfully');\n } catch (error) {\n this.context.logger.error('Failed to initialize HCS-10 plugin:', error);\n }\n }\n\n private initializeTools(): void {\n if (!this.stateManager) {\n throw new Error('StateManager must be initialized before creating tools');\n }\n\n const hederaKit = this.context.config.hederaKit as HederaAgentKit;\n if (!hederaKit) {\n throw new Error('HederaKit not found in context config');\n }\n\n const hcs10Builder = new HCS10Builder(hederaKit, this.stateManager);\n\n this.tools = [\n new RegisterAgentTool({\n hederaKit: hederaKit,\n hcs10Builder: hcs10Builder,\n logger: this.context.logger,\n }),\n new FindRegistrationsTool({\n hederaKit: hederaKit,\n hcs10Builder: hcs10Builder,\n logger: this.context.logger,\n }),\n new RetrieveProfileTool({\n hederaKit: hederaKit,\n hcs10Builder: hcs10Builder,\n logger: this.context.logger,\n }),\n new InitiateConnectionTool({\n hederaKit: hederaKit,\n hcs10Builder: hcs10Builder,\n logger: this.context.logger,\n }),\n new ListConnectionsTool({\n hederaKit: hederaKit,\n hcs10Builder: hcs10Builder,\n logger: this.context.logger,\n }),\n new SendMessageToConnectionTool({\n hederaKit: hederaKit,\n hcs10Builder: hcs10Builder,\n logger: this.context.logger,\n }),\n new CheckMessagesTool({\n hederaKit: hederaKit,\n hcs10Builder: hcs10Builder,\n logger: this.context.logger,\n }),\n new ConnectionMonitorTool({\n hederaKit: hederaKit,\n hcs10Builder: hcs10Builder,\n logger: this.context.logger,\n }),\n new ManageConnectionRequestsTool({\n hederaKit: hederaKit,\n hcs10Builder: hcs10Builder,\n logger: this.context.logger,\n }),\n new AcceptConnectionRequestTool({\n hederaKit: hederaKit,\n hcs10Builder: hcs10Builder,\n logger: this.context.logger,\n }),\n new ListUnapprovedConnectionRequestsTool({\n hederaKit: hederaKit,\n hcs10Builder: hcs10Builder,\n logger: this.context.logger,\n }),\n ];\n }\n\n getTools(): HederaTool[] {\n return this.tools;\n }\n\n getStateManager(): IStateManager | undefined {\n return this.stateManager;\n }\n\n override async cleanup(): Promise<void> {\n this.tools = [];\n delete this.state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WAAO,KAAK;AAAA,EACd;AAAA,EAEA,kBAA6C;AAC3C,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,MAAe,UAAyB;AACtC,SAAK,QAAQ,CAAA;AACb,WAAO,KAAK;AACZ,QAAI,KAAK,SAAS,QAAQ;AACxB,WAAK,QAAQ,OAAO,KAAK,0BAA0B;AAAA,IACrD;AAAA,EACF;AACF;"}
@@ -1 +1 @@
1
- {"version":3,"file":"index21.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(): { maxStorage: number; currentUsage: number; utilizationPercentage: number } {\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<{ content: string; type: string; storedAt: string; id: string }> {\n return this.messages.map((stored) => ({\n content: 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): { maxAgeMs: number; priority: number } {\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,mBAAmB;AAAA,MACnB,mBAAmB;AAAA,MACnB,kBAAkB;AAAA,MAClB,mBAAmB;AAAA,MACnB,oBAAoB;AAAA,MACpB,oBAAoB;AAAA,MACpB,oBAAoB;AAAA,QAClB,uBAAuB;AAAA,QACvB,yBAAyB;AAAA,QACzB,sBAAsB;AAAA,QACtB,eAAe,CAAA;AAAA,QACf,iBAAiB,CAAA;AAAA,QACjB,cAAc,CAAA;AAAA,MAAC;AAAA,IACjB;AAGF,QAAI,KAAK,gBAAgB,mBAAmB;AAC1C,WAAK,2BAAA;AAAA,IACP;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,cAAc,UAAsC;AAClD,QAAI,SAAS,WAAW,GAAG;AACz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AAA;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;AAn5BE,gBAAuB,sBAAsB;AAhBxC,IAAM,iBAAN;"}
1
+ {"version":3,"file":"index21.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,mBAAmB;AAAA,MACnB,mBAAmB;AAAA,MACnB,kBAAkB;AAAA,MAClB,mBAAmB;AAAA,MACnB,oBAAoB;AAAA,MACpB,oBAAoB;AAAA,MACpB,oBAAoB;AAAA,QAClB,uBAAuB;AAAA,QACvB,yBAAyB;AAAA,QACzB,sBAAsB;AAAA,QACtB,eAAe,CAAA;AAAA,QACf,iBAAiB,CAAA;AAAA,QACjB,cAAc,CAAA;AAAA,MAAC;AAAA,IACjB;AAGF,QAAI,KAAK,gBAAgB,mBAAmB;AAC1C,WAAK,2BAAA;AAAA,IACP;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,cAAc,UAAsC;AAClD,QAAI,SAAS,WAAW,GAAG;A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A;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;"}
@@ -12,8 +12,8 @@ import "langchain/agents";
12
12
  import "zod-to-json-schema";
13
13
  import "./index12.js";
14
14
  import "@langchain/core/prompts";
15
- import "@modelcontextprotocol/sdk/client/index.js";
16
- import "@modelcontextprotocol/sdk/client/stdio.js";
15
+ import "@modelcontextprotocol/sdk/client/index";
16
+ import "@modelcontextprotocol/sdk/client/stdio";
17
17
  import "./index18.js";
18
18
  import "@langchain/core/messages";
19
19
  import "./index19.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index24.js","sources":["../../src/services/content-store-manager.ts"],"sourcesContent":["import { ContentStorage } from '../memory/content-storage';\nimport {\n ContentStoreService,\n extractReferenceId,\n shouldUseReference,\n ContentResolverRegistry,\n type ContentStoreInterface,\n type ContentResolverInterface,\n type ReferenceResolutionResult,\n} from '@hashgraphonline/standards-sdk';\nimport type {\n ContentReference,\n ContentReferenceConfig,\n ContentReferenceStats,\n} from '../types/content-reference';\nimport { Logger } from '@hashgraphonline/standards-sdk';\n\n/**\n * Content metadata interface for adapter compatibility\n */\ninterface AdapterContentMetadata {\n mimeType?: string;\n fileName?: string;\n sizeBytes?: number;\n [key: string]: unknown;\n}\n\n/**\n * Configuration interface for content storage\n */\ninterface ContentStoreConfig {\n maxSize?: number;\n enableCompression?: boolean;\n [key: string]: unknown;\n}\n\n/**\n * Adapter to make ContentStorage compatible with ContentStoreInterface\n */\nclass ContentStorageAdapter implements ContentStoreInterface {\n constructor(private storage: ContentStorage) {}\n\n async storeContent(\n content: Buffer,\n metadata: AdapterContentMetadata\n ): Promise<string> {\n const storeMetadata = {\n contentType: 'binary' as const,\n sizeBytes: content.length,\n source: 'system' as const,\n ...metadata,\n };\n const contentRef = await this.storage.storeContent(content, storeMetadata);\n return contentRef.referenceId;\n }\n\n async resolveReference(\n referenceId: string\n ): Promise<ReferenceResolutionResult> {\n const result = await this.storage.resolveReference(referenceId);\n if (result.success && result.content) {\n const response: ReferenceResolutionResult = {\n content: result.content,\n };\n if (result.metadata) {\n response.metadata = {\n ...(result.metadata.mimeType !== undefined && {\n mimeType: result.metadata.mimeType,\n }),\n ...(result.metadata.fileName !== undefined && {\n fileName: result.metadata.fileName,\n }),\n originalSize: result.metadata.sizeBytes,\n };\n }\n return response;\n } else {\n throw new Error(result.error || 'Reference not found');\n }\n }\n\n async hasReference(referenceId: string): Promise<boolean> {\n return await this.storage.hasReference(referenceId);\n }\n\n async cleanupReference(referenceId: string): Promise<void> {\n await this.storage.cleanupReference(referenceId);\n }\n\n async getStats(): Promise<unknown> {\n return await this.storage.getStats();\n }\n\n async updateConfig(config: ContentStoreConfig): Promise<void> {\n const referenceConfig = {\n sizeThresholdBytes: config.maxSize || 10240,\n enableAutoCleanup: config.enableCompression || true,\n ...config,\n };\n return await this.storage.updateConfig(referenceConfig);\n }\n\n async performCleanup(): Promise<void> {\n await this.storage.performCleanup();\n }\n\n async dispose(): Promise<void> {\n return Promise.resolve(this.storage.dispose());\n }\n}\n\n/**\n * Content resolver implementation for dependency injection\n */\nclass ContentResolver implements ContentResolverInterface {\n constructor(private adapter: ContentStorageAdapter) {}\n\n async resolveReference(\n referenceId: string\n ): Promise<ReferenceResolutionResult> {\n return await this.adapter.resolveReference(referenceId);\n }\n\n shouldUseReference(content: string | Buffer): boolean {\n return shouldUseReference(content);\n }\n\n extractReferenceId(input: string): string | null {\n return extractReferenceId(input);\n }\n}\n\n/**\n * Manages content store lifecycle and cross-package registration\n */\nexport class ContentStoreManager {\n private contentStorage: ContentStorage;\n private adapter: ContentStorageAdapter;\n private resolver: ContentResolver;\n private logger: Logger;\n private isRegistered = false;\n\n constructor(\n maxMessageStorage: number = 1000,\n referenceConfig?: Partial<ContentReferenceConfig>,\n logger?: Logger\n ) {\n this.logger = logger || new Logger({ module: 'ContentStoreManager' });\n\n this.contentStorage = new ContentStorage(\n maxMessageStorage,\n referenceConfig\n );\n this.adapter = new ContentStorageAdapter(this.contentStorage);\n this.resolver = new ContentResolver(this.adapter);\n }\n\n /**\n * Initialize and register content storage for cross-package access\n */\n async initialize(): Promise<void> {\n if (this.isRegistered) {\n this.logger.warn('ContentStoreManager is already initialized');\n return;\n }\n\n try {\n if (\n ContentStoreService &&\n typeof (ContentStoreService as unknown as { setInstance?: Function }).setInstance === 'function'\n ) {\n await (ContentStoreService as unknown as { setInstance: (adapter: unknown) => Promise<void> }).setInstance(\n this.adapter\n );\n } else {\n this.logger.warn('ContentStoreService.setInstance is unavailable; skipping registration');\n }\n if (\n ContentResolverRegistry &&\n typeof (ContentResolverRegistry as unknown as { register?: Function }).register === 'function'\n ) {\n (ContentResolverRegistry as unknown as { register: (resolver: unknown) => void }).register(\n this.resolver\n );\n } else {\n this.logger.warn('ContentResolverRegistry.register is unavailable; skipping registration');\n }\n this.isRegistered = true;\n this.logger.info(\n 'ContentStoreManager initialized and registered for cross-package access'\n );\n } catch (error) {\n this.logger.error('Failed to initialize ContentStoreManager:', error);\n throw error;\n }\n }\n\n /**\n * Get the underlying ContentStorage instance\n */\n getContentStorage(): ContentStorage {\n return this.contentStorage;\n }\n\n /**\n * Get storage statistics\n */\n async getStats(): Promise<ContentReferenceStats> {\n return await this.contentStorage.getStats();\n }\n\n /**\n * Update configuration\n */\n async updateConfig(config: Partial<ContentReferenceConfig>): Promise<void> {\n return await this.contentStorage.updateConfig(config);\n }\n\n /**\n * Perform manual cleanup\n */\n async performCleanup(): Promise<{ cleanedUp: number; errors: string[] }> {\n return await this.contentStorage.performCleanup();\n }\n\n /**\n * Check if content should be stored as reference\n */\n shouldUseReference(content: Buffer | string): boolean {\n return this.contentStorage.shouldUseReference(content);\n }\n\n /**\n * Store content if it's large enough\n */\n async storeContentIfLarge(\n content: Buffer | string,\n metadata: AdapterContentMetadata\n ): Promise<ContentReference | null> {\n const storeMetadata = {\n source: 'system' as const,\n contentType: 'binary' as const,\n ...metadata,\n };\n return await this.contentStorage.storeContentIfLarge(\n content,\n storeMetadata\n );\n }\n\n /**\n * Cleanup and unregister\n */\n async dispose(): Promise<void> {\n if (this.isRegistered) {\n this.contentStorage.dispose();\n if (\n ContentStoreService &&\n typeof (ContentStoreService as unknown as { dispose?: Function }).dispose === 'function'\n ) {\n (ContentStoreService as unknown as { dispose: () => void }).dispose();\n }\n if (\n ContentResolverRegistry &&\n typeof (ContentResolverRegistry as unknown as { unregister?: Function }).unregister === 'function'\n ) {\n (ContentResolverRegistry as unknown as { unregister: () => void }).unregister();\n }\n this.isRegistered = false;\n this.logger.info('ContentStoreManager disposed and unregistered');\n }\n }\n\n /**\n * Check if the manager is initialized\n */\n isInitialized(): boolean {\n return this.isRegistered;\n }\n}\n"],"names":[],"mappings":";;AAuCA,MAAM,sBAAuD;AAAA,EAC3D,YAAoB,SAAyB;AAAzB,SAAA,UAAA;AAAA,EAA0B;AAAA,EAE9C,MAAM,aACJ,SACA,UACiB;AACjB,UAAM,gBAAgB;AAAA,MACpB,aAAa;AAAA,MACb,WAAW,QAAQ;AAAA,MACnB,QAAQ;AAAA,MACR,GAAG;AAAA,IAAA;AAEL,UAAM,aAAa,MAAM,KAAK,QAAQ,aAAa,SAAS,aAAa;AACzE,WAAO,WAAW;AAAA,EACpB;AAAA,EAEA,MAAM,iBACJ,aACoC;AACpC,UAAM,SAAS,MAAM,KAAK,QAAQ,iBAAiB,WAAW;AAC9D,QAAI,OAAO,WAAW,OAAO,SAAS;AACpC,YAAM,WAAsC;AAAA,QAC1C,SAAS,OAAO;AAAA,MAAA;AAElB,UAAI,OAAO,UAAU;AACnB,iBAAS,WAAW;AAAA,UAClB,GAAI,OAAO,SAAS,aAAa,UAAa;AAAA,YAC5C,UAAU,OAAO,SAAS;AAAA,UAAA;AAAA,UAE5B,GAAI,OAAO,SA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O;AAAA,EACvD;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,oBACJ,SACA,UACkC;AAClC,UAAM,gBAAgB;AAAA,MACpB,QAAQ;AAAA,MACR,aAAa;AAAA,MACb,GAAG;AAAA,IAAA;AAEL,WAAO,MAAM,KAAK,eAAe;AAAA,MAC/B;AAAA,MACA;AAAA,IAAA;AAAA,EAEJ;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,UAAyB;AAC7B,QAAI,KAAK,cAAc;AACrB,WAAK,eAAe,QAAA;AACpB,UACE,uBACA,OAAQ,oBAA0D,YAAY,YAC9E;AACC,4BAA2D,QAAA;AAAA,MAC9D;AACA,UACE,2BACA,OAAQ,wBAAiE,eAAe,YACxF;AACC,gCAAkE,WAAA;AAAA,MACrE;AACA,WAAK,eAAe;AACpB,WAAK,OAAO,KAAK,+CAA+C;AAAA,IAClE;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,gBAAyB;AACvB,WAAO,KAAK;AAAA,EACd;AACF;"}
1
+ {"version":3,"file":"index24.js","sources":["../../src/services/content-store-manager.ts"],"sourcesContent":["import { ContentStorage } from '../memory/content-storage';\nimport {\n ContentStoreService,\n extractReferenceId,\n shouldUseReference,\n ContentResolverRegistry,\n type ContentStoreInterface,\n type ContentResolverInterface,\n type ReferenceResolutionResult,\n} from '@hashgraphonline/standards-sdk';\nimport type {\n ContentReference,\n ContentReferenceConfig,\n ContentReferenceStats,\n} from '../types/content-reference';\nimport { Logger } from '@hashgraphonline/standards-sdk';\n\n/**\n * Content metadata interface for adapter compatibility\n */\ninterface AdapterContentMetadata {\n mimeType?: string;\n fileName?: string;\n sizeBytes?: number;\n [key: string]: unknown;\n}\n\n/**\n * Configuration interface for content storage\n */\ninterface ContentStoreConfig {\n maxSize?: number;\n enableCompression?: boolean;\n [key: string]: unknown;\n}\n\n/**\n * Adapter to make ContentStorage compatible with ContentStoreInterface\n */\nclass ContentStorageAdapter implements ContentStoreInterface {\n constructor(private storage: ContentStorage) {}\n\n async storeContent(\n content: Buffer,\n metadata: AdapterContentMetadata\n ): Promise<string> {\n const storeMetadata = {\n contentType: 'binary' as const,\n sizeBytes: content.length,\n source: 'system' as const,\n ...metadata,\n };\n const contentRef = await this.storage.storeContent(content, storeMetadata);\n return contentRef.referenceId;\n }\n\n async resolveReference(\n referenceId: string\n ): Promise<ReferenceResolutionResult> {\n const result = await this.storage.resolveReference(referenceId);\n if (result.success && result.content) {\n const response: ReferenceResolutionResult = {\n content: result.content,\n };\n if (result.metadata) {\n response.metadata = {\n ...(result.metadata.mimeType !== undefined && {\n mimeType: result.metadata.mimeType,\n }),\n ...(result.metadata.fileName !== undefined && {\n fileName: result.metadata.fileName,\n }),\n originalSize: result.metadata.sizeBytes,\n };\n }\n return response;\n } else {\n throw new Error(result.error || 'Reference not found');\n }\n }\n\n async hasReference(referenceId: string): Promise<boolean> {\n return await this.storage.hasReference(referenceId);\n }\n\n async cleanupReference(referenceId: string): Promise<void> {\n await this.storage.cleanupReference(referenceId);\n }\n\n async getStats(): Promise<unknown> {\n return await this.storage.getStats();\n }\n\n async updateConfig(config: ContentStoreConfig): Promise<void> {\n const referenceConfig = {\n sizeThresholdBytes: config.maxSize || 10240,\n enableAutoCleanup: config.enableCompression || true,\n ...config,\n };\n return await this.storage.updateConfig(referenceConfig);\n }\n\n async performCleanup(): Promise<void> {\n await this.storage.performCleanup();\n }\n\n async dispose(): Promise<void> {\n return Promise.resolve(this.storage.dispose());\n }\n}\n\n/**\n * Content resolver implementation for dependency injection\n */\nclass ContentResolver implements ContentResolverInterface {\n constructor(private adapter: ContentStorageAdapter) {}\n\n async resolveReference(\n referenceId: string\n ): Promise<ReferenceResolutionResult> {\n return await this.adapter.resolveReference(referenceId);\n }\n\n shouldUseReference(content: string | Buffer): boolean {\n return shouldUseReference(content);\n }\n\n extractReferenceId(input: string): string | null {\n return extractReferenceId(input);\n }\n}\n\n/**\n * Manages content store lifecycle and cross-package registration\n */\nexport class ContentStoreManager {\n private contentStorage: ContentStorage;\n private adapter: ContentStorageAdapter;\n private resolver: ContentResolver;\n private logger: Logger;\n protected isRegistered = false;\n\n constructor(\n maxMessageStorage: number = 1000,\n referenceConfig?: Partial<ContentReferenceConfig>,\n logger?: Logger\n ) {\n this.logger = logger || new Logger({ module: 'ContentStoreManager' });\n\n this.contentStorage = new ContentStorage(\n maxMessageStorage,\n referenceConfig\n );\n this.adapter = new ContentStorageAdapter(this.contentStorage);\n this.resolver = new ContentResolver(this.adapter);\n }\n\n /**\n * Initialize and register content storage for cross-package access\n */\n async initialize(): Promise<void> {\n if (this.isRegistered) {\n this.logger.warn('ContentStoreManager is already initialized');\n return;\n }\n\n try {\n if (\n ContentStoreService &&\n typeof (ContentStoreService as unknown as { setInstance?: Function }).setInstance === 'function'\n ) {\n await (ContentStoreService as unknown as { setInstance: (adapter: unknown) => Promise<void> }).setInstance(\n this.adapter\n );\n } else {\n this.logger.warn('ContentStoreService.setInstance is unavailable; skipping registration');\n }\n if (\n ContentResolverRegistry &&\n typeof (ContentResolverRegistry as unknown as { register?: Function }).register === 'function'\n ) {\n (ContentResolverRegistry as unknown as { register: (resolver: unknown) => void }).register(\n this.resolver\n );\n } else {\n this.logger.warn('ContentResolverRegistry.register is unavailable; skipping registration');\n }\n this.isRegistered = true;\n this.logger.info(\n 'ContentStoreManager initialized and registered for cross-package access'\n );\n } catch (error) {\n this.logger.error('Failed to initialize ContentStoreManager:', error);\n throw error;\n }\n }\n\n /**\n * Get the underlying ContentStorage instance\n */\n getContentStorage(): ContentStorage {\n return this.contentStorage;\n }\n\n /**\n * Get storage statistics\n */\n async getStats(): Promise<ContentReferenceStats> {\n return await this.contentStorage.getStats();\n }\n\n /**\n * Update configuration\n */\n async updateConfig(config: Partial<ContentReferenceConfig>): Promise<void> {\n return await this.contentStorage.updateConfig(config);\n }\n\n /**\n * Perform manual cleanup\n */\n async performCleanup(): Promise<{ cleanedUp: number; errors: string[] }> {\n return await this.contentStorage.performCleanup();\n }\n\n /**\n * Check if content should be stored as reference\n */\n shouldUseReference(content: Buffer | string): boolean {\n return this.contentStorage.shouldUseReference(content);\n }\n\n /**\n * Store content if it's large enough\n */\n async storeContentIfLarge(\n content: Buffer | string,\n metadata: AdapterContentMetadata\n ): Promise<ContentReference | null> {\n const storeMetadata = {\n source: 'system' as const,\n contentType: 'binary' as const,\n ...metadata,\n };\n return await this.contentStorage.storeContentIfLarge(\n content,\n storeMetadata\n );\n }\n\n /**\n * Cleanup and unregister\n */\n async dispose(): Promise<void> {\n if (this.isRegistered) {\n this.contentStorage.dispose();\n if (\n ContentStoreService &&\n typeof (ContentStoreService as unknown as { dispose?: Function }).dispose === 'function'\n ) {\n (ContentStoreService as unknown as { dispose: () => void }).dispose();\n }\n if (\n ContentResolverRegistry &&\n typeof (ContentResolverRegistry as unknown as { unregister?: Function }).unregister === 'function'\n ) {\n (ContentResolverRegistry as unknown as { unregister: () => void }).unregister();\n }\n this.isRegistered = false;\n this.logger.info('ContentStoreManager disposed and unregistered');\n }\n }\n\n /**\n * Check if the manager is initialized\n */\n isInitialized(): boolean {\n return this.isRegistered;\n }\n}\n"],"names":[],"mappings":";;AAuCA,MAAM,sBAAuD;AAAA,EAC3D,YAAoB,SAAyB;AAAzB,SAAA,UAAA;AAAA,EAA0B;AAAA,EAE9C,MAAM,aACJ,SACA,UACiB;AACjB,UAAM,gBAAgB;AAAA,MACpB,aAAa;AAAA,MACb,WAAW,QAAQ;AAAA,MACnB,QAAQ;AAAA,MACR,GAAG;AAAA,IAAA;AAEL,UAAM,aAAa,MAAM,KAAK,QAAQ,aAAa,SAAS,aAAa;AACzE,WAAO,WAAW;AAAA,EACpB;AAAA,EAEA,MAAM,iBACJ,aACoC;AACpC,UAAM,SAAS,MAAM,KAAK,QAAQ,iBAAiB,WAAW;AAC9D,QAAI,OAAO,WAAW,OAAO,SAAS;AACpC,YAAM,WAAsC;AAAA,QAC1C,SAAS,OAAO;AAAA,MAAA;AAElB,UAAI,OAAO,UAAU;AACnB,iBAAS,WAAW;A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AAK,eAAe,eAAA;AAAA,EACnC;AAAA;AAAA;AAAA;AAAA,EAKA,mBAAmB,SAAmC;AACpD,WAAO,KAAK,eAAe,mBAAmB,OAAO;AAAA,EACvD;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,oBACJ,SACA,UACkC;AAClC,UAAM,gBAAgB;AAAA,MACpB,QAAQ;AAAA,MACR,aAAa;AAAA,MACb,GAAG;AAAA,IAAA;AAEL,WAAO,MAAM,KAAK,eAAe;AAAA,MAC/B;AAAA,MACA;AAAA,IAAA;AAAA,EAEJ;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,UAAyB;AAC7B,QAAI,KAAK,cAAc;AACrB,WAAK,eAAe,QAAA;AACpB,UACE,uBACA,OAAQ,oBAA0D,YAAY,YAC9E;AACC,4BAA2D,QAAA;AAAA,MAC9D;AACA,UACE,2BACA,OAAQ,wBAAiE,eAAe,YACxF;AACC,gCAAkE,WAAA;AAAA,MACrE;AACA,WAAK,eAAe;AACpB,WAAK,OAAO,KAAK,+CAA+C;AAAA,IAClE;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,gBAAyB;AACvB,WAAO,KAAK;AAAA,EACd;AACF;"}
@@ -1 +1 @@
1
- {"version":3,"file":"index26.js","sources":["../../src/services/formatters/types.ts"],"sourcesContent":["export enum EntityFormat {\n TOPIC_ID = 'topicId',\n HRL = 'hrl',\n SCHEDULE_ID = 'scheduleId',\n TOKEN_ID = 'tokenId',\n ADDRESS = 'address',\n SYMBOL = 'symbol',\n SERIAL_NUMBER = 'serialNumber',\n METADATA = 'metadata',\n ACCOUNT_ID = 'accountId',\n ALIAS = 'alias',\n EVM_ADDRESS = 'evmAddress',\n CONTRACT_ID = 'contractId',\n FILE_ID = 'fileId',\n ANY = 'any'\n}\n\nexport interface ConversionContext {\n networkType?: string;\n sessionId?: string;\n toolName?: string;\n toolPreferences?: Record<string, string>;\n [key: string]: unknown;\n}\n\nexport interface FormatConverter<TSource = string, TTarget = string> {\n sourceFormat: EntityFormat;\n targetFormat: EntityFormat;\n canConvert(source: string, context: ConversionContext): boolean;\n convert(entity: TSource, context: ConversionContext): Promise<TTarget>;\n}"],"names":["EntityFormat"],"mappings":"AAAO,IAAK,iCAAAA,kBAAL;AACLA,gBAAA,UAAA,IAAW;AACXA,gBAAA,KAAA,IAAM;AACNA,gBAAA,aAAA,IAAc;AACdA,gBAAA,UAAA,IAAW;AACXA,gBAAA,SAAA,IAAU;AACVA,gBAAA,QAAA,IAAS;AACTA,gBAAA,eAAA,IAAgB;AAChBA,gBAAA,UAAA,IAAW;AACXA,gBAAA,YAAA,IAAa;AACbA,gBAAA,OAAA,IAAQ;AACRA,gBAAA,aAAA,IAAc;AACdA,gBAAA,aAAA,IAAc;AACdA,gBAAA,SAAA,IAAU;AACVA,gBAAA,KAAA,IAAM;AAdI,SAAAA;AAAA,GAAA,gBAAA,CAAA,CAAA;"}
1
+ {"version":3,"file":"index26.js","sources":["../../src/services/formatters/types.ts"],"sourcesContent":["import { NetworkType } from '@hashgraphonline/standards-sdk';\n\nexport enum EntityFormat {\n TOPIC_ID = 'topicId',\n HRL = 'hrl',\n SCHEDULE_ID = 'scheduleId',\n TOKEN_ID = 'tokenId',\n ADDRESS = 'address',\n SYMBOL = 'symbol',\n SERIAL_NUMBER = 'serialNumber',\n METADATA = 'metadata',\n ACCOUNT_ID = 'accountId',\n ALIAS = 'alias',\n EVM_ADDRESS = 'evmAddress',\n CONTRACT_ID = 'contractId',\n FILE_ID = 'fileId',\n ANY = 'any'\n}\n\nexport interface ConversionContext {\n networkType?: NetworkType;\n sessionId?: string;\n toolName?: string;\n toolPreferences?: Record<string, string>;\n [key: string]: unknown;\n}\n\nexport interface FormatConverter<TSource = string, TTarget = string> {\n sourceFormat: EntityFormat;\n targetFormat: EntityFormat;\n canConvert(source: string, context: ConversionContext): boolean;\n convert(entity: TSource, context: ConversionContext): Promise<TTarget>;\n}"],"names":["EntityFormat"],"mappings":"AAEO,IAAK,iCAAAA,kBAAL;AACLA,gBAAA,UAAA,IAAW;AACXA,gBAAA,KAAA,IAAM;AACNA,gBAAA,aAAA,IAAc;AACdA,gBAAA,UAAA,IAAW;AACXA,gBAAA,SAAA,IAAU;AACVA,gBAAA,QAAA,IAAS;AACTA,gBAAA,eAAA,IAAgB;AAChBA,gBAAA,UAAA,IAAW;AACXA,gBAAA,YAAA,IAAa;AACbA,gBAAA,OAAA,IAAQ;AACRA,gBAAA,aAAA,IAAc;AACdA,gBAAA,aAAA,IAAc;AACdA,gBAAA,SAAA,IAAU;AACVA,gBAAA,KAAA,IAAM;AAdI,SAAAA;AAAA,GAAA,gBAAA,CAAA,CAAA;"}