@hashgraphonline/conversational-agent 0.2.103 → 0.2.106

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 (70) hide show
  1. package/dist/cjs/conversational-agent.d.ts +11 -2
  2. package/dist/cjs/core/tool-registry.d.ts +3 -0
  3. package/dist/cjs/forms/field-guidance-registry.d.ts +33 -0
  4. package/dist/cjs/index.cjs +1 -1
  5. package/dist/cjs/index.cjs.map +1 -1
  6. package/dist/cjs/index.d.ts +1 -0
  7. package/dist/cjs/plugins/inscribe/InscribePlugin.d.ts +1 -0
  8. package/dist/cjs/runtime/wallet-bridge.d.ts +23 -0
  9. package/dist/cjs/signers/browser-signer.d.ts +32 -0
  10. package/dist/esm/index.js +3 -0
  11. package/dist/esm/index.js.map +1 -1
  12. package/dist/esm/index10.js +13 -5
  13. package/dist/esm/index10.js.map +1 -1
  14. package/dist/esm/index13.js +157 -179
  15. package/dist/esm/index13.js.map +1 -1
  16. package/dist/esm/index2.js +29 -25
  17. package/dist/esm/index2.js.map +1 -1
  18. package/dist/esm/index21.js +1 -1
  19. package/dist/esm/index23.js +3 -3
  20. package/dist/esm/index3.js.map +1 -1
  21. package/dist/esm/index33.js +5 -5
  22. package/dist/esm/index33.js.map +1 -1
  23. package/dist/esm/index36.js +8 -45
  24. package/dist/esm/index36.js.map +1 -1
  25. package/dist/esm/index37.js +41 -102
  26. package/dist/esm/index37.js.map +1 -1
  27. package/dist/esm/index38.js +107 -21
  28. package/dist/esm/index38.js.map +1 -1
  29. package/dist/esm/index39.js +66 -12
  30. package/dist/esm/index39.js.map +1 -1
  31. package/dist/esm/index4.js +43 -0
  32. package/dist/esm/index4.js.map +1 -1
  33. package/dist/esm/index40.js +21 -7
  34. package/dist/esm/index40.js.map +1 -1
  35. package/dist/esm/index41.js +11 -4
  36. package/dist/esm/index41.js.map +1 -1
  37. package/dist/esm/index42.js +7 -255
  38. package/dist/esm/index42.js.map +1 -1
  39. package/dist/esm/index43.js +5 -184
  40. package/dist/esm/index43.js.map +1 -1
  41. package/dist/esm/index44.js +254 -75
  42. package/dist/esm/index44.js.map +1 -1
  43. package/dist/esm/index45.js +181 -24
  44. package/dist/esm/index45.js.map +1 -1
  45. package/dist/esm/index46.js +30 -0
  46. package/dist/esm/index46.js.map +1 -0
  47. package/dist/esm/index47.js +95 -0
  48. package/dist/esm/index47.js.map +1 -0
  49. package/dist/esm/index5.js +2 -2
  50. package/dist/esm/index6.js +153 -46
  51. package/dist/esm/index6.js.map +1 -1
  52. package/dist/types/conversational-agent.d.ts +11 -2
  53. package/dist/types/core/tool-registry.d.ts +3 -0
  54. package/dist/types/forms/field-guidance-registry.d.ts +33 -0
  55. package/dist/types/index.d.ts +1 -0
  56. package/dist/types/plugins/inscribe/InscribePlugin.d.ts +1 -0
  57. package/dist/types/runtime/wallet-bridge.d.ts +23 -0
  58. package/dist/types/signers/browser-signer.d.ts +32 -0
  59. package/package.json +19 -10
  60. package/src/conversational-agent.ts +181 -59
  61. package/src/core/tool-registry.ts +25 -0
  62. package/src/forms/field-guidance-registry.ts +215 -188
  63. package/src/forms/form-generator.ts +28 -12
  64. package/src/index.ts +1 -0
  65. package/src/langchain/langchain-agent.ts +1 -1
  66. package/src/plugins/hcs-10/HCS10Plugin.ts +32 -28
  67. package/src/plugins/hcs-2/HCS2Plugin.ts +4 -2
  68. package/src/plugins/inscribe/InscribePlugin.ts +47 -2
  69. package/src/runtime/wallet-bridge.ts +41 -0
  70. package/src/signers/browser-signer.ts +112 -0
@@ -1 +1 @@
1
- {"version":3,"file":"index45.js","sources":["../../src/types/content-reference.ts"],"sourcesContent":["/**\n * Content Reference System Types\n *\n * Shared interfaces for the Reference-Based Content System that handles\n * large content storage with unique reference IDs to optimize context window usage.\n */\n\n/**\n * Unique identifier for stored content references\n * Format: Cryptographically secure 32-byte identifier with base64url encoding\n */\nexport type ReferenceId = string;\n\n/**\n * Lifecycle state of a content reference\n */\nexport type ReferenceLifecycleState =\n | 'active'\n | 'expired'\n | 'cleanup_pending'\n | 'invalid';\n\n/**\n * Content types supported by the reference system\n */\nexport type ContentType =\n | 'text'\n | 'json'\n | 'html'\n | 'markdown'\n | 'binary'\n | 'unknown';\n\n/**\n * Sources that created the content reference\n */\nexport type ContentSource =\n | 'mcp_tool'\n | 'user_upload'\n | 'agent_generated'\n | 'system';\n\n/**\n * Metadata associated with stored content\n */\nexport interface ContentMetadata {\n /** Content type classification */\n contentType: ContentType;\n\n /** MIME type of the original content */\n mimeType?: string;\n\n /** Size in bytes of the stored content */\n sizeBytes: number;\n\n /** When the content was originally stored */\n createdAt: Date;\n\n /** Last time the content was accessed via reference resolution */\n lastAccessedAt: Date;\n\n /** Source that created this content reference */\n source: ContentSource;\n\n /** Name of the MCP tool that generated the content (if applicable) */\n mcpToolName?: string;\n\n /** Original filename or suggested name for the content */\n fileName?: string;\n\n /** Number of times this reference has been resolved */\n accessCount: number;\n\n /** Tags for categorization and cleanup policies */\n tags?: string[];\n\n /** Custom metadata from the source */\n customMetadata?: Record<string, unknown>;\n}\n\n/**\n * Core content reference object passed through agent context\n * Designed to be lightweight (<100 tokens) while providing enough\n * information for agent decision-making\n */\nexport interface ContentReference {\n /** Unique identifier for resolving the content */\n referenceId: ReferenceId;\n\n /** Current lifecycle state */\n state: ReferenceLifecycleState;\n\n /** Brief description or preview of the content (max 200 chars) */\n preview: string;\n\n /** Essential metadata for agent decision-making */\n metadata: Pick<\n ContentMetadata,\n 'contentType' | 'sizeBytes' | 'source' | 'fileName' | 'mimeType'\n >;\n\n /** When this reference was created */\n createdAt: Date;\n\n /** Special format indicator for reference IDs in content */\n readonly format: 'ref://{id}';\n}\n\n/**\n * Result of attempting to resolve a content reference\n */\nexport interface ReferenceResolutionResult {\n /** Whether the resolution was successful */\n success: boolean;\n\n /** The resolved content if successful */\n content?: Buffer;\n\n /** Complete metadata if successful */\n metadata?: ContentMetadata;\n\n /** Error message if resolution failed */\n error?: string;\n\n /** Specific error type for targeted error handling */\n errorType?:\n | 'not_found'\n | 'expired'\n | 'corrupted'\n | 'access_denied'\n | 'system_error';\n\n /** Suggested actions for recovery */\n suggestedActions?: string[];\n}\n\n/**\n * Configuration for content reference storage and lifecycle\n */\nexport interface ContentReferenceConfig {\n /** Size threshold above which content should be stored as references (default: 10KB) */\n sizeThresholdBytes: number;\n\n /** Maximum age for unused references before cleanup (default: 1 hour) */\n maxAgeMs: number;\n\n /** Maximum number of references to store simultaneously */\n maxReferences: number;\n\n /** Maximum total storage size for all references */\n maxTotalStorageBytes: number;\n\n /** Whether to enable automatic cleanup */\n enableAutoCleanup: boolean;\n\n /** Interval for cleanup checks in milliseconds */\n cleanupIntervalMs: number;\n\n /** Whether to persist references across restarts */\n enablePersistence: boolean;\n\n /** Storage backend configuration */\n storageBackend: 'memory' | 'filesystem' | 'hybrid';\n\n /** Cleanup policies for different content types */\n cleanupPolicies: {\n /** Policy for content marked as \"recent\" from MCP tools */\n recent: { maxAgeMs: number; priority: number };\n\n /** Policy for user-uploaded content */\n userContent: { maxAgeMs: number; priority: number };\n\n /** Policy for agent-generated content */\n agentGenerated: { maxAgeMs: number; priority: number };\n\n /** Default policy for other content */\n default: { maxAgeMs: number; priority: number };\n };\n}\n\n/**\n * Default configuration values\n */\nexport const DEFAULT_CONTENT_REFERENCE_CONFIG: ContentReferenceConfig = {\n sizeThresholdBytes: 10 * 1024,\n maxAgeMs: 60 * 60 * 1000,\n maxReferences: 100,\n maxTotalStorageBytes: 100 * 1024 * 1024,\n enableAutoCleanup: true,\n cleanupIntervalMs: 5 * 60 * 1000,\n enablePersistence: false,\n storageBackend: 'memory',\n cleanupPolicies: {\n recent: { maxAgeMs: 30 * 60 * 1000, priority: 1 },\n userContent: { maxAgeMs: 2 * 60 * 60 * 1000, priority: 2 },\n agentGenerated: { maxAgeMs: 60 * 60 * 1000, priority: 3 },\n default: { maxAgeMs: 60 * 60 * 1000, priority: 4 },\n },\n};\n\n/**\n * Statistics about content reference usage and storage\n */\nexport interface ContentReferenceStats {\n /** Total number of active references */\n activeReferences: number;\n\n /** Total storage used by all references in bytes */\n totalStorageBytes: number;\n\n /** Number of references cleaned up in last cleanup cycle */\n recentlyCleanedUp: number;\n\n /** Number of successful reference resolutions since startup */\n totalResolutions: number;\n\n /** Number of failed resolution attempts */\n failedResolutions: number;\n\n /** Average content size in bytes */\n averageContentSize: number;\n\n /** Most frequently accessed reference ID */\n mostAccessedReferenceId?: ReferenceId;\n\n /** Storage utilization percentage */\n storageUtilization: number;\n\n /** Performance metrics */\n performanceMetrics: {\n /** Average time to create a reference in milliseconds */\n averageCreationTimeMs: number;\n\n /** Average time to resolve a reference in milliseconds */\n averageResolutionTimeMs: number;\n\n /** Average cleanup time in milliseconds */\n averageCleanupTimeMs: number;\n };\n}\n\n/**\n * Error types for content reference operations\n */\nexport class ContentReferenceError extends Error {\n constructor(\n message: string,\n public readonly type: ReferenceResolutionResult['errorType'],\n public readonly referenceId?: ReferenceId,\n public readonly suggestedActions?: string[]\n ) {\n super(message);\n this.name = 'ContentReferenceError';\n }\n}\n\n/**\n * Interface for content reference storage implementations\n */\nexport interface ContentReferenceStore {\n /**\n * Store content and return a reference\n */\n storeContent(\n content: Buffer,\n metadata: Omit<\n ContentMetadata,\n 'createdAt' | 'lastAccessedAt' | 'accessCount'\n >\n ): Promise<ContentReference>;\n\n /**\n * Resolve a reference to its content\n */\n resolveReference(\n referenceId: ReferenceId\n ): Promise<ReferenceResolutionResult>;\n\n /**\n * Check if a reference exists and is valid\n */\n hasReference(referenceId: ReferenceId): Promise<boolean>;\n\n /**\n * Mark a reference for cleanup\n */\n cleanupReference(referenceId: ReferenceId): Promise<boolean>;\n\n /**\n * Get current storage statistics\n */\n getStats(): Promise<ContentReferenceStats>;\n\n /**\n * Update configuration\n */\n updateConfig(config: Partial<ContentReferenceConfig>): Promise<void>;\n\n /**\n * Perform cleanup based on current policies\n */\n performCleanup(): Promise<{ cleanedUp: number; errors: string[] }>;\n\n /**\n * Dispose of resources\n */\n dispose(): Promise<void>;\n}\n"],"names":[],"mappings":"AAuLO,MAAM,mCAA2D;AAAA,EACtE,oBAAoB,KAAK;AAAA,EACzB,UAAU,KAAK,KAAK;AAAA,EACpB,eAAe;AAAA,EACf,sBAAsB,MAAM,OAAO;AAAA,EACnC,mBAAmB;AAAA,EACnB,mBAAmB,IAAI,KAAK;AAAA,EAC5B,mBAAmB;AAAA,EACnB,gBAAgB;AAAA,EAChB,iBAAiB;AAAA,IACf,QAAQ,EAAE,UAAU,KAAK,KAAK,KAAM,UAAU,EAAA;AAAA,IAC9C,aAAa,EAAE,UAAU,IAAI,KAAK,KAAK,KAAM,UAAU,EAAA;AAAA,IACvD,gBAAgB,EAAE,UAAU,KAAK,KAAK,KAAM,UAAU,EAAA;AAAA,IACtD,SAAS,EAAE,UAAU,KAAK,KAAK,KAAM,UAAU,EAAA;AAAA,EAAE;AAErD;AA8CO,MAAM,8BAA8B,MAAM;AAAA,EAC/C,YACE,SACgB,MACA,aACA,kBAChB;AACA,UAAM,OAAO;AAJG,SAAA,OAAA;AACA,SAAA,cAAA;AACA,SAAA,mBAAA;AAGhB,SAAK,OAAO;AAAA,EACd;AACF;"}
1
+ {"version":3,"file":"index45.js","sources":["../../src/execution/execution-pipeline.ts"],"sourcesContent":["import { ZodError } from 'zod';\nimport { Logger } from '@hashgraphonline/standards-sdk';\nimport { SmartMemoryManager } from '../memory/smart-memory-manager';\nimport { FormEngine, ToolExecutionResult } from '../forms/form-engine';\nimport type { FormMessage, FormSubmission } from '../forms/types';\nimport type { ToolRegistry, ToolRegistryEntry } from '../core/tool-registry';\n\n/**\n * Session context for tool execution\n */\nexport interface SessionContext {\n sessionId: string;\n userId?: string;\n timestamp: number;\n conversationId?: string;\n}\n\n/**\n * Context passed through execution pipeline\n */\nexport interface ExecutionContext {\n toolName: string;\n input: unknown;\n session: SessionContext;\n memory: SmartMemoryManager;\n traceId: string;\n toolEntry: ToolRegistryEntry;\n}\n\n/**\n * Result of tool execution with metadata\n */\nexport interface ExecutionResult extends ToolExecutionResult {\n traceId: string;\n executionTime: number;\n}\n\n/**\n * ExecutionPipeline handles tool execution coordination\n */\nexport class ExecutionPipeline {\n private logger: Logger;\n private toolRegistry: ToolRegistry;\n private formEngine: FormEngine;\n private memory: SmartMemoryManager;\n\n constructor(\n toolRegistry: ToolRegistry,\n formEngine: FormEngine,\n memory: SmartMemoryManager,\n logger?: Logger\n ) {\n this.toolRegistry = toolRegistry;\n this.formEngine = formEngine;\n this.memory = memory;\n this.logger = logger || new Logger({ module: 'ExecutionPipeline' });\n }\n\n /**\n * Execute a tool through the pipeline\n */\n async execute(\n toolName: string,\n input: unknown,\n sessionContext?: SessionContext\n ): Promise<ExecutionResult> {\n const traceId = `trace-${Date.now()}-${Math.random()\n .toString(36)\n .substr(2, 9)}`;\n const startTime = Date.now();\n\n const toolEntry = this.toolRegistry.getTool(toolName);\n if (!toolEntry) {\n throw new Error(`Tool not found in registry: ${toolName}`);\n }\n\n const context: ExecutionContext = {\n toolName,\n input,\n session: sessionContext || this.buildDefaultSession(),\n memory: this.memory,\n traceId,\n toolEntry,\n };\n\n try {\n const shouldGenerateForm = await this.checkFormGeneration(context);\n if (shouldGenerateForm.requiresForm && shouldGenerateForm.formMessage) {\n return {\n success: false,\n output: 'Form generation required',\n requiresForm: true,\n formMessage: shouldGenerateForm.formMessage,\n traceId,\n executionTime: Date.now() - startTime,\n };\n }\n\n const result = await this.executeToolDirect(context);\n\n return {\n success: true,\n output: result,\n traceId,\n executionTime: Date.now() - startTime,\n };\n } catch (error) {\n return this.handleExecutionError(\n error,\n context,\n traceId,\n Date.now() - startTime\n );\n }\n }\n\n /**\n * Execute tool with validation\n */\n async executeWithValidation(\n toolName: string,\n input: unknown,\n sessionContext?: SessionContext\n ): Promise<ExecutionResult> {\n return this.execute(toolName, input, sessionContext);\n }\n\n /**\n * Process form submission\n */\n async processFormSubmission(\n toolName: string,\n formId: string,\n parameters: Record<string, unknown>,\n sessionContext?: SessionContext\n ): Promise<ExecutionResult> {\n const traceId = `form-${Date.now()}-${Math.random()\n .toString(36)\n .substr(2, 9)}`;\n const startTime = Date.now();\n\n try {\n const formSubmission: FormSubmission = {\n formId,\n toolName,\n parameters,\n timestamp: Date.now(),\n };\n\n const processedInput = await this.formEngine.processSubmission(\n formSubmission\n );\n\n return this.execute(toolName, processedInput, sessionContext);\n } catch (error) {\n return {\n success: false,\n output: 'Form submission processing failed',\n error: error instanceof Error ? error.message : String(error),\n traceId,\n executionTime: Date.now() - startTime,\n };\n }\n }\n\n /**\n * Check if form generation is required\n */\n private async checkFormGeneration(context: ExecutionContext): Promise<{\n requiresForm: boolean;\n formMessage?: FormMessage;\n }> {\n const inputRecord = context.input as Record<string, unknown>;\n if (inputRecord?.__fromForm === true || inputRecord?.renderForm === false) {\n return { requiresForm: false };\n }\n\n if (\n !this.formEngine.shouldGenerateForm(context.toolEntry.tool, context.input)\n ) {\n return { requiresForm: false };\n }\n\n const formMessage = await this.formEngine.generateForm(\n context.toolName,\n context.toolEntry.tool,\n context.input\n );\n\n if (formMessage) {\n return { requiresForm: true, formMessage };\n }\n\n return { requiresForm: false };\n }\n\n /**\n * Execute tool directly\n */\n private async executeToolDirect(context: ExecutionContext): Promise<string> {\n const { toolEntry, input } = context;\n const parameters = (input as Record<string, unknown>) || {};\n const mergedArgs = { ...parameters, renderForm: false };\n\n if (toolEntry.wrapper) {\n return this.executeWrappedTool(toolEntry, mergedArgs);\n }\n\n return await toolEntry.tool.call(mergedArgs);\n }\n\n /**\n * Execute wrapped tool\n */\n private async executeWrappedTool(\n toolEntry: ToolRegistryEntry,\n mergedArgs: Record<string, unknown>\n ): Promise<string> {\n const wrapper = toolEntry.wrapper;\n if (!wrapper) {\n throw new Error('Tool wrapper not found');\n }\n\n const wrapperAsAny = wrapper as unknown as {\n executeOriginal?: (args: Record<string, unknown>) => Promise<string>;\n originalTool?: {\n call?: (args: Record<string, unknown>) => Promise<string>;\n };\n };\n\n if (wrapperAsAny.executeOriginal) {\n return await wrapperAsAny.executeOriginal(mergedArgs);\n }\n\n if (wrapperAsAny.originalTool?.call) {\n return await wrapperAsAny.originalTool.call(mergedArgs);\n }\n\n return await toolEntry.originalTool.call(mergedArgs);\n }\n\n /**\n * Handle execution error\n */\n private handleExecutionError(\n error: unknown,\n context: ExecutionContext,\n traceId: string,\n executionTime: number\n ): ExecutionResult {\n const errorMessage = error instanceof Error ? error.message : String(error);\n\n if (error instanceof ZodError) {\n return {\n success: false,\n output: 'Validation error occurred',\n error: errorMessage,\n traceId,\n executionTime,\n };\n }\n\n this.logger.error(`Tool execution failed: ${context.toolName}`, {\n traceId,\n error: errorMessage,\n });\n\n return {\n success: false,\n output: 'Tool execution failed',\n error: errorMessage,\n traceId,\n executionTime,\n };\n }\n\n /**\n * Build default session context\n */\n private buildDefaultSession(): SessionContext {\n return {\n sessionId: `session-${Date.now()}-${Math.random()\n .toString(36)\n .substr(2, 9)}`,\n timestamp: Date.now(),\n };\n }\n\n /**\n * Get statistics about the pipeline\n */\n getStatistics(): {\n totalMiddleware: number;\n registeredMiddleware: string[];\n } {\n return {\n totalMiddleware: 0,\n registeredMiddleware: [],\n };\n }\n}\n"],"names":[],"mappings":";;AAwCO,MAAM,kBAAkB;AAAA,EAM7B,YACE,cACA,YACA,QACA,QACA;AACA,SAAK,eAAe;AACpB,SAAK,aAAa;AAClB,SAAK,SAAS;AACd,SAAK,SAAS,UAAU,IAAI,OAAO,EAAE,QAAQ,qBAAqB;AAAA,EACpE;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,QACJ,UACA,OACA,gBAC0B;AAC1B,UAAM,UAAU,SAAS,KAAK,IAAA,CAAK,IAAI,KAAK,OAAA,EACzC,SAAS,EAAE,EACX,OAAO,GAAG,CAAC,CAAC;AACf,UAAM,YAAY,KAAK,IAAA;AAEvB,UAAM,YAAY,KAAK,aAAa,QAAQ,QAAQ;AACpD,QAAI,CAAC,WAAW;AACd,YAAM,IAAI,MAAM,+BAA+B,QAAQ,EAAE;AAAA,IAC3D;AAEA,UAAM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AAEA,QAAI,aAAa,cAAc,MAAM;AACnC,aAAO,MAAM,aAAa,aAAa,KAAK,UAAU;AAAA,IACxD;AAEA,WAAO,MAAM,UAAU,aAAa,KAAK,UAAU;AAAA,EACrD;AAAA;AAAA;AAAA;AAAA,EAKQ,qBACN,OACA,SACA,SACA,eACiB;AACjB,UAAM,eAAe,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAE1E,QAAI,iBAAiB,UAAU;AAC7B,aAAO;AAAA,QACL,SAAS;AAAA,QACT,QAAQ;AAAA,QACR,OAAO;AAAA,QACP;AAAA,QACA;AAAA,MAAA;AAAA,IAEJ;AAEA,SAAK,OAAO,MAAM,0BAA0B,QAAQ,QAAQ,IAAI;AAAA,MAC9D;AAAA,MACA,OAAO;AAAA,IAAA,CACR;AAED,WAAO;AAAA,MACL,SAAS;AAAA,MACT,QAAQ;AAAA,MACR,OAAO;AAAA,MACP;AAAA,MACA;AAAA,IAAA;AAAA,EAEJ;AAAA;AAAA;AAAA;AAAA,EAKQ,sBAAsC;AAC5C,WAAO;AAAA,MACL,WAAW,WAAW,KAAK,IAAA,CAAK,IAAI,KAAK,OAAA,EACtC,SAAS,EAAE,EACX,OAAO,GAAG,CAAC,CAAC;AAAA,MACf,WAAW,KAAK,IAAA;AAAA,IAAI;AAAA,EAExB;AAAA;AAAA;AAAA;AAAA,EAKA,gBAGE;AACA,WAAO;AAAA,MACL,iBAAiB;AAAA,MACjB,sBAAsB,CAAA;AAAA,IAAC;AAAA,EAE3B;AACF;"}
@@ -0,0 +1,30 @@
1
+ const DEFAULT_CONTENT_REFERENCE_CONFIG = {
2
+ sizeThresholdBytes: 10 * 1024,
3
+ maxAgeMs: 60 * 60 * 1e3,
4
+ maxReferences: 100,
5
+ maxTotalStorageBytes: 100 * 1024 * 1024,
6
+ enableAutoCleanup: true,
7
+ cleanupIntervalMs: 5 * 60 * 1e3,
8
+ enablePersistence: false,
9
+ storageBackend: "memory",
10
+ cleanupPolicies: {
11
+ recent: { maxAgeMs: 30 * 60 * 1e3, priority: 1 },
12
+ userContent: { maxAgeMs: 2 * 60 * 60 * 1e3, priority: 2 },
13
+ agentGenerated: { maxAgeMs: 60 * 60 * 1e3, priority: 3 },
14
+ default: { maxAgeMs: 60 * 60 * 1e3, priority: 4 }
15
+ }
16
+ };
17
+ class ContentReferenceError extends Error {
18
+ constructor(message, type, referenceId, suggestedActions) {
19
+ super(message);
20
+ this.type = type;
21
+ this.referenceId = referenceId;
22
+ this.suggestedActions = suggestedActions;
23
+ this.name = "ContentReferenceError";
24
+ }
25
+ }
26
+ export {
27
+ ContentReferenceError,
28
+ DEFAULT_CONTENT_REFERENCE_CONFIG
29
+ };
30
+ //# sourceMappingURL=index46.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index46.js","sources":["../../src/types/content-reference.ts"],"sourcesContent":["/**\n * Content Reference System Types\n *\n * Shared interfaces for the Reference-Based Content System that handles\n * large content storage with unique reference IDs to optimize context window usage.\n */\n\n/**\n * Unique identifier for stored content references\n * Format: Cryptographically secure 32-byte identifier with base64url encoding\n */\nexport type ReferenceId = string;\n\n/**\n * Lifecycle state of a content reference\n */\nexport type ReferenceLifecycleState =\n | 'active'\n | 'expired'\n | 'cleanup_pending'\n | 'invalid';\n\n/**\n * Content types supported by the reference system\n */\nexport type ContentType =\n | 'text'\n | 'json'\n | 'html'\n | 'markdown'\n | 'binary'\n | 'unknown';\n\n/**\n * Sources that created the content reference\n */\nexport type ContentSource =\n | 'mcp_tool'\n | 'user_upload'\n | 'agent_generated'\n | 'system';\n\n/**\n * Metadata associated with stored content\n */\nexport interface ContentMetadata {\n /** Content type classification */\n contentType: ContentType;\n\n /** MIME type of the original content */\n mimeType?: string;\n\n /** Size in bytes of the stored content */\n sizeBytes: number;\n\n /** When the content was originally stored */\n createdAt: Date;\n\n /** Last time the content was accessed via reference resolution */\n lastAccessedAt: Date;\n\n /** Source that created this content reference */\n source: ContentSource;\n\n /** Name of the MCP tool that generated the content (if applicable) */\n mcpToolName?: string;\n\n /** Original filename or suggested name for the content */\n fileName?: string;\n\n /** Number of times this reference has been resolved */\n accessCount: number;\n\n /** Tags for categorization and cleanup policies */\n tags?: string[];\n\n /** Custom metadata from the source */\n customMetadata?: Record<string, unknown>;\n}\n\n/**\n * Core content reference object passed through agent context\n * Designed to be lightweight (<100 tokens) while providing enough\n * information for agent decision-making\n */\nexport interface ContentReference {\n /** Unique identifier for resolving the content */\n referenceId: ReferenceId;\n\n /** Current lifecycle state */\n state: ReferenceLifecycleState;\n\n /** Brief description or preview of the content (max 200 chars) */\n preview: string;\n\n /** Essential metadata for agent decision-making */\n metadata: Pick<\n ContentMetadata,\n 'contentType' | 'sizeBytes' | 'source' | 'fileName' | 'mimeType'\n >;\n\n /** When this reference was created */\n createdAt: Date;\n\n /** Special format indicator for reference IDs in content */\n readonly format: 'ref://{id}';\n}\n\n/**\n * Result of attempting to resolve a content reference\n */\nexport interface ReferenceResolutionResult {\n /** Whether the resolution was successful */\n success: boolean;\n\n /** The resolved content if successful */\n content?: Buffer;\n\n /** Complete metadata if successful */\n metadata?: ContentMetadata;\n\n /** Error message if resolution failed */\n error?: string;\n\n /** Specific error type for targeted error handling */\n errorType?:\n | 'not_found'\n | 'expired'\n | 'corrupted'\n | 'access_denied'\n | 'system_error';\n\n /** Suggested actions for recovery */\n suggestedActions?: string[];\n}\n\n/**\n * Configuration for content reference storage and lifecycle\n */\nexport interface ContentReferenceConfig {\n /** Size threshold above which content should be stored as references (default: 10KB) */\n sizeThresholdBytes: number;\n\n /** Maximum age for unused references before cleanup (default: 1 hour) */\n maxAgeMs: number;\n\n /** Maximum number of references to store simultaneously */\n maxReferences: number;\n\n /** Maximum total storage size for all references */\n maxTotalStorageBytes: number;\n\n /** Whether to enable automatic cleanup */\n enableAutoCleanup: boolean;\n\n /** Interval for cleanup checks in milliseconds */\n cleanupIntervalMs: number;\n\n /** Whether to persist references across restarts */\n enablePersistence: boolean;\n\n /** Storage backend configuration */\n storageBackend: 'memory' | 'filesystem' | 'hybrid';\n\n /** Cleanup policies for different content types */\n cleanupPolicies: {\n /** Policy for content marked as \"recent\" from MCP tools */\n recent: { maxAgeMs: number; priority: number };\n\n /** Policy for user-uploaded content */\n userContent: { maxAgeMs: number; priority: number };\n\n /** Policy for agent-generated content */\n agentGenerated: { maxAgeMs: number; priority: number };\n\n /** Default policy for other content */\n default: { maxAgeMs: number; priority: number };\n };\n}\n\n/**\n * Default configuration values\n */\nexport const DEFAULT_CONTENT_REFERENCE_CONFIG: ContentReferenceConfig = {\n sizeThresholdBytes: 10 * 1024,\n maxAgeMs: 60 * 60 * 1000,\n maxReferences: 100,\n maxTotalStorageBytes: 100 * 1024 * 1024,\n enableAutoCleanup: true,\n cleanupIntervalMs: 5 * 60 * 1000,\n enablePersistence: false,\n storageBackend: 'memory',\n cleanupPolicies: {\n recent: { maxAgeMs: 30 * 60 * 1000, priority: 1 },\n userContent: { maxAgeMs: 2 * 60 * 60 * 1000, priority: 2 },\n agentGenerated: { maxAgeMs: 60 * 60 * 1000, priority: 3 },\n default: { maxAgeMs: 60 * 60 * 1000, priority: 4 },\n },\n};\n\n/**\n * Statistics about content reference usage and storage\n */\nexport interface ContentReferenceStats {\n /** Total number of active references */\n activeReferences: number;\n\n /** Total storage used by all references in bytes */\n totalStorageBytes: number;\n\n /** Number of references cleaned up in last cleanup cycle */\n recentlyCleanedUp: number;\n\n /** Number of successful reference resolutions since startup */\n totalResolutions: number;\n\n /** Number of failed resolution attempts */\n failedResolutions: number;\n\n /** Average content size in bytes */\n averageContentSize: number;\n\n /** Most frequently accessed reference ID */\n mostAccessedReferenceId?: ReferenceId;\n\n /** Storage utilization percentage */\n storageUtilization: number;\n\n /** Performance metrics */\n performanceMetrics: {\n /** Average time to create a reference in milliseconds */\n averageCreationTimeMs: number;\n\n /** Average time to resolve a reference in milliseconds */\n averageResolutionTimeMs: number;\n\n /** Average cleanup time in milliseconds */\n averageCleanupTimeMs: number;\n };\n}\n\n/**\n * Error types for content reference operations\n */\nexport class ContentReferenceError extends Error {\n constructor(\n message: string,\n public readonly type: ReferenceResolutionResult['errorType'],\n public readonly referenceId?: ReferenceId,\n public readonly suggestedActions?: string[]\n ) {\n super(message);\n this.name = 'ContentReferenceError';\n }\n}\n\n/**\n * Interface for content reference storage implementations\n */\nexport interface ContentReferenceStore {\n /**\n * Store content and return a reference\n */\n storeContent(\n content: Buffer,\n metadata: Omit<\n ContentMetadata,\n 'createdAt' | 'lastAccessedAt' | 'accessCount'\n >\n ): Promise<ContentReference>;\n\n /**\n * Resolve a reference to its content\n */\n resolveReference(\n referenceId: ReferenceId\n ): Promise<ReferenceResolutionResult>;\n\n /**\n * Check if a reference exists and is valid\n */\n hasReference(referenceId: ReferenceId): Promise<boolean>;\n\n /**\n * Mark a reference for cleanup\n */\n cleanupReference(referenceId: ReferenceId): Promise<boolean>;\n\n /**\n * Get current storage statistics\n */\n getStats(): Promise<ContentReferenceStats>;\n\n /**\n * Update configuration\n */\n updateConfig(config: Partial<ContentReferenceConfig>): Promise<void>;\n\n /**\n * Perform cleanup based on current policies\n */\n performCleanup(): Promise<{ cleanedUp: number; errors: string[] }>;\n\n /**\n * Dispose of resources\n */\n dispose(): Promise<void>;\n}\n"],"names":[],"mappings":"AAuLO,MAAM,mCAA2D;AAAA,EACtE,oBAAoB,KAAK;AAAA,EACzB,UAAU,KAAK,KAAK;AAAA,EACpB,eAAe;AAAA,EACf,sBAAsB,MAAM,OAAO;AAAA,EACnC,mBAAmB;AAAA,EACnB,mBAAmB,IAAI,KAAK;AAAA,EAC5B,mBAAmB;AAAA,EACnB,gBAAgB;AAAA,EAChB,iBAAiB;AAAA,IACf,QAAQ,EAAE,UAAU,KAAK,KAAK,KAAM,UAAU,EAAA;AAAA,IAC9C,aAAa,EAAE,UAAU,IAAI,KAAK,KAAK,KAAM,UAAU,EAAA;AAAA,IACvD,gBAAgB,EAAE,UAAU,KAAK,KAAK,KAAM,UAAU,EAAA;AAAA,IACtD,SAAS,EAAE,UAAU,KAAK,KAAK,KAAM,UAAU,EAAA;AAAA,EAAE;AAErD;AA8CO,MAAM,8BAA8B,MAAM;AAAA,EAC/C,YACE,SACgB,MACA,aACA,kBAChB;AACA,UAAM,OAAO;AAJG,SAAA,OAAA;AACA,SAAA,cAAA;AACA,SAAA,mBAAA;AAGhB,SAAK,OAAO;AAAA,EACd;AACF;"}
@@ -0,0 +1,95 @@
1
+ import { TransferTransaction, AccountId, Hbar } from "@hashgraph/sdk";
2
+ import BigNumber from "bignumber.js";
3
+ import { BaseServiceBuilder } from "hedera-agent-kit";
4
+ class AccountBuilder extends BaseServiceBuilder {
5
+ constructor(hederaKit) {
6
+ super(hederaKit);
7
+ }
8
+ /**
9
+ * Transfers HBAR between accounts with proper decimal handling
10
+ */
11
+ transferHbar(params, isUserInitiated = true) {
12
+ this.clearNotes();
13
+ const transaction = new TransferTransaction();
14
+ if (!params.transfers || params.transfers.length === 0) {
15
+ throw new Error("HbarTransferParams must include at least one transfer.");
16
+ }
17
+ let netZeroInTinybars = new BigNumber(0);
18
+ let userTransferProcessedForScheduling = false;
19
+ if (isUserInitiated && this.kit.userAccountId && this.kit.operationalMode === "provideBytes" && params.transfers.length === 1) {
20
+ const receiverTransfer = params.transfers[0];
21
+ const amountValue = typeof receiverTransfer.amount === "string" || typeof receiverTransfer.amount === "number" ? receiverTransfer.amount : receiverTransfer.amount.toString();
22
+ const amountBigNum = new BigNumber(amountValue);
23
+ if (amountBigNum.isPositive()) {
24
+ const recipientAccountId = typeof receiverTransfer.accountId === "string" ? AccountId.fromString(receiverTransfer.accountId) : receiverTransfer.accountId;
25
+ const roundedAmount = amountBigNum.toFixed(8, BigNumber.ROUND_DOWN);
26
+ const sdkHbarAmount = Hbar.fromString(roundedAmount);
27
+ this.logger.info(
28
+ `[AccountBuilder.transferHbar] Configuring user-initiated scheduled transfer: ${sdkHbarAmount.toString()} from ${this.kit.userAccountId} to ${recipientAccountId.toString()}`
29
+ );
30
+ this.addNote(
31
+ `Configured HBAR transfer from your account (${this.kit.userAccountId}) to ${recipientAccountId.toString()} for ${sdkHbarAmount.toString()}.`
32
+ );
33
+ transaction.addHbarTransfer(recipientAccountId, sdkHbarAmount);
34
+ transaction.addHbarTransfer(
35
+ AccountId.fromString(this.kit.userAccountId),
36
+ sdkHbarAmount.negated()
37
+ );
38
+ userTransferProcessedForScheduling = true;
39
+ }
40
+ }
41
+ if (!userTransferProcessedForScheduling) {
42
+ const processedTransfers = [];
43
+ for (const transferInput of params.transfers) {
44
+ const accountId = typeof transferInput.accountId === "string" ? AccountId.fromString(transferInput.accountId) : transferInput.accountId;
45
+ const amountValue = typeof transferInput.amount === "string" || typeof transferInput.amount === "number" ? transferInput.amount : transferInput.amount.toString();
46
+ const amountBigNum = new BigNumber(amountValue);
47
+ const roundedAmount = amountBigNum.toFixed(8, BigNumber.ROUND_DOWN);
48
+ this.logger.info(
49
+ `Processing transfer: ${amountValue} HBAR (rounded to ${roundedAmount}) for account ${accountId.toString()}`
50
+ );
51
+ const sdkHbarAmount = Hbar.fromString(roundedAmount);
52
+ processedTransfers.push({
53
+ accountId,
54
+ amount: amountBigNum,
55
+ hbar: sdkHbarAmount
56
+ });
57
+ const tinybarsContribution = sdkHbarAmount.toTinybars();
58
+ netZeroInTinybars = netZeroInTinybars.plus(
59
+ tinybarsContribution.toString()
60
+ );
61
+ }
62
+ if (!netZeroInTinybars.isZero()) {
63
+ this.logger.warn(
64
+ `Transfer sum not zero: ${netZeroInTinybars.toString()} tinybars off. Adjusting last transfer.`
65
+ );
66
+ if (processedTransfers.length > 0) {
67
+ const lastTransfer = processedTransfers[processedTransfers.length - 1];
68
+ const adjustment = netZeroInTinybars.dividedBy(-1e8);
69
+ const adjustedAmount = lastTransfer.amount.plus(adjustment);
70
+ const adjustedRounded = adjustedAmount.toFixed(8, BigNumber.ROUND_DOWN);
71
+ lastTransfer.hbar = Hbar.fromString(adjustedRounded);
72
+ this.logger.info(
73
+ `Adjusted last transfer for ${lastTransfer.accountId.toString()} to ${adjustedRounded} HBAR`
74
+ );
75
+ }
76
+ }
77
+ for (const transfer of processedTransfers) {
78
+ transaction.addHbarTransfer(transfer.accountId, transfer.hbar);
79
+ }
80
+ }
81
+ if (typeof params.memo !== "undefined") {
82
+ if (params.memo === null) {
83
+ this.logger.warn("Received null for memo in transferHbar.");
84
+ } else {
85
+ transaction.setTransactionMemo(params.memo);
86
+ }
87
+ }
88
+ this.setCurrentTransaction(transaction);
89
+ return this;
90
+ }
91
+ }
92
+ export {
93
+ AccountBuilder
94
+ };
95
+ //# sourceMappingURL=index47.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index47.js","sources":["../../src/plugins/hbar/AccountBuilder.ts"],"sourcesContent":["import {\n AccountId,\n Hbar,\n TransferTransaction,\n} from '@hashgraph/sdk';\nimport BigNumber from 'bignumber.js';\nimport { HederaAgentKit, BaseServiceBuilder } from 'hedera-agent-kit';\nimport { HbarTransferParams } from './types';\n\n/**\n * Custom AccountBuilder that properly handles HBAR decimal conversion\n */\nexport class AccountBuilder extends BaseServiceBuilder {\n constructor(hederaKit: HederaAgentKit) {\n super(hederaKit);\n }\n\n /**\n * Transfers HBAR between accounts with proper decimal handling\n */\n public transferHbar(\n params: HbarTransferParams,\n isUserInitiated: boolean = true\n ): this {\n this.clearNotes();\n const transaction = new TransferTransaction();\n \n if (!params.transfers || params.transfers.length === 0) {\n throw new Error('HbarTransferParams must include at least one transfer.');\n }\n\n let netZeroInTinybars = new BigNumber(0);\n let userTransferProcessedForScheduling = false;\n\n if (\n isUserInitiated &&\n this.kit.userAccountId &&\n (this.kit.operationalMode as string) === 'provideBytes' &&\n params.transfers.length === 1\n ) {\n const receiverTransfer = params.transfers[0];\n const amountValue =\n typeof receiverTransfer.amount === 'string' ||\n typeof receiverTransfer.amount === 'number'\n ? receiverTransfer.amount\n : receiverTransfer.amount.toString();\n\n const amountBigNum = new BigNumber(amountValue);\n\n if (amountBigNum.isPositive()) {\n const recipientAccountId =\n typeof receiverTransfer.accountId === 'string'\n ? AccountId.fromString(receiverTransfer.accountId)\n : receiverTransfer.accountId;\n\n const roundedAmount = amountBigNum.toFixed(8, BigNumber.ROUND_DOWN);\n const sdkHbarAmount = Hbar.fromString(roundedAmount);\n\n this.logger.info(\n `[AccountBuilder.transferHbar] Configuring user-initiated scheduled transfer: ${sdkHbarAmount.toString()} from ${\n this.kit.userAccountId\n } to ${recipientAccountId.toString()}`\n );\n \n this.addNote(\n `Configured HBAR transfer from your account (${\n this.kit.userAccountId\n }) to ${recipientAccountId.toString()} for ${sdkHbarAmount.toString()}.`\n );\n\n transaction.addHbarTransfer(recipientAccountId, sdkHbarAmount);\n transaction.addHbarTransfer(\n AccountId.fromString(this.kit.userAccountId),\n sdkHbarAmount.negated()\n );\n\n userTransferProcessedForScheduling = true;\n }\n }\n\n if (!userTransferProcessedForScheduling) {\n const processedTransfers: Array<{\n accountId: AccountId;\n amount: BigNumber;\n hbar: Hbar;\n }> = [];\n \n for (const transferInput of params.transfers) {\n const accountId =\n typeof transferInput.accountId === 'string'\n ? AccountId.fromString(transferInput.accountId)\n : transferInput.accountId;\n\n const amountValue =\n typeof transferInput.amount === 'string' ||\n typeof transferInput.amount === 'number'\n ? transferInput.amount\n : transferInput.amount.toString();\n\n const amountBigNum = new BigNumber(amountValue);\n const roundedAmount = amountBigNum.toFixed(8, BigNumber.ROUND_DOWN);\n \n this.logger.info(\n `Processing transfer: ${amountValue} HBAR (rounded to ${roundedAmount}) for account ${accountId.toString()}`\n );\n\n const sdkHbarAmount = Hbar.fromString(roundedAmount);\n processedTransfers.push({\n accountId,\n amount: amountBigNum,\n hbar: sdkHbarAmount\n });\n\n const tinybarsContribution = sdkHbarAmount.toTinybars();\n netZeroInTinybars = netZeroInTinybars.plus(\n tinybarsContribution.toString()\n );\n }\n\n if (!netZeroInTinybars.isZero()) {\n this.logger.warn(\n `Transfer sum not zero: ${netZeroInTinybars.toString()} tinybars off. Adjusting last transfer.`\n );\n \n if (processedTransfers.length > 0) {\n const lastTransfer = processedTransfers[processedTransfers.length - 1];\n const adjustment = netZeroInTinybars.dividedBy(-100000000);\n const adjustedAmount = lastTransfer.amount.plus(adjustment);\n const adjustedRounded = adjustedAmount.toFixed(8, BigNumber.ROUND_DOWN);\n lastTransfer.hbar = Hbar.fromString(adjustedRounded);\n \n this.logger.info(\n `Adjusted last transfer for ${lastTransfer.accountId.toString()} to ${adjustedRounded} HBAR`\n );\n }\n }\n \n for (const transfer of processedTransfers) {\n transaction.addHbarTransfer(transfer.accountId, transfer.hbar);\n }\n }\n\n if (typeof params.memo !== 'undefined') {\n if (params.memo === null) {\n this.logger.warn('Received null for memo in transferHbar.');\n } else {\n transaction.setTransactionMemo(params.memo);\n }\n }\n\n this.setCurrentTransaction(transaction);\n return this;\n }\n}"],"names":[],"mappings":";;;AAYO,MAAM,uBAAuB,mBAAmB;AAAA,EACrD,YAAY,WAA2B;AACrC,UAAM,SAAS;AAAA,EACjB;AAAA;AAAA;AAAA;AAAA,EAKO,aACL,QACA,kBAA2B,MACrB;AACN,SAAK,WAAA;AACL,UAAM,cAAc,IAAI,oBAAA;AAExB,QAAI,CAAC,OAAO,aAAa,OAAO,UAAU,WAAW,GAAG;AACtD,YAAM,IAAI,MAAM,wDAAwD;AAAA,IAC1E;AAEA,QAAI,oBAAoB,IAAI,UAAU,CAAC;AACvC,QAAI,qCAAqC;AAEzC,QACE,mBACA,KAAK,IAAI,iBACR,KAAK,IAAI,oBAA+B,kBACzC,OAAO,UAAU,WAAW,GAC5B;AACA,YAAM,mBAAmB,OAAO,UAAU,CAAC;AAC3C,YAAM,cACJ,OAAO,iBAAiB,WAAW,YACnC,OAAO,iBAAiB,WAAW,WAC/B,iBAAiB,SACjB,iBAAiB,OAAO,SAAA;AAE9B,YAAM,eAAe,IAAI,UAAU,WAAW;AAE9C,UAAI,aAAa,cAAc;AAC7B,cAAM,qBACJ,OAAO,iBAAiB,cAAc,WAClC,UAAU,WAAW,iBAAiB,SAAS,IAC/C,iBAAiB;AAEvB,cAAM,gBAAgB,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U;AAAA,QAAA;AAGxD,YAAI,mBAAmB,SAAS,GAAG;AACjC,gBAAM,eAAe,mBAAmB,mBAAmB,SAAS,CAAC;AACrE,gBAAM,aAAa,kBAAkB,UAAU,IAAU;AACzD,gBAAM,iBAAiB,aAAa,OAAO,KAAK,UAAU;AAC1D,gBAAM,kBAAkB,eAAe,QAAQ,GAAG,UAAU,UAAU;AACtE,uBAAa,OAAO,KAAK,WAAW,eAAe;AAEnD,eAAK,OAAO;AAAA,YACV,8BAA8B,aAAa,UAAU,SAAA,CAAU,OAAO,eAAe;AAAA,UAAA;AAAA,QAEzF;AAAA,MACF;AAEA,iBAAW,YAAY,oBAAoB;AACzC,oBAAY,gBAAgB,SAAS,WAAW,SAAS,IAAI;AAAA,MAC/D;AAAA,IACF;AAEA,QAAI,OAAO,OAAO,SAAS,aAAa;AACtC,UAAI,OAAO,SAAS,MAAM;AACxB,aAAK,OAAO,KAAK,yCAAyC;AAAA,MAC5D,OAAO;AACL,oBAAY,mBAAmB,OAAO,IAAI;AAAA,MAC5C;AAAA,IACF;AAEA,SAAK,sBAAsB,WAAW;AACtC,WAAO;AAAA,EACT;AACF;"}
@@ -1,6 +1,6 @@
1
1
  import { BasePlugin, HederaAirdropTokenTool } from "hedera-agent-kit";
2
- import { TransferHbarTool } from "./index36.js";
3
- import { AirdropToolWrapper } from "./index37.js";
2
+ import { TransferHbarTool } from "./index37.js";
3
+ import { AirdropToolWrapper } from "./index38.js";
4
4
  class HbarPlugin extends BasePlugin {
5
5
  constructor() {
6
6
  super(...arguments);
@@ -1,17 +1,18 @@
1
1
  import { ServerSigner, getAllHederaCorePlugins } from "hedera-agent-kit";
2
2
  import { Logger } from "@hashgraphonline/standards-sdk";
3
3
  import { createAgent } from "./index8.js";
4
+ import { BrowserSigner } from "./index39.js";
4
5
  import { LangChainProvider } from "./index9.js";
5
6
  import { ChatOpenAI } from "@langchain/openai";
6
- import OpenAI from "openai";
7
7
  import { ChatAnthropic } from "@langchain/anthropic";
8
8
  import { SystemMessage, HumanMessage, AIMessage } from "@langchain/core/messages";
9
9
  import { HCS10Plugin } from "./index2.js";
10
10
  import { HCS2Plugin } from "./index3.js";
11
11
  import { InscribePlugin } from "./index4.js";
12
+ import { getWalletBridgeProvider } from "./index36.js";
13
+ import { OpenConvaiState, InscriberBuilder } from "@hashgraphonline/standards-agent-kit";
12
14
  import { HbarPlugin } from "./index5.js";
13
- import { OpenConvaiState } from "@hashgraphonline/standards-agent-kit";
14
- import { getSystemMessage } from "./index38.js";
15
+ import { getSystemMessage } from "./index40.js";
15
16
  import { ContentStoreManager } from "./index24.js";
16
17
  import { SmartMemoryManager } from "./index18.js";
17
18
  import "./index19.js";
@@ -19,7 +20,14 @@ import "./index20.js";
19
20
  import "./index21.js";
20
21
  import "crypto";
21
22
  import { createEntityTools } from "./index34.js";
23
+ import { ParameterService } from "./index29.js";
24
+ import { FormatConverterRegistry } from "./index25.js";
25
+ import { TopicIdToHrlConverter } from "./index27.js";
26
+ import { StringNormalizationConverter } from "./index28.js";
22
27
  const DEFAULT_MODEL_NAME = "gpt-4o";
28
+ const DEFAULT_OPENAI_MODEL = "gpt-4o-mini";
29
+ const DEFAULT_OPENROUTER_MODEL = "openai/gpt-4o-mini";
30
+ const DEFAULT_CLAUDE_MODEL = "claude-3-7-sonnet-latest";
23
31
  const DEFAULT_TEMPERATURE = 0.1;
24
32
  const DEFAULT_NETWORK = "testnet";
25
33
  const DEFAULT_OPERATIONAL_MODE = "autonomous";
@@ -46,7 +54,16 @@ const _ConversationalAgent = class _ConversationalAgent {
46
54
  );
47
55
  this.logger.info("Entity memory initialized");
48
56
  const provider = options.entityMemoryProvider || options.llmProvider || "openai";
49
- const modelName = options.entityMemoryModelName || (provider === "anthropic" ? "claude-3-7-sonnet-latest" : provider === "openrouter" ? "openai/gpt-4o-mini" : "gpt-4o-mini");
57
+ let modelName = options.entityMemoryModelName;
58
+ if (!modelName) {
59
+ if (provider === "anthropic") {
60
+ modelName = DEFAULT_CLAUDE_MODEL;
61
+ } else if (provider === "openrouter") {
62
+ modelName = DEFAULT_OPENROUTER_MODEL;
63
+ } else {
64
+ modelName = DEFAULT_OPENAI_MODEL;
65
+ }
66
+ }
50
67
  let resolverLLM;
51
68
  if (provider === "anthropic") {
52
69
  resolverLLM = new ChatAnthropic({
@@ -57,19 +74,17 @@ const _ConversationalAgent = class _ConversationalAgent {
57
74
  } else if (provider === "openrouter") {
58
75
  const baseURL = options.openRouterBaseURL || "https://openrouter.ai/api/v1";
59
76
  const apiKey = options.openRouterApiKey || options.openAIApiKey;
60
- const client = new OpenAI({
61
- apiKey,
62
- baseURL,
63
- defaultHeaders: {
64
- Referer: process.env.OPENROUTER_REFERRER || "https://hashgraphonline.com",
65
- "HTTP-Referer": process.env.OPENROUTER_REFERRER || "https://hashgraphonline.com",
66
- "X-Title": process.env.OPENROUTER_TITLE || "Hashgraph Online Conversational Agent"
67
- }
68
- });
69
77
  resolverLLM = new ChatOpenAI({
70
- client,
78
+ apiKey,
71
79
  model: modelName,
72
- temperature: 0
80
+ temperature: 0,
81
+ configuration: {
82
+ baseURL,
83
+ defaultHeaders: {
84
+ "HTTP-Referer": process.env.OPENROUTER_REFERRER || "https://hashgraphonline.com",
85
+ "X-Title": process.env.OPENROUTER_TITLE || "Hashgraph Online Conversational Agent"
86
+ }
87
+ }
73
88
  });
74
89
  } else {
75
90
  resolverLLM = new ChatOpenAI({
@@ -98,41 +113,108 @@ const _ConversationalAgent = class _ConversationalAgent {
98
113
  } = this.options;
99
114
  this.validateOptions(accountId, privateKey);
100
115
  try {
101
- const serverSigner = new ServerSigner(
102
- accountId,
103
- privateKey,
104
- network
105
- );
116
+ const opMode = this.options.operationalMode || DEFAULT_OPERATIONAL_MODE;
117
+ const bytesMode = opMode !== "autonomous";
118
+ let signer;
119
+ try {
120
+ const IB = InscriberBuilder;
121
+ if (typeof IB.setPreferWalletOnly === "function") {
122
+ IB.setPreferWalletOnly(bytesMode);
123
+ }
124
+ } catch (e) {
125
+ this.logger.warn("Failed to set wallet-only preference", e);
126
+ }
127
+ if (!bytesMode) {
128
+ signer = new ServerSigner(accountId, privateKey, network);
129
+ } else {
130
+ const chain = String(network || "testnet") === "mainnet" ? "mainnet" : "testnet";
131
+ const effectiveAccount = this.options.userAccountId || accountId;
132
+ signer = new BrowserSigner(effectiveAccount, chain, this.options.walletExecutor);
133
+ }
134
+ this.logger.info("Signer configured", {
135
+ operationalMode: opMode,
136
+ bytesMode,
137
+ signerClass: Object.getPrototypeOf(signer)?.constructor?.name || "unknown"
138
+ });
139
+ try {
140
+ const bridge = getWalletBridgeProvider();
141
+ if (bridge) {
142
+ const IB = InscriberBuilder;
143
+ if (typeof IB.setWalletInfoResolver === "function") {
144
+ IB.setWalletInfoResolver(async () => {
145
+ const status = await bridge.status();
146
+ if (status.connected && status.accountId && status.network) {
147
+ return { accountId: status.accountId, network: status.network };
148
+ }
149
+ return null;
150
+ });
151
+ }
152
+ if (typeof IB.setWalletExecutor === "function") {
153
+ IB.setWalletExecutor(async (base64, network2) => {
154
+ return await bridge.executeBytes(base64, network2);
155
+ });
156
+ }
157
+ if (typeof IB.setStartInscriptionDelegate === "function" && bridge.startInscription) {
158
+ IB.setStartInscriptionDelegate(async (request, network2) => {
159
+ return await bridge.startInscription(request, network2);
160
+ });
161
+ }
162
+ try {
163
+ const sak = await import("@hashgraphonline/standards-agent-kit");
164
+ const reg = sak?.SignerProviderRegistry;
165
+ if (reg) {
166
+ reg.setWalletInfoResolver(async () => {
167
+ const status = await bridge.status();
168
+ if (status.connected && status.accountId && status.network) {
169
+ return { accountId: status.accountId, network: status.network };
170
+ }
171
+ return null;
172
+ });
173
+ reg.setWalletExecutor(async (base64, network2) => {
174
+ return await bridge.executeBytes(base64, network2);
175
+ });
176
+ if (typeof bridge.startHCS === "function") {
177
+ reg.setStartHCSDelegate(async (op, request, network2) => {
178
+ return await bridge.startHCS(op, request, network2);
179
+ });
180
+ }
181
+ reg.setPreferWalletOnly(!!bytesMode);
182
+ }
183
+ } catch (sakWireErr) {
184
+ this.logger.warn("Failed to wire SAK SignerProviderRegistry wallet delegates", sakWireErr);
185
+ }
186
+ }
187
+ } catch (e) {
188
+ this.logger.warn("Failed to register wallet bridge providers", e);
189
+ }
106
190
  let llm;
107
191
  let providerInfo = { provider: llmProvider };
108
192
  if (llmProvider === "anthropic") {
109
193
  llm = new ChatAnthropic({
110
194
  apiKey: openAIApiKey,
111
- model: openAIModelName || "claude-3-7-sonnet-latest",
195
+ model: openAIModelName || DEFAULT_CLAUDE_MODEL,
112
196
  temperature: DEFAULT_TEMPERATURE
113
197
  });
114
198
  providerInfo = {
115
199
  ...providerInfo,
116
- model: openAIModelName || "claude-3-7-sonnet-latest",
200
+ model: openAIModelName || DEFAULT_CLAUDE_MODEL,
117
201
  keyPresent: !!openAIApiKey
118
202
  };
119
203
  } else if (llmProvider === "openrouter") {
120
204
  const baseURL = this.options.openRouterBaseURL || "https://openrouter.ai/api/v1";
121
205
  const apiKey = this.options.openRouterApiKey || openAIApiKey;
122
206
  const modelName = openAIModelName || "anthropic/claude-3-haiku-20240307";
123
- const client = new OpenAI({
124
- apiKey,
125
- baseURL,
126
- defaultHeaders: {
127
- Referer: process.env.OPENROUTER_REFERRER || "https://hashgraphonline.com",
128
- "HTTP-Referer": process.env.OPENROUTER_REFERRER || "https://hashgraphonline.com",
129
- "X-Title": process.env.OPENROUTER_TITLE || "Hashgraph Online Conversational Agent"
130
- }
131
- });
132
207
  llm = new ChatOpenAI({
133
- client,
208
+ apiKey,
134
209
  model: modelName,
135
- temperature: DEFAULT_TEMPERATURE
210
+ temperature: DEFAULT_TEMPERATURE,
211
+ configuration: {
212
+ baseURL,
213
+ defaultHeaders: {
214
+ "HTTP-Referer": process.env.OPENROUTER_REFERRER || "https://hashgraphonline.com",
215
+ "X-Title": process.env.OPENROUTER_TITLE || "Hashgraph Online Conversational Agent"
216
+ }
217
+ }
136
218
  });
137
219
  providerInfo = {
138
220
  ...providerInfo,
@@ -141,16 +223,16 @@ const _ConversationalAgent = class _ConversationalAgent {
141
223
  keyPresent: !!apiKey
142
224
  };
143
225
  } else {
144
- const modelName = openAIModelName || "gpt-4o-mini";
145
- const isGPT5Model = modelName.toLowerCase().includes("gpt-5") || modelName.toLowerCase().includes("gpt5");
226
+ const modelName2 = openAIModelName || DEFAULT_OPENAI_MODEL;
227
+ const isGPT5Model = modelName2.toLowerCase().includes("gpt-5") || modelName2.toLowerCase().includes("gpt5");
146
228
  llm = new ChatOpenAI({
147
229
  apiKey: openAIApiKey,
148
- model: modelName,
230
+ model: modelName2,
149
231
  ...isGPT5Model ? { temperature: 1 } : { temperature: DEFAULT_TEMPERATURE }
150
232
  });
151
233
  providerInfo = {
152
234
  ...providerInfo,
153
- model: modelName,
235
+ model: modelName2,
154
236
  keyPresent: !!openAIApiKey
155
237
  };
156
238
  }
@@ -158,7 +240,7 @@ const _ConversationalAgent = class _ConversationalAgent {
158
240
  this.logger.info("Preparing plugins...");
159
241
  const allPlugins = this.preparePlugins();
160
242
  this.logger.info("Creating agent config...");
161
- const agentConfig = this.createAgentConfig(serverSigner, llm, allPlugins);
243
+ const agentConfig = this.createAgentConfig(signer, llm, allPlugins);
162
244
  this.logger.info("Creating agent...");
163
245
  this.agent = createAgent(agentConfig);
164
246
  this.logger.info("Agent created");
@@ -176,6 +258,26 @@ const _ConversationalAgent = class _ConversationalAgent {
176
258
  this.logger.info("agent.boot() completed");
177
259
  this.logger.info("🔥 agent.boot() completed");
178
260
  if (this.agent) {
261
+ try {
262
+ const registry = new FormatConverterRegistry();
263
+ registry.register(new TopicIdToHrlConverter());
264
+ registry.register(new StringNormalizationConverter());
265
+ const paramService = new ParameterService(
266
+ registry,
267
+ this.options.network || "testnet"
268
+ );
269
+ paramService.attachToAgent(this.agent, {
270
+ getEntities: async () => this.memoryManager?.getEntityAssociations() || []
271
+ });
272
+ this.logger.info(
273
+ "Parameter preprocessing callback attached (internal)"
274
+ );
275
+ } catch (e) {
276
+ this.logger.warn(
277
+ "Failed to attach internal parameter preprocessing callback",
278
+ e
279
+ );
280
+ }
179
281
  const cfg = agentConfig;
180
282
  cfg.filtering = cfg.filtering || {};
181
283
  const originalPredicate = cfg.filtering.toolPredicate;
@@ -302,22 +404,27 @@ const _ConversationalAgent = class _ConversationalAgent {
302
404
  * @throws {Error} If required fields are missing
303
405
  */
304
406
  validateOptions(accountId, privateKey) {
305
- if (!accountId || !privateKey) {
306
- throw new Error("Account ID and private key are required");
407
+ const opMode = this.options.operationalMode || DEFAULT_OPERATIONAL_MODE;
408
+ const bytesMode = opMode !== "autonomous";
409
+ if (!accountId) {
410
+ throw new Error("Account ID is required");
411
+ }
412
+ if (!privateKey && !bytesMode) {
413
+ throw new Error("Private key is required in autonomous mode");
307
414
  }
308
415
  if (typeof accountId !== "string") {
309
416
  throw new Error(
310
417
  `Account ID must be a string, received ${typeof accountId}`
311
418
  );
312
419
  }
313
- if (typeof privateKey !== "string") {
420
+ if (!bytesMode && typeof privateKey !== "string") {
314
421
  throw new Error(
315
422
  `Private key must be a string, received ${typeof privateKey}: ${JSON.stringify(
316
423
  privateKey
317
424
  )}`
318
425
  );
319
426
  }
320
- if (privateKey.length < 10) {
427
+ if (!bytesMode && typeof privateKey === "string" && privateKey.length < 10) {
321
428
  throw new Error("Private key appears to be invalid (too short)");
322
429
  }
323
430
  }
@@ -347,12 +454,12 @@ const _ConversationalAgent = class _ConversationalAgent {
347
454
  /**
348
455
  * Creates the agent configuration object.
349
456
  *
350
- * @param serverSigner - The server signer instance
457
+ * @param signer - The signer instance
351
458
  * @param llm - The language model instance
352
459
  * @param allPlugins - Array of plugins to use
353
460
  * @returns Configuration object for creating the agent
354
461
  */
355
- createAgentConfig(serverSigner, llm, allPlugins) {
462
+ createAgentConfig(signer, llm, allPlugins) {
356
463
  const {
357
464
  operationalMode = DEFAULT_OPERATIONAL_MODE,
358
465
  userAccountId,
@@ -366,7 +473,7 @@ const _ConversationalAgent = class _ConversationalAgent {
366
473
  } = this.options;
367
474
  return {
368
475
  framework: "langchain",
369
- signer: serverSigner,
476
+ signer,
370
477
  execution: {
371
478
  mode: operationalMode === "autonomous" ? "direct" : "bytes",
372
479
  operationalMode,
@@ -579,7 +686,7 @@ const _ConversationalAgent = class _ConversationalAgent {
579
686
  }
580
687
  if (typeof response === "string") {
581
688
  const match = response.match(
582
- /transaction[\s\w]*ID[\s:"]*([0-9a-fA-F@\.\-]+)/i
689
+ /transaction[\s\w]*ID[\s:"]*([0-9a-fA-F@._-]+)/i
583
690
  );
584
691
  return match ? match[1] : void 0;
585
692
  }