@hashgraphonline/conversational-agent 0.1.219 → 0.1.220
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/base-agent.d.ts +2 -0
- package/dist/cjs/index.cjs +1 -1
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/langchain/form-aware-agent-executor.d.ts +6 -3
- package/dist/esm/index10.js +2 -2
- package/dist/esm/index21.js +1 -1
- package/dist/esm/index23.js +1 -1
- package/dist/esm/index25.js +0 -4
- package/dist/esm/index25.js.map +1 -1
- package/dist/esm/index29.js +0 -6
- package/dist/esm/index29.js.map +1 -1
- package/dist/esm/index31.js +4 -71
- package/dist/esm/index31.js.map +1 -1
- package/dist/esm/index37.js +11 -4
- package/dist/esm/index37.js.map +1 -1
- package/dist/esm/index38.js +6 -11
- package/dist/esm/index38.js.map +1 -1
- package/dist/esm/index39.js +5 -255
- package/dist/esm/index39.js.map +1 -1
- package/dist/esm/index40.js +213 -142
- package/dist/esm/index40.js.map +1 -1
- package/dist/esm/index41.js +181 -24
- package/dist/esm/index41.js.map +1 -1
- package/dist/esm/index42.js +26 -6
- package/dist/esm/index42.js.map +1 -1
- package/dist/esm/index6.js +1 -5
- package/dist/esm/index6.js.map +1 -1
- package/dist/esm/index7.js.map +1 -1
- package/dist/types/base-agent.d.ts +2 -0
- package/dist/types/langchain/form-aware-agent-executor.d.ts +6 -3
- package/package.json +2 -2
- package/src/base-agent.ts +4 -0
- package/src/conversational-agent.ts +3 -14
- package/src/langchain/form-aware-agent-executor.ts +64 -81
- package/src/langchain/langchain-agent.ts +24 -104
- package/src/services/formatters/format-converter-registry.ts +0 -5
package/dist/esm/index41.js
CHANGED
|
@@ -1,30 +1,187 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
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 }
|
|
1
|
+
import { ZodError } from "zod";
|
|
2
|
+
import { Logger } from "@hashgraphonline/standards-sdk";
|
|
3
|
+
class ExecutionPipeline {
|
|
4
|
+
constructor(toolRegistry, formEngine, memory, logger) {
|
|
5
|
+
this.toolRegistry = toolRegistry;
|
|
6
|
+
this.formEngine = formEngine;
|
|
7
|
+
this.memory = memory;
|
|
8
|
+
this.logger = logger || new Logger({ module: "ExecutionPipeline" });
|
|
15
9
|
}
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
10
|
+
/**
|
|
11
|
+
* Execute a tool through the pipeline
|
|
12
|
+
*/
|
|
13
|
+
async execute(toolName, input, sessionContext) {
|
|
14
|
+
const traceId = `trace-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
|
|
15
|
+
const startTime = Date.now();
|
|
16
|
+
const toolEntry = this.toolRegistry.getTool(toolName);
|
|
17
|
+
if (!toolEntry) {
|
|
18
|
+
throw new Error(`Tool not found in registry: ${toolName}`);
|
|
19
|
+
}
|
|
20
|
+
const context = {
|
|
21
|
+
toolName,
|
|
22
|
+
input,
|
|
23
|
+
session: sessionContext || this.buildDefaultSession(),
|
|
24
|
+
memory: this.memory,
|
|
25
|
+
traceId,
|
|
26
|
+
toolEntry
|
|
27
|
+
};
|
|
28
|
+
try {
|
|
29
|
+
const shouldGenerateForm = await this.checkFormGeneration(context);
|
|
30
|
+
if (shouldGenerateForm.requiresForm && shouldGenerateForm.formMessage) {
|
|
31
|
+
return {
|
|
32
|
+
success: false,
|
|
33
|
+
output: "Form generation required",
|
|
34
|
+
requiresForm: true,
|
|
35
|
+
formMessage: shouldGenerateForm.formMessage,
|
|
36
|
+
traceId,
|
|
37
|
+
executionTime: Date.now() - startTime
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
const result = await this.executeToolDirect(context);
|
|
41
|
+
return {
|
|
42
|
+
success: true,
|
|
43
|
+
output: result,
|
|
44
|
+
traceId,
|
|
45
|
+
executionTime: Date.now() - startTime
|
|
46
|
+
};
|
|
47
|
+
} catch (error) {
|
|
48
|
+
return this.handleExecutionError(
|
|
49
|
+
error,
|
|
50
|
+
context,
|
|
51
|
+
traceId,
|
|
52
|
+
Date.now() - startTime
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Execute tool with validation
|
|
58
|
+
*/
|
|
59
|
+
async executeWithValidation(toolName, input, sessionContext) {
|
|
60
|
+
return this.execute(toolName, input, sessionContext);
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Process form submission
|
|
64
|
+
*/
|
|
65
|
+
async processFormSubmission(toolName, formId, parameters, sessionContext) {
|
|
66
|
+
const traceId = `form-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
|
|
67
|
+
const startTime = Date.now();
|
|
68
|
+
try {
|
|
69
|
+
const formSubmission = {
|
|
70
|
+
formId,
|
|
71
|
+
toolName,
|
|
72
|
+
parameters,
|
|
73
|
+
timestamp: Date.now()
|
|
74
|
+
};
|
|
75
|
+
const processedInput = await this.formEngine.processSubmission(
|
|
76
|
+
formSubmission
|
|
77
|
+
);
|
|
78
|
+
return this.execute(toolName, processedInput, sessionContext);
|
|
79
|
+
} catch (error) {
|
|
80
|
+
return {
|
|
81
|
+
success: false,
|
|
82
|
+
output: "Form submission processing failed",
|
|
83
|
+
error: error instanceof Error ? error.message : String(error),
|
|
84
|
+
traceId,
|
|
85
|
+
executionTime: Date.now() - startTime
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Check if form generation is required
|
|
91
|
+
*/
|
|
92
|
+
async checkFormGeneration(context) {
|
|
93
|
+
const inputRecord = context.input;
|
|
94
|
+
if (inputRecord?.__fromForm === true || inputRecord?.renderForm === false) {
|
|
95
|
+
return { requiresForm: false };
|
|
96
|
+
}
|
|
97
|
+
if (!this.formEngine.shouldGenerateForm(context.toolEntry.tool, context.input)) {
|
|
98
|
+
return { requiresForm: false };
|
|
99
|
+
}
|
|
100
|
+
const formMessage = await this.formEngine.generateForm(
|
|
101
|
+
context.toolName,
|
|
102
|
+
context.toolEntry.tool,
|
|
103
|
+
context.input
|
|
104
|
+
);
|
|
105
|
+
if (formMessage) {
|
|
106
|
+
return { requiresForm: true, formMessage };
|
|
107
|
+
}
|
|
108
|
+
return { requiresForm: false };
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Execute tool directly
|
|
112
|
+
*/
|
|
113
|
+
async executeToolDirect(context) {
|
|
114
|
+
const { toolEntry, input } = context;
|
|
115
|
+
const parameters = input || {};
|
|
116
|
+
const mergedArgs = { ...parameters, renderForm: false };
|
|
117
|
+
if (toolEntry.wrapper) {
|
|
118
|
+
return this.executeWrappedTool(toolEntry, mergedArgs);
|
|
119
|
+
}
|
|
120
|
+
return await toolEntry.tool.call(mergedArgs);
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Execute wrapped tool
|
|
124
|
+
*/
|
|
125
|
+
async executeWrappedTool(toolEntry, mergedArgs) {
|
|
126
|
+
const wrapper = toolEntry.wrapper;
|
|
127
|
+
if (!wrapper) {
|
|
128
|
+
throw new Error("Tool wrapper not found");
|
|
129
|
+
}
|
|
130
|
+
const wrapperAsAny = wrapper;
|
|
131
|
+
if (wrapperAsAny.executeOriginal) {
|
|
132
|
+
return await wrapperAsAny.executeOriginal(mergedArgs);
|
|
133
|
+
}
|
|
134
|
+
if (wrapperAsAny.originalTool?.call) {
|
|
135
|
+
return await wrapperAsAny.originalTool.call(mergedArgs);
|
|
136
|
+
}
|
|
137
|
+
return await toolEntry.originalTool.call(mergedArgs);
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Handle execution error
|
|
141
|
+
*/
|
|
142
|
+
handleExecutionError(error, context, traceId, executionTime) {
|
|
143
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
144
|
+
if (error instanceof ZodError) {
|
|
145
|
+
return {
|
|
146
|
+
success: false,
|
|
147
|
+
output: "Validation error occurred",
|
|
148
|
+
error: errorMessage,
|
|
149
|
+
traceId,
|
|
150
|
+
executionTime
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
this.logger.error(`Tool execution failed: ${context.toolName}`, {
|
|
154
|
+
traceId,
|
|
155
|
+
error: errorMessage
|
|
156
|
+
});
|
|
157
|
+
return {
|
|
158
|
+
success: false,
|
|
159
|
+
output: "Tool execution failed",
|
|
160
|
+
error: errorMessage,
|
|
161
|
+
traceId,
|
|
162
|
+
executionTime
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Build default session context
|
|
167
|
+
*/
|
|
168
|
+
buildDefaultSession() {
|
|
169
|
+
return {
|
|
170
|
+
sessionId: `session-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
|
|
171
|
+
timestamp: Date.now()
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Get statistics about the pipeline
|
|
176
|
+
*/
|
|
177
|
+
getStatistics() {
|
|
178
|
+
return {
|
|
179
|
+
totalMiddleware: 0,
|
|
180
|
+
registeredMiddleware: []
|
|
181
|
+
};
|
|
24
182
|
}
|
|
25
183
|
}
|
|
26
184
|
export {
|
|
27
|
-
|
|
28
|
-
DEFAULT_CONTENT_REFERENCE_CONFIG
|
|
185
|
+
ExecutionPipeline
|
|
29
186
|
};
|
|
30
187
|
//# sourceMappingURL=index41.js.map
|
package/dist/esm/index41.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index41.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":"index41.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,g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/esm/index42.js
CHANGED
|
@@ -1,10 +1,30 @@
|
|
|
1
|
-
const
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
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
|
+
}
|
|
6
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
|
+
}
|
|
7
26
|
export {
|
|
8
|
-
|
|
27
|
+
ContentReferenceError,
|
|
28
|
+
DEFAULT_CONTENT_REFERENCE_CONFIG
|
|
9
29
|
};
|
|
10
30
|
//# sourceMappingURL=index42.js.map
|
package/dist/esm/index42.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index42.js","sources":["../../src/
|
|
1
|
+
{"version":3,"file":"index42.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;"}
|
package/dist/esm/index6.js
CHANGED
|
@@ -209,10 +209,6 @@ const _ConversationalAgent = class _ConversationalAgent {
|
|
|
209
209
|
if (!this.agent) {
|
|
210
210
|
throw new Error(_ConversationalAgent.NOT_INITIALIZED_ERROR);
|
|
211
211
|
}
|
|
212
|
-
const internalAgent = this.agent;
|
|
213
|
-
if (!internalAgent.processFormSubmission || typeof internalAgent.processFormSubmission !== "function") {
|
|
214
|
-
throw new Error("processFormSubmission not available on internal agent");
|
|
215
|
-
}
|
|
216
212
|
try {
|
|
217
213
|
this.logger.info("Processing form submission:", {
|
|
218
214
|
formId: submission.formId,
|
|
@@ -220,7 +216,7 @@ const _ConversationalAgent = class _ConversationalAgent {
|
|
|
220
216
|
parameterKeys: Object.keys(submission.parameters || {}),
|
|
221
217
|
hasContext: !!submission.context
|
|
222
218
|
});
|
|
223
|
-
const response = await
|
|
219
|
+
const response = await this.agent.processFormSubmission(submission);
|
|
224
220
|
this.logger.info("Form submission processed successfully");
|
|
225
221
|
return response;
|
|
226
222
|
} catch (error) {
|
package/dist/esm/index6.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index6.js","sources":["../../src/conversational-agent.ts"],"sourcesContent":["import {\n ServerSigner,\n getAllHederaCorePlugins,\n BasePlugin,\n} from 'hedera-agent-kit';\nimport { Logger, type NetworkType } from '@hashgraphonline/standards-sdk';\nimport { createAgent } from './agent-factory';\nimport { LangChainProvider } from './providers';\nimport type { ChatResponse, ConversationContext } from './base-agent';\nimport { ChatOpenAI } from '@langchain/openai';\nimport { ChatAnthropic } from '@langchain/anthropic';\nimport {\n HumanMessage,\n AIMessage,\n SystemMessage,\n} from '@langchain/core/messages';\nimport type { AgentOperationalMode, MirrorNodeConfig } from 'hedera-agent-kit';\nimport { HCS10Plugin } from './plugins/hcs-10/HCS10Plugin';\nimport { HCS2Plugin } from './plugins/hcs-2/HCS2Plugin';\nimport { InscribePlugin } from './plugins/inscribe/InscribePlugin';\nimport { HbarPlugin } from './plugins/hbar/HbarPlugin';\nimport { OpenConvaiState } from '@hashgraphonline/standards-agent-kit';\nimport type { IStateManager } from '@hashgraphonline/standards-agent-kit';\nimport { getSystemMessage } from './config/system-message';\nimport type { MCPServerConfig, MCPConnectionStatus } from './mcp/types';\nimport { ContentStoreManager } from './services/content-store-manager';\nimport { SmartMemoryManager, type SmartMemoryConfig } from './memory';\nimport {\n createEntityTools,\n ResolveEntitiesTool,\n ExtractEntitiesTool,\n} from './tools/entity-resolver-tool';\nimport type { FormSubmission } from './forms/types';\n\nexport type ToolDescriptor = {\n name: string;\n namespace?: string;\n};\n\nexport type ChatHistoryItem = {\n type: 'human' | 'ai' | 'system';\n content: string;\n};\n\nexport type AgentInstance = ReturnType<typeof createAgent>;\n\nexport type MirrorNetwork = 'testnet' | 'mainnet' | 'previewnet';\n\nconst DEFAULT_MODEL_NAME = 'gpt-4o';\nconst DEFAULT_TEMPERATURE = 0.1;\nconst DEFAULT_NETWORK = 'testnet';\nconst DEFAULT_OPERATIONAL_MODE: AgentOperationalMode = 'autonomous';\n\nexport interface ConversationalAgentOptions {\n accountId: string;\n privateKey: string;\n network?: NetworkType;\n openAIApiKey: string;\n openAIModelName?: string;\n llmProvider?: 'openai' | 'anthropic';\n verbose?: boolean;\n operationalMode?: AgentOperationalMode;\n userAccountId?: string;\n customSystemMessagePreamble?: string;\n customSystemMessagePostamble?: string;\n additionalPlugins?: BasePlugin[];\n stateManager?: IStateManager;\n scheduleUserTransactionsInBytesMode?: boolean;\n mirrorNodeConfig?: MirrorNodeConfig;\n disableLogging?: boolean;\n enabledPlugins?: string[];\n toolFilter?: (tool: { name: string; namespace?: string }) => boolean;\n mcpServers?: MCPServerConfig[];\n\n /** Enable automatic entity memory functionality (default: true) */\n entityMemoryEnabled?: boolean;\n\n /** Configuration for entity memory system */\n entityMemoryConfig?: SmartMemoryConfig;\n}\n\n/**\n * The ConversationalAgent class is an optional wrapper around the HederaConversationalAgent class,\n * which includes the OpenConvAIPlugin and the OpenConvaiState by default.\n * If you want to use a different plugin or state manager, you can pass them in the options.\n * This class is not required and the plugin can be used directly with the HederaConversationalAgent class.\n *\n * @param options - The options for the ConversationalAgent.\n * @returns A new instance of the ConversationalAgent class.\n */\nexport class ConversationalAgent {\n private static readonly NOT_INITIALIZED_ERROR = 'Agent not initialized. Call initialize() first.';\n protected agent?: AgentInstance;\n public hcs10Plugin: HCS10Plugin;\n public hcs2Plugin: HCS2Plugin;\n public inscribePlugin: InscribePlugin;\n public hbarPlugin: HbarPlugin;\n public stateManager: IStateManager;\n private options: ConversationalAgentOptions;\n public logger: Logger;\n public contentStoreManager?: ContentStoreManager;\n public memoryManager?: SmartMemoryManager | undefined;\n private entityTools?: {\n resolveEntities: ResolveEntitiesTool;\n extractEntities: ExtractEntitiesTool;\n };\n\n constructor(options: ConversationalAgentOptions) {\n this.options = options;\n this.stateManager = options.stateManager || new OpenConvaiState();\n this.hcs10Plugin = new HCS10Plugin();\n this.hcs2Plugin = new HCS2Plugin();\n this.inscribePlugin = new InscribePlugin();\n this.hbarPlugin = new HbarPlugin();\n this.logger = new Logger({\n module: 'ConversationalAgent',\n silent: options.disableLogging || false,\n });\n\n if (this.options.entityMemoryEnabled !== false) {\n if (!options.openAIApiKey) {\n throw new Error(\n 'OpenAI API key is required when entity memory is enabled'\n );\n }\n\n this.memoryManager = new SmartMemoryManager(\n this.options.entityMemoryConfig\n );\n this.logger.info('Entity memory initialized');\n\n this.entityTools = createEntityTools(options.openAIApiKey, 'gpt-4o-mini');\n this.logger.info('LLM-based entity resolver tools initialized');\n }\n }\n\n /**\n * Initialize the conversational agent with Hedera Hashgraph connection and AI configuration\n * @throws {Error} If account ID or private key is missing\n * @throws {Error} If initialization fails\n */\n async initialize(): Promise<void> {\n const {\n accountId,\n privateKey,\n network = DEFAULT_NETWORK,\n openAIApiKey,\n openAIModelName = DEFAULT_MODEL_NAME,\n llmProvider = 'openai',\n } = this.options;\n\n this.validateOptions(accountId, privateKey);\n\n try {\n const serverSigner = new ServerSigner(\n accountId!,\n privateKey!,\n network as MirrorNetwork\n );\n\n let llm: ChatOpenAI | ChatAnthropic;\n if (llmProvider === 'anthropic') {\n llm = new ChatAnthropic({\n apiKey: openAIApiKey,\n modelName: openAIModelName || 'claude-3-5-sonnet-20241022',\n temperature: DEFAULT_TEMPERATURE,\n });\n } else {\n const modelName = openAIModelName || 'gpt-4o-mini';\n const isGPT5Model =\n modelName.toLowerCase().includes('gpt-5') ||\n modelName.toLowerCase().includes('gpt5');\n llm = new ChatOpenAI({\n apiKey: openAIApiKey,\n modelName: openAIModelName,\n ...(isGPT5Model\n ? { temperature: 1 }\n : { temperature: DEFAULT_TEMPERATURE }),\n });\n }\n\n this.logger.info('Preparing plugins...');\n const allPlugins = this.preparePlugins();\n this.logger.info('Creating agent config...');\n const agentConfig = this.createAgentConfig(serverSigner, llm, allPlugins);\n\n this.logger.info('Creating agent...');\n this.agent = createAgent(agentConfig);\n this.logger.info('Agent created');\n\n this.logger.info('Configuring HCS10 plugin...');\n this.configureHCS10Plugin(allPlugins);\n this.logger.info('HCS10 plugin configured');\n\n this.contentStoreManager = new ContentStoreManager();\n await this.contentStoreManager.initialize();\n this.logger.info(\n 'ContentStoreManager initialized for content reference support'\n );\n\n this.logger.info('About to call agent.boot()');\n this.logger.info('🔥 About to call agent.boot()');\n await this.agent.boot();\n this.logger.info('agent.boot() completed');\n this.logger.info('🔥 agent.boot() completed');\n\n if (this.agent) {\n const cfg = agentConfig;\n cfg.filtering = cfg.filtering || {};\n const originalPredicate = cfg.filtering.toolPredicate as\n | ((t: ToolDescriptor) => boolean)\n | undefined;\n const userPredicate = this.options.toolFilter;\n cfg.filtering.toolPredicate = (tool: ToolDescriptor): boolean => {\n if (tool && tool.name === 'hedera-account-transfer-hbar') {\n return false;\n }\n if (tool && tool.name === 'hedera-hts-airdrop-token') {\n return false;\n }\n if (originalPredicate && !originalPredicate(tool)) {\n return false;\n }\n if (userPredicate && !userPredicate(tool)) {\n return false;\n }\n return true;\n };\n }\n\n if (this.options.mcpServers && this.options.mcpServers.length > 0) {\n this.connectMCP();\n }\n } catch (error) {\n this.logger.error('Failed to initialize ConversationalAgent:', error);\n throw error;\n }\n }\n\n /**\n * Get the HCS-10 plugin instance\n * @returns {HCS10Plugin} The HCS-10 plugin instance\n */\n getPlugin(): HCS10Plugin {\n return this.hcs10Plugin;\n }\n\n /**\n * Get the state manager instance\n * @returns {IStateManager} The state manager instance\n */\n getStateManager(): IStateManager {\n return this.stateManager;\n }\n\n /**\n * Get the underlying agent instance\n * @returns {ReturnType<typeof createAgent>} The agent instance\n * @throws {Error} If agent is not initialized\n */\n getAgent(): ReturnType<typeof createAgent> {\n if (!this.agent) {\n throw new Error(ConversationalAgent.NOT_INITIALIZED_ERROR);\n }\n return this.agent;\n }\n\n /**\n * Get the conversational agent instance (alias for getAgent)\n * @returns {ReturnType<typeof createAgent>} The agent instance\n * @throws {Error} If agent is not initialized\n */\n getConversationalAgent(): ReturnType<typeof createAgent> {\n return this.getAgent();\n }\n\n /**\n * Process a message through the conversational agent\n * @param {string} message - The message to process\n * @param {Array<{type: 'human' | 'ai'; content: string}>} chatHistory - Previous chat history\n * @returns {Promise<ChatResponse>} The agent's response\n * @throws {Error} If agent is not initialized\n */\n async processMessage(\n message: string,\n chatHistory: ChatHistoryItem[] = []\n ): Promise<ChatResponse> {\n if (!this.agent) {\n throw new Error('Agent not initialized. Call initialize() first.');\n }\n\n try {\n const resolvedMessage = message;\n\n const messages = chatHistory.map((msg) => {\n const content = msg.content;\n if (msg.type === 'system') {\n return new SystemMessage(content);\n }\n return msg.type === 'human'\n ? new HumanMessage(content)\n : new AIMessage(content);\n });\n\n const context: ConversationContext = { messages };\n const response = await this.agent.chat(resolvedMessage, context);\n\n if (\n this.memoryManager &&\n this.options.operationalMode !== 'returnBytes'\n ) {\n await this.extractAndStoreEntities(response, message);\n }\n\n this.logger.info('Message processed successfully');\n return response;\n } catch (error) {\n this.logger.error('Error processing message:', error);\n throw error;\n }\n }\n\n /**\n * Process form submission through the conversational agent\n * @param {FormSubmission} submission - The form submission data\n * @returns {Promise<ChatResponse>} The agent's response after processing the form\n * @throws {Error} If agent is not initialized or doesn't support form processing\n */\n async processFormSubmission(\n submission: FormSubmission\n ): Promise<ChatResponse> {\n if (!this.agent) {\n throw new Error(ConversationalAgent.NOT_INITIALIZED_ERROR);\n }\n\n const internalAgent = this.agent as {\n processFormSubmission?: (\n submission: FormSubmission\n ) => Promise<ChatResponse>;\n };\n if (\n !internalAgent.processFormSubmission ||\n typeof internalAgent.processFormSubmission !== 'function'\n ) {\n throw new Error('processFormSubmission not available on internal agent');\n }\n\n try {\n this.logger.info('Processing form submission:', {\n formId: submission.formId,\n toolName: submission.toolName,\n parameterKeys: Object.keys(submission.parameters || {}),\n hasContext: !!submission.context,\n });\n const response = await internalAgent.processFormSubmission(submission);\n this.logger.info('Form submission processed successfully');\n return response;\n } catch (error) {\n this.logger.error('Error processing form submission:', error);\n throw error;\n }\n }\n\n /**\n * Validates initialization options and throws if required fields are missing.\n *\n * @param accountId - The Hedera account ID\n * @param privateKey - The private key for the account\n * @throws {Error} If required fields are missing\n */\n private validateOptions(accountId?: string, privateKey?: string): void {\n if (!accountId || !privateKey) {\n throw new Error('Account ID and private key are required');\n }\n\n if (typeof accountId !== 'string') {\n throw new Error(\n `Account ID must be a string, received ${typeof accountId}`\n );\n }\n\n if (typeof privateKey !== 'string') {\n throw new Error(\n `Private key must be a string, received ${typeof privateKey}: ${JSON.stringify(\n privateKey\n )}`\n );\n }\n\n if (privateKey.length < 10) {\n throw new Error('Private key appears to be invalid (too short)');\n }\n }\n\n /**\n * Prepares the list of plugins to use based on configuration.\n *\n * @returns Array of plugins to initialize with the agent\n */\n private preparePlugins(): BasePlugin[] {\n const { additionalPlugins = [], enabledPlugins } = this.options;\n\n const standardPlugins = [\n this.hcs10Plugin,\n this.hcs2Plugin,\n this.inscribePlugin,\n this.hbarPlugin,\n ];\n\n const corePlugins = getAllHederaCorePlugins();\n\n if (enabledPlugins) {\n const enabledSet = new Set(enabledPlugins);\n const filteredPlugins = [...standardPlugins, ...corePlugins].filter(\n (plugin) => enabledSet.has(plugin.id)\n );\n return [...filteredPlugins, ...additionalPlugins];\n }\n\n return [...standardPlugins, ...corePlugins, ...additionalPlugins];\n }\n\n /**\n * Creates the agent configuration object.\n *\n * @param serverSigner - The server signer instance\n * @param llm - The language model instance\n * @param allPlugins - Array of plugins to use\n * @returns Configuration object for creating the agent\n */\n private createAgentConfig(\n serverSigner: ServerSigner,\n llm: ChatOpenAI | ChatAnthropic,\n allPlugins: BasePlugin[]\n ): Parameters<typeof createAgent>[0] {\n const {\n operationalMode = DEFAULT_OPERATIONAL_MODE,\n userAccountId,\n scheduleUserTransactionsInBytesMode,\n customSystemMessagePreamble,\n customSystemMessagePostamble,\n verbose = false,\n mirrorNodeConfig,\n disableLogging,\n accountId = '',\n } = this.options;\n\n return {\n framework: 'langchain',\n signer: serverSigner,\n execution: {\n mode: operationalMode === 'autonomous' ? 'direct' : 'bytes',\n operationalMode: operationalMode,\n ...(userAccountId && { userAccountId }),\n ...(scheduleUserTransactionsInBytesMode !== undefined && {\n scheduleUserTransactionsInBytesMode:\n scheduleUserTransactionsInBytesMode,\n scheduleUserTransactions: scheduleUserTransactionsInBytesMode,\n }),\n },\n ai: {\n provider: new LangChainProvider(llm),\n temperature: DEFAULT_TEMPERATURE,\n },\n filtering: {\n toolPredicate: (tool: ToolDescriptor): boolean => {\n if (tool.name === 'hedera-account-transfer-hbar') return false;\n if (this.options.toolFilter && !this.options.toolFilter(tool)) {\n return false;\n }\n return true;\n },\n },\n messaging: {\n systemPreamble:\n customSystemMessagePreamble || getSystemMessage(accountId),\n ...(customSystemMessagePostamble && {\n systemPostamble: customSystemMessagePostamble,\n }),\n conciseMode: true,\n },\n extensions: {\n plugins: allPlugins,\n ...(mirrorNodeConfig && {\n mirrorConfig: mirrorNodeConfig as Record<string, unknown>,\n }),\n },\n ...(this.options.mcpServers && {\n mcp: {\n servers: this.options.mcpServers,\n autoConnect: false,\n },\n }),\n debug: {\n verbose,\n silent: disableLogging ?? false,\n },\n };\n }\n\n /**\n * Configures the HCS-10 plugin with the state manager.\n *\n * @param allPlugins - Array of all plugins\n */\n private configureHCS10Plugin(allPlugins: BasePlugin[]): void {\n const hcs10 = allPlugins.find((p) => p.id === 'hcs-10');\n if (hcs10) {\n (\n hcs10 as BasePlugin & { appConfig?: Record<string, unknown> }\n ).appConfig = {\n stateManager: this.stateManager,\n };\n }\n }\n\n /**\n * Create a ConversationalAgent with specific plugins enabled\n */\n private static withPlugins(\n options: ConversationalAgentOptions,\n plugins: string[]\n ): ConversationalAgent {\n return new ConversationalAgent({\n ...options,\n enabledPlugins: plugins,\n });\n }\n\n /**\n * Create a ConversationalAgent with only HTS (Hedera Token Service) tools enabled\n */\n static withHTS(options: ConversationalAgentOptions): ConversationalAgent {\n return this.withPlugins(options, ['hts-token']);\n }\n\n /**\n * Create a ConversationalAgent with only HCS-2 tools enabled\n */\n static withHCS2(options: ConversationalAgentOptions): ConversationalAgent {\n return this.withPlugins(options, ['hcs-2']);\n }\n\n /**\n * Create a ConversationalAgent with only HCS-10 tools enabled\n */\n static withHCS10(options: ConversationalAgentOptions): ConversationalAgent {\n return this.withPlugins(options, ['hcs-10']);\n }\n\n /**\n * Create a ConversationalAgent with only inscription tools enabled\n */\n static withInscribe(\n options: ConversationalAgentOptions\n ): ConversationalAgent {\n return this.withPlugins(options, ['inscribe']);\n }\n\n /**\n * Create a ConversationalAgent with only account management tools enabled\n */\n static withAccount(options: ConversationalAgentOptions): ConversationalAgent {\n return this.withPlugins(options, ['account']);\n }\n\n /**\n * Create a ConversationalAgent with only file service tools enabled\n */\n static withFileService(\n options: ConversationalAgentOptions\n ): ConversationalAgent {\n return this.withPlugins(options, ['file-service']);\n }\n\n /**\n * Create a ConversationalAgent with only consensus service tools enabled\n */\n static withConsensusService(\n options: ConversationalAgentOptions\n ): ConversationalAgent {\n return this.withPlugins(options, ['consensus-service']);\n }\n\n /**\n * Create a ConversationalAgent with only smart contract tools enabled\n */\n static withSmartContract(\n options: ConversationalAgentOptions\n ): ConversationalAgent {\n return this.withPlugins(options, ['smart-contract']);\n }\n\n /**\n * Create a ConversationalAgent with all HCS standards plugins\n */\n static withAllStandards(\n options: ConversationalAgentOptions\n ): ConversationalAgent {\n return this.withPlugins(options, ['hcs-10', 'hcs-2', 'inscribe']);\n }\n\n /**\n * Create a ConversationalAgent with minimal Hedera tools (no HCS standards)\n */\n static minimal(options: ConversationalAgentOptions): ConversationalAgent {\n return this.withPlugins(options, []);\n }\n\n /**\n * Create a ConversationalAgent with MCP servers configured\n */\n static withMCP(\n options: ConversationalAgentOptions,\n mcpServers: MCPServerConfig[]\n ): ConversationalAgent {\n return new ConversationalAgent({\n ...options,\n mcpServers,\n });\n }\n\n /**\n * Extract and store entities from agent responses\n * @param response - Agent response containing potential entity information\n * @param originalMessage - Original user message for context\n */\n private async extractAndStoreEntities(\n response: unknown,\n originalMessage: string\n ): Promise<void> {\n if (!this.memoryManager || !this.entityTools) {\n return;\n }\n\n try {\n this.logger.info('Starting LLM-based entity extraction');\n\n const responseText = this.extractResponseText(response);\n\n const entitiesJson = await this.entityTools.extractEntities.call({\n response: responseText,\n userMessage: originalMessage,\n });\n\n try {\n const entities = JSON.parse(entitiesJson);\n\n for (const entity of entities) {\n if (\n entity &&\n typeof entity === 'object' &&\n 'name' in entity &&\n 'type' in entity &&\n 'id' in entity\n ) {\n this.logger.info(\n `Storing entity: ${entity.name} (${entity.type}) -> ${entity.id}`\n );\n\n const transactionId = this.extractTransactionId(response);\n const idStr = String(entity.id);\n const isHederaId = /^0\\.0\\.[0-9]+$/.test(idStr);\n if (!isHederaId) {\n this.logger.warn('Skipping non-ID entity from extraction', {\n id: idStr,\n name: String(entity.name),\n type: String(entity.type),\n });\n } else {\n this.memoryManager.storeEntityAssociation(\n idStr,\n String(entity.name),\n String(entity.type),\n transactionId\n );\n }\n }\n }\n\n if (entities.length > 0) {\n this.logger.info(\n `Stored ${entities.length} entities via LLM extraction`\n );\n } else {\n this.logger.info('No entities found in response via LLM extraction');\n }\n } catch (parseError) {\n this.logger.error(\n 'Failed to parse extracted entities JSON:',\n parseError\n );\n throw parseError;\n }\n } catch (error) {\n this.logger.error('Entity extraction failed:', error);\n throw error;\n }\n }\n\n /**\n * Extract transaction ID from response if available\n * @param response - Transaction response\n * @returns Transaction ID or undefined\n */\n private extractTransactionId(response: unknown): string | undefined {\n try {\n if (\n typeof response === 'object' &&\n response &&\n 'transactionId' in response\n ) {\n const responseWithTxId = response as { transactionId?: unknown };\n return typeof responseWithTxId.transactionId === 'string'\n ? responseWithTxId.transactionId\n : undefined;\n }\n if (typeof response === 'string') {\n const match = response.match(\n /transaction[\\s\\w]*ID[\\s:\"]*([0-9a-fA-F@\\.\\-]+)/i\n );\n return match ? match[1] : undefined;\n }\n return undefined;\n } catch {\n return undefined;\n }\n }\n\n /**\n * Connect to MCP servers asynchronously\n * @private\n */\n private connectMCP(): void {\n if (!this.agent || !this.options.mcpServers) {\n return;\n }\n\n this.agent\n .connectMCPServers()\n .catch((e) => {\n this.logger.error('Failed to connect MCP servers:', e);\n })\n .then(() => {\n this.logger.info('MCP servers connected successfully');\n });\n }\n\n /**\n * Get MCP connection status for all servers\n * @returns {Map<string, MCPConnectionStatus>} Connection status map\n */\n getMCPConnectionStatus(): Map<string, MCPConnectionStatus> {\n if (this.agent) {\n return this.agent.getMCPConnectionStatus();\n }\n return new Map();\n }\n\n /**\n * Check if a specific MCP server is connected\n * @param {string} serverName - Name of the server to check\n * @returns {boolean} True if connected, false otherwise\n */\n isMCPServerConnected(serverName: string): boolean {\n if (this.agent) {\n const statusMap = this.agent.getMCPConnectionStatus();\n const status = statusMap.get(serverName);\n return status?.connected ?? false;\n }\n return false;\n }\n\n /**\n * Clean up resources\n */\n async cleanup(): Promise<void> {\n try {\n this.logger.info('Cleaning up ConversationalAgent...');\n\n if (this.memoryManager) {\n try {\n this.memoryManager.dispose();\n this.logger.info('Memory manager cleaned up successfully');\n } catch (error) {\n this.logger.warn('Error cleaning up memory manager:', error);\n }\n this.memoryManager = undefined;\n }\n\n if (this.contentStoreManager) {\n await this.contentStoreManager.dispose();\n this.logger.info('ContentStoreManager cleaned up');\n }\n\n this.logger.info('ConversationalAgent cleanup completed');\n } catch (error) {\n this.logger.error('Error during cleanup:', error);\n }\n }\n\n private extractResponseText(response: unknown): string {\n if (typeof response === 'string') {\n return response;\n }\n\n if (response && typeof response === 'object' && 'output' in response) {\n const responseWithOutput = response as { output: unkn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;AACnB,eAAK,OAAO,KAAK,wCAAwC;AAAA,QAC3D,SAAS,OAAO;AACd,eAAK,OAAO,KAAK,qCAAqC,KAAK;AAAA,QAC7D;AACA,aAAK,gBAAgB;AAAA,MACvB;AAEA,UAAI,KAAK,qBAAqB;AAC5B,cAAM,KAAK,oBAAoB,QAAA;AAC/B,aAAK,OAAO,KAAK,gCAAgC;AAAA,MACnD;AAEA,WAAK,OAAO,KAAK,uCAAuC;AAAA,IAC1D,SAAS,OAAO;AACd,WAAK,OAAO,MAAM,yBAAyB,KAAK;AAAA,IAClD;AAAA,EACF;AAAA,EAEQ,oBAAoB,UAA2B;AACrD,QAAI,OAAO,aAAa,UAAU;AAChC,aAAO;AAAA,IACT;AAEA,QAAI,YAAY,OAAO,aAAa,YAAY,YAAY,UAAU;AACpE,YAAM,qBAAqB;AAC3B,aAAO,OAAO,mBAAmB,MAAM;AAAA,IACzC;AAEA,WAAO,KAAK,UAAU,QAAQ;AAAA,EAChC;AACF;AAltBE,qBAAwB,wBAAwB;AAD3C,IAAM,sBAAN;"}
|
|
1
|
+
{"version":3,"file":"index6.js","sources":["../../src/conversational-agent.ts"],"sourcesContent":["import {\n ServerSigner,\n getAllHederaCorePlugins,\n BasePlugin,\n} from 'hedera-agent-kit';\nimport { Logger, type NetworkType } from '@hashgraphonline/standards-sdk';\nimport { createAgent } from './agent-factory';\nimport { LangChainProvider } from './providers';\nimport type { ChatResponse, ConversationContext } from './base-agent';\nimport { ChatOpenAI } from '@langchain/openai';\nimport { ChatAnthropic } from '@langchain/anthropic';\nimport {\n HumanMessage,\n AIMessage,\n SystemMessage,\n} from '@langchain/core/messages';\nimport type { AgentOperationalMode, MirrorNodeConfig } from 'hedera-agent-kit';\nimport { HCS10Plugin } from './plugins/hcs-10/HCS10Plugin';\nimport { HCS2Plugin } from './plugins/hcs-2/HCS2Plugin';\nimport { InscribePlugin } from './plugins/inscribe/InscribePlugin';\nimport { HbarPlugin } from './plugins/hbar/HbarPlugin';\nimport { OpenConvaiState } from '@hashgraphonline/standards-agent-kit';\nimport type { IStateManager } from '@hashgraphonline/standards-agent-kit';\nimport { getSystemMessage } from './config/system-message';\nimport type { MCPServerConfig, MCPConnectionStatus } from './mcp/types';\nimport { ContentStoreManager } from './services/content-store-manager';\nimport { SmartMemoryManager, type SmartMemoryConfig } from './memory';\nimport {\n createEntityTools,\n ResolveEntitiesTool,\n ExtractEntitiesTool,\n} from './tools/entity-resolver-tool';\nimport type { FormSubmission } from './forms/types';\n\nexport type ToolDescriptor = {\n name: string;\n namespace?: string;\n};\n\nexport type ChatHistoryItem = {\n type: 'human' | 'ai' | 'system';\n content: string;\n};\n\nexport type AgentInstance = ReturnType<typeof createAgent>;\n\nexport type MirrorNetwork = 'testnet' | 'mainnet' | 'previewnet';\n\nconst DEFAULT_MODEL_NAME = 'gpt-4o';\nconst DEFAULT_TEMPERATURE = 0.1;\nconst DEFAULT_NETWORK = 'testnet';\nconst DEFAULT_OPERATIONAL_MODE: AgentOperationalMode = 'autonomous';\n\nexport interface ConversationalAgentOptions {\n accountId: string;\n privateKey: string;\n network?: NetworkType;\n openAIApiKey: string;\n openAIModelName?: string;\n llmProvider?: 'openai' | 'anthropic';\n verbose?: boolean;\n operationalMode?: AgentOperationalMode;\n userAccountId?: string;\n customSystemMessagePreamble?: string;\n customSystemMessagePostamble?: string;\n additionalPlugins?: BasePlugin[];\n stateManager?: IStateManager;\n scheduleUserTransactionsInBytesMode?: boolean;\n mirrorNodeConfig?: MirrorNodeConfig;\n disableLogging?: boolean;\n enabledPlugins?: string[];\n toolFilter?: (tool: { name: string; namespace?: string }) => boolean;\n mcpServers?: MCPServerConfig[];\n\n /** Enable automatic entity memory functionality (default: true) */\n entityMemoryEnabled?: boolean;\n\n /** Configuration for entity memory system */\n entityMemoryConfig?: SmartMemoryConfig;\n}\n\n/**\n * The ConversationalAgent class is an optional wrapper around the HederaConversationalAgent class,\n * which includes the OpenConvAIPlugin and the OpenConvaiState by default.\n * If you want to use a different plugin or state manager, you can pass them in the options.\n * This class is not required and the plugin can be used directly with the HederaConversationalAgent class.\n *\n * @param options - The options for the ConversationalAgent.\n * @returns A new instance of the ConversationalAgent class.\n */\nexport class ConversationalAgent {\n private static readonly NOT_INITIALIZED_ERROR =\n 'Agent not initialized. Call initialize() first.';\n protected agent?: AgentInstance;\n public hcs10Plugin: HCS10Plugin;\n public hcs2Plugin: HCS2Plugin;\n public inscribePlugin: InscribePlugin;\n public hbarPlugin: HbarPlugin;\n public stateManager: IStateManager;\n private options: ConversationalAgentOptions;\n public logger: Logger;\n public contentStoreManager?: ContentStoreManager;\n public memoryManager?: SmartMemoryManager | undefined;\n private entityTools?: {\n resolveEntities: ResolveEntitiesTool;\n extractEntities: ExtractEntitiesTool;\n };\n\n constructor(options: ConversationalAgentOptions) {\n this.options = options;\n this.stateManager = options.stateManager || new OpenConvaiState();\n this.hcs10Plugin = new HCS10Plugin();\n this.hcs2Plugin = new HCS2Plugin();\n this.inscribePlugin = new InscribePlugin();\n this.hbarPlugin = new HbarPlugin();\n this.logger = new Logger({\n module: 'ConversationalAgent',\n silent: options.disableLogging || false,\n });\n\n if (this.options.entityMemoryEnabled !== false) {\n if (!options.openAIApiKey) {\n throw new Error(\n 'OpenAI API key is required when entity memory is enabled'\n );\n }\n\n this.memoryManager = new SmartMemoryManager(\n this.options.entityMemoryConfig\n );\n this.logger.info('Entity memory initialized');\n\n this.entityTools = createEntityTools(options.openAIApiKey, 'gpt-4o-mini');\n this.logger.info('LLM-based entity resolver tools initialized');\n }\n }\n\n /**\n * Initialize the conversational agent with Hedera Hashgraph connection and AI configuration\n * @throws {Error} If account ID or private key is missing\n * @throws {Error} If initialization fails\n */\n async initialize(): Promise<void> {\n const {\n accountId,\n privateKey,\n network = DEFAULT_NETWORK,\n openAIApiKey,\n openAIModelName = DEFAULT_MODEL_NAME,\n llmProvider = 'openai',\n } = this.options;\n\n this.validateOptions(accountId, privateKey);\n\n try {\n const serverSigner = new ServerSigner(\n accountId!,\n privateKey!,\n network as MirrorNetwork\n );\n\n let llm: ChatOpenAI | ChatAnthropic;\n if (llmProvider === 'anthropic') {\n llm = new ChatAnthropic({\n apiKey: openAIApiKey,\n modelName: openAIModelName || 'claude-3-5-sonnet-20241022',\n temperature: DEFAULT_TEMPERATURE,\n });\n } else {\n const modelName = openAIModelName || 'gpt-4o-mini';\n const isGPT5Model =\n modelName.toLowerCase().includes('gpt-5') ||\n modelName.toLowerCase().includes('gpt5');\n llm = new ChatOpenAI({\n apiKey: openAIApiKey,\n modelName: openAIModelName,\n ...(isGPT5Model\n ? { temperature: 1 }\n : { temperature: DEFAULT_TEMPERATURE }),\n });\n }\n\n this.logger.info('Preparing plugins...');\n const allPlugins = this.preparePlugins();\n this.logger.info('Creating agent config...');\n const agentConfig = this.createAgentConfig(serverSigner, llm, allPlugins);\n\n this.logger.info('Creating agent...');\n this.agent = createAgent(agentConfig);\n this.logger.info('Agent created');\n\n this.logger.info('Configuring HCS10 plugin...');\n this.configureHCS10Plugin(allPlugins);\n this.logger.info('HCS10 plugin configured');\n\n this.contentStoreManager = new ContentStoreManager();\n await this.contentStoreManager.initialize();\n this.logger.info(\n 'ContentStoreManager initialized for content reference support'\n );\n\n this.logger.info('About to call agent.boot()');\n this.logger.info('🔥 About to call agent.boot()');\n await this.agent.boot();\n this.logger.info('agent.boot() completed');\n this.logger.info('🔥 agent.boot() completed');\n\n if (this.agent) {\n const cfg = agentConfig;\n cfg.filtering = cfg.filtering || {};\n const originalPredicate = cfg.filtering.toolPredicate as\n | ((t: ToolDescriptor) => boolean)\n | undefined;\n const userPredicate = this.options.toolFilter;\n cfg.filtering.toolPredicate = (tool: ToolDescriptor): boolean => {\n if (tool && tool.name === 'hedera-account-transfer-hbar') {\n return false;\n }\n if (tool && tool.name === 'hedera-hts-airdrop-token') {\n return false;\n }\n if (originalPredicate && !originalPredicate(tool)) {\n return false;\n }\n if (userPredicate && !userPredicate(tool)) {\n return false;\n }\n return true;\n };\n }\n\n if (this.options.mcpServers && this.options.mcpServers.length > 0) {\n this.connectMCP();\n }\n } catch (error) {\n this.logger.error('Failed to initialize ConversationalAgent:', error);\n throw error;\n }\n }\n\n /**\n * Get the HCS-10 plugin instance\n * @returns {HCS10Plugin} The HCS-10 plugin instance\n */\n getPlugin(): HCS10Plugin {\n return this.hcs10Plugin;\n }\n\n /**\n * Get the state manager instance\n * @returns {IStateManager} The state manager instance\n */\n getStateManager(): IStateManager {\n return this.stateManager;\n }\n\n /**\n * Get the underlying agent instance\n * @returns {ReturnType<typeof createAgent>} The agent instance\n * @throws {Error} If agent is not initialized\n */\n getAgent(): ReturnType<typeof createAgent> {\n if (!this.agent) {\n throw new Error(ConversationalAgent.NOT_INITIALIZED_ERROR);\n }\n return this.agent;\n }\n\n /**\n * Get the conversational agent instance (alias for getAgent)\n * @returns {ReturnType<typeof createAgent>} The agent instance\n * @throws {Error} If agent is not initialized\n */\n getConversationalAgent(): ReturnType<typeof createAgent> {\n return this.getAgent();\n }\n\n /**\n * Process a message through the conversational agent\n * @param {string} message - The message to process\n * @param {Array<{type: 'human' | 'ai'; content: string}>} chatHistory - Previous chat history\n * @returns {Promise<ChatResponse>} The agent's response\n * @throws {Error} If agent is not initialized\n */\n async processMessage(\n message: string,\n chatHistory: ChatHistoryItem[] = []\n ): Promise<ChatResponse> {\n if (!this.agent) {\n throw new Error('Agent not initialized. Call initialize() first.');\n }\n\n try {\n const resolvedMessage = message;\n\n const messages = chatHistory.map((msg) => {\n const content = msg.content;\n if (msg.type === 'system') {\n return new SystemMessage(content);\n }\n return msg.type === 'human'\n ? new HumanMessage(content)\n : new AIMessage(content);\n });\n\n const context: ConversationContext = { messages };\n const response = await this.agent.chat(resolvedMessage, context);\n\n if (\n this.memoryManager &&\n this.options.operationalMode !== 'returnBytes'\n ) {\n await this.extractAndStoreEntities(response, message);\n }\n\n this.logger.info('Message processed successfully');\n return response;\n } catch (error) {\n this.logger.error('Error processing message:', error);\n throw error;\n }\n }\n\n /**\n * Process form submission through the conversational agent\n * @param {FormSubmission} submission - The form submission data\n * @returns {Promise<ChatResponse>} The agent's response after processing the form\n * @throws {Error} If agent is not initialized or doesn't support form processing\n */\n async processFormSubmission(\n submission: FormSubmission\n ): Promise<ChatResponse> {\n if (!this.agent) {\n throw new Error(ConversationalAgent.NOT_INITIALIZED_ERROR);\n }\n\n try {\n this.logger.info('Processing form submission:', {\n formId: submission.formId,\n toolName: submission.toolName,\n parameterKeys: Object.keys(submission.parameters || {}),\n hasContext: !!submission.context,\n });\n const response = await this.agent.processFormSubmission(submission);\n this.logger.info('Form submission processed successfully');\n return response;\n } catch (error) {\n this.logger.error('Error processing form submission:', error);\n throw error;\n }\n }\n\n /**\n * Validates initialization options and throws if required fields are missing.\n *\n * @param accountId - The Hedera account ID\n * @param privateKey - The private key for the account\n * @throws {Error} If required fields are missing\n */\n private validateOptions(accountId?: string, privateKey?: string): void {\n if (!accountId || !privateKey) {\n throw new Error('Account ID and private key are required');\n }\n\n if (typeof accountId !== 'string') {\n throw new Error(\n `Account ID must be a string, received ${typeof accountId}`\n );\n }\n\n if (typeof privateKey !== 'string') {\n throw new Error(\n `Private key must be a string, received ${typeof privateKey}: ${JSON.stringify(\n privateKey\n )}`\n );\n }\n\n if (privateKey.length < 10) {\n throw new Error('Private key appears to be invalid (too short)');\n }\n }\n\n /**\n * Prepares the list of plugins to use based on configuration.\n *\n * @returns Array of plugins to initialize with the agent\n */\n private preparePlugins(): BasePlugin[] {\n const { additionalPlugins = [], enabledPlugins } = this.options;\n\n const standardPlugins = [\n this.hcs10Plugin,\n this.hcs2Plugin,\n this.inscribePlugin,\n this.hbarPlugin,\n ];\n\n const corePlugins = getAllHederaCorePlugins();\n\n if (enabledPlugins) {\n const enabledSet = new Set(enabledPlugins);\n const filteredPlugins = [...standardPlugins, ...corePlugins].filter(\n (plugin) => enabledSet.has(plugin.id)\n );\n return [...filteredPlugins, ...additionalPlugins];\n }\n\n return [...standardPlugins, ...corePlugins, ...additionalPlugins];\n }\n\n /**\n * Creates the agent configuration object.\n *\n * @param serverSigner - The server signer instance\n * @param llm - The language model instance\n * @param allPlugins - Array of plugins to use\n * @returns Configuration object for creating the agent\n */\n private createAgentConfig(\n serverSigner: ServerSigner,\n llm: ChatOpenAI | ChatAnthropic,\n allPlugins: BasePlugin[]\n ): Parameters<typeof createAgent>[0] {\n const {\n operationalMode = DEFAULT_OPERATIONAL_MODE,\n userAccountId,\n scheduleUserTransactionsInBytesMode,\n customSystemMessagePreamble,\n customSystemMessagePostamble,\n verbose = false,\n mirrorNodeConfig,\n disableLogging,\n accountId = '',\n } = this.options;\n\n return {\n framework: 'langchain',\n signer: serverSigner,\n execution: {\n mode: operationalMode === 'autonomous' ? 'direct' : 'bytes',\n operationalMode: operationalMode,\n ...(userAccountId && { userAccountId }),\n ...(scheduleUserTransactionsInBytesMode !== undefined && {\n scheduleUserTransactionsInBytesMode:\n scheduleUserTransactionsInBytesMode,\n scheduleUserTransactions: scheduleUserTransactionsInBytesMode,\n }),\n },\n ai: {\n provider: new LangChainProvider(llm),\n temperature: DEFAULT_TEMPERATURE,\n },\n filtering: {\n toolPredicate: (tool: ToolDescriptor): boolean => {\n if (tool.name === 'hedera-account-transfer-hbar') return false;\n if (this.options.toolFilter && !this.options.toolFilter(tool)) {\n return false;\n }\n return true;\n },\n },\n messaging: {\n systemPreamble:\n customSystemMessagePreamble || getSystemMessage(accountId),\n ...(customSystemMessagePostamble && {\n systemPostamble: customSystemMessagePostamble,\n }),\n conciseMode: true,\n },\n extensions: {\n plugins: allPlugins,\n ...(mirrorNodeConfig && {\n mirrorConfig: mirrorNodeConfig as Record<string, unknown>,\n }),\n },\n ...(this.options.mcpServers && {\n mcp: {\n servers: this.options.mcpServers,\n autoConnect: false,\n },\n }),\n debug: {\n verbose,\n silent: disableLogging ?? false,\n },\n };\n }\n\n /**\n * Configures the HCS-10 plugin with the state manager.\n *\n * @param allPlugins - Array of all plugins\n */\n private configureHCS10Plugin(allPlugins: BasePlugin[]): void {\n const hcs10 = allPlugins.find((p) => p.id === 'hcs-10');\n if (hcs10) {\n (\n hcs10 as BasePlugin & { appConfig?: Record<string, unknown> }\n ).appConfig = {\n stateManager: this.stateManager,\n };\n }\n }\n\n /**\n * Create a ConversationalAgent with specific plugins enabled\n */\n private static withPlugins(\n options: ConversationalAgentOptions,\n plugins: string[]\n ): ConversationalAgent {\n return new ConversationalAgent({\n ...options,\n enabledPlugins: plugins,\n });\n }\n\n /**\n * Create a ConversationalAgent with only HTS (Hedera Token Service) tools enabled\n */\n static withHTS(options: ConversationalAgentOptions): ConversationalAgent {\n return this.withPlugins(options, ['hts-token']);\n }\n\n /**\n * Create a ConversationalAgent with only HCS-2 tools enabled\n */\n static withHCS2(options: ConversationalAgentOptions): ConversationalAgent {\n return this.withPlugins(options, ['hcs-2']);\n }\n\n /**\n * Create a ConversationalAgent with only HCS-10 tools enabled\n */\n static withHCS10(options: ConversationalAgentOptions): ConversationalAgent {\n return this.withPlugins(options, ['hcs-10']);\n }\n\n /**\n * Create a ConversationalAgent with only inscription tools enabled\n */\n static withInscribe(\n options: ConversationalAgentOptions\n ): ConversationalAgent {\n return this.withPlugins(options, ['inscribe']);\n }\n\n /**\n * Create a ConversationalAgent with only account management tools enabled\n */\n static withAccount(options: ConversationalAgentOptions): ConversationalAgent {\n return this.withPlugins(options, ['account']);\n }\n\n /**\n * Create a ConversationalAgent with only file service tools enabled\n */\n static withFileService(\n options: ConversationalAgentOptions\n ): ConversationalAgent {\n return this.withPlugins(options, ['file-service']);\n }\n\n /**\n * Create a ConversationalAgent with only consensus service tools enabled\n */\n static withConsensusService(\n options: ConversationalAgentOptions\n ): ConversationalAgent {\n return this.withPlugins(options, ['consensus-service']);\n }\n\n /**\n * Create a ConversationalAgent with only smart contract tools enabled\n */\n static withSmartContract(\n options: ConversationalAgentOptions\n ): ConversationalAgent {\n return this.withPlugins(options, ['smart-contract']);\n }\n\n /**\n * Create a ConversationalAgent with all HCS standards plugins\n */\n static withAllStandards(\n options: ConversationalAgentOptions\n ): ConversationalAgent {\n return this.withPlugins(options, ['hcs-10', 'hcs-2', 'inscribe']);\n }\n\n /**\n * Create a ConversationalAgent with minimal Hedera tools (no HCS standards)\n */\n static minimal(options: ConversationalAgentOptions): ConversationalAgent {\n return this.withPlugins(options, []);\n }\n\n /**\n * Create a ConversationalAgent with MCP servers configured\n */\n static withMCP(\n options: ConversationalAgentOptions,\n mcpServers: MCPServerConfig[]\n ): ConversationalAgent {\n return new ConversationalAgent({\n ...options,\n mcpServers,\n });\n }\n\n /**\n * Extract and store entities from agent responses\n * @param response - Agent response containing potential entity information\n * @param originalMessage - Original user message for context\n */\n private async extractAndStoreEntities(\n response: unknown,\n originalMessage: string\n ): Promise<void> {\n if (!this.memoryManager || !this.entityTools) {\n return;\n }\n\n try {\n this.logger.info('Starting LLM-based entity extraction');\n\n const responseText = this.extractResponseText(response);\n\n const entitiesJson = await this.entityTools.extractEntities.call({\n response: responseText,\n userMessage: originalMessage,\n });\n\n try {\n const entities = JSON.parse(entitiesJson);\n\n for (const entity of entities) {\n if (\n entity &&\n typeof entity === 'object' &&\n 'name' in entity &&\n 'type' in entity &&\n 'id' in entity\n ) {\n this.logger.info(\n `Storing entity: ${entity.name} (${entity.type}) -> ${entity.id}`\n );\n\n const transactionId = this.extractTransactionId(response);\n const idStr = String(entity.id);\n const isHederaId = /^0\\.0\\.[0-9]+$/.test(idStr);\n if (!isHederaId) {\n this.logger.warn('Skipping non-ID entity from extraction', {\n id: idStr,\n name: String(entity.name),\n type: String(entity.type),\n });\n } else {\n this.memoryManager.storeEntityAssociation(\n idStr,\n String(entity.name),\n String(entity.type),\n transactionId\n );\n }\n }\n }\n\n if (entities.length > 0) {\n this.logger.info(\n `Stored ${entities.length} entities via LLM extraction`\n );\n } else {\n this.logger.info('No entities found in response via LLM extraction');\n }\n } catch (parseError) {\n this.logger.error(\n 'Failed to parse extracted entities JSON:',\n parseError\n );\n throw parseError;\n }\n } catch (error) {\n this.logger.error('Entity extraction failed:', error);\n throw error;\n }\n }\n\n /**\n * Extract transaction ID from response if available\n * @param response - Transaction response\n * @returns Transaction ID or undefined\n */\n private extractTransactionId(response: unknown): string | undefined {\n try {\n if (\n typeof response === 'object' &&\n response &&\n 'transactionId' in response\n ) {\n const responseWithTxId = response as { transactionId?: unknown };\n return typeof responseWithTxId.transactionId === 'string'\n ? responseWithTxId.transactionId\n : undefined;\n }\n if (typeof response === 'string') {\n const match = response.match(\n /transaction[\\s\\w]*ID[\\s:\"]*([0-9a-fA-F@\\.\\-]+)/i\n );\n return match ? match[1] : undefined;\n }\n return undefined;\n } catch {\n return undefined;\n }\n }\n\n /**\n * Connect to MCP servers asynchronously\n * @private\n */\n private connectMCP(): void {\n if (!this.agent || !this.options.mcpServers) {\n return;\n }\n\n this.agent\n .connectMCPServers()\n .catch((e) => {\n this.logger.error('Failed to connect MCP servers:', e);\n })\n .then(() => {\n this.logger.info('MCP servers connected successfully');\n });\n }\n\n /**\n * Get MCP connection status for all servers\n * @returns {Map<string, MCPConnectionStatus>} Connection status map\n */\n getMCPConnectionStatus(): Map<string, MCPConnectionStatus> {\n if (this.agent) {\n return this.agent.getMCPConnectionStatus();\n }\n return new Map();\n }\n\n /**\n * Check if a specific MCP server is connected\n * @param {string} serverName - Name of the server to check\n * @returns {boolean} True if connected, false otherwise\n */\n isMCPServerConnected(serverName: string): boolean {\n if (this.agent) {\n const statusMap = this.agent.getMCPConnectionStatus();\n const status = statusMap.get(serverName);\n return status?.connected ?? false;\n }\n return false;\n }\n\n /**\n * Clean up resources\n */\n async cleanup(): Promise<void> {\n try {\n this.logger.info('Cleaning up ConversationalAgent...');\n\n if (this.memoryManager) {\n try {\n this.memoryManager.dispose();\n this.logger.info('Memory manager cleaned up successfully');\n } catch (error) {\n this.logger.warn('Error cleaning up memory manager:', error);\n }\n this.memoryManager = undefined;\n }\n\n if (this.contentStoreManager) {\n await this.contentStoreManager.dispose();\n this.logger.info('ContentStoreManager cleaned up');\n }\n\n this.logger.info('ConversationalAgent cleanup completed');\n } catch (error) {\n this.logger.error('Error during cleanup:', error);\n }\n }\n\n private extractResponseText(response: unknown): string {\n if (typeof response === 'string') {\n return response;\n }\n\n if (response && typeof response === 'object' && 'output' in response) {\n const responseWithOutput = response as { output: unknown };\n return String(responseWithOutput.output);\n }\n\n return JSON.stringify(response);\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAgDA,MAAM,qBAAqB;AAC3B,MAAM,sBAAsB;AAC5B,MAAM,kBAAkB;AACxB,MAAM,2BAAiD;AAuChD,MAAM,uBAAN,MAAM,qBAAoB;AAAA,EAkB/B,YAAY,SAAqC;AAC/C,SAAK,UAAU;AACf,SAAK,eAAe,QAAQ,gBAAgB,IAAI,gBAAA;AAChD,SAAK,cAAc,IAAI,YAAA;AACvB,SAAK,aAAa,IAAI,WAAA;AACtB,SAAK,iBAAiB,IAAI,eAAA;AAC1B,SAAK,aAAa,IAAI,WAAA;AACtB,SAAK,SAAS,IAAI,OAAO;AAAA,MACvB,QAAQ;AAAA,MACR,QAAQ,QAAQ,kBAAkB;AAAA,IAAA,CACnC;AAED,QAAI,KAAK,QAAQ,wBAAwB,OAAO;AAC9C,UAAI,CAAC,QAAQ,cAAc;AACzB,cAAM,IAAI;AAAA,UACR;AAAA,QAAA;AAAA,MAEJ;AAEA,WAAK,gBAAgB,IAAI;AAAA,QACvB,KAAK,QAAQ;AAAA,MAAA;AAEf,WAAK,OAAO,KAAK,2BAA2B;AAE5C,WAAK,cAAc,kBAAkB,QAAQ,cAAc,aAAa;AACxE,WAAK,OAAO,KAAK,6CAA6C;AAAA,IAChE;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,aAA4B;AAChC,UAAM;AAAA,MACJ;AAAA,MACA;AAAA,MACA,UAAU;AAAA,MACV;AAAA,MACA,kBAAkB;AAAA,MAClB,cAAc;AAAA,IAAA,IACZ,KAAK;AAET,SAAK,gBAAgB,WAAW,UAAU;AAE1C,QAAI;AACF,YAAM,eAAe,IAAI;A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cAAc,QAAA;AACnB,eAAK,OAAO,KAAK,wCAAwC;AAAA,QAC3D,SAAS,OAAO;AACd,eAAK,OAAO,KAAK,qCAAqC,KAAK;AAAA,QAC7D;AACA,aAAK,gBAAgB;AAAA,MACvB;AAEA,UAAI,KAAK,qBAAqB;AAC5B,cAAM,KAAK,oBAAoB,QAAA;AAC/B,aAAK,OAAO,KAAK,gCAAgC;AAAA,MACnD;AAEA,WAAK,OAAO,KAAK,uCAAuC;AAAA,IAC1D,SAAS,OAAO;AACd,WAAK,OAAO,MAAM,yBAAyB,KAAK;AAAA,IAClD;AAAA,EACF;AAAA,EAEQ,oBAAoB,UAA2B;AACrD,QAAI,OAAO,aAAa,UAAU;AAChC,aAAO;AAAA,IACT;AAEA,QAAI,YAAY,OAAO,aAAa,YAAY,YAAY,UAAU;AACpE,YAAM,qBAAqB;AAC3B,aAAO,OAAO,mBAAmB,MAAM;AAAA,IACzC;AAEA,WAAO,KAAK,UAAU,QAAQ;AAAA,EAChC;AACF;AAvsBE,qBAAwB,wBACtB;AAFG,IAAM,sBAAN;"}
|
package/dist/esm/index7.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index7.js","sources":["../../src/base-agent.ts"],"sourcesContent":["import type { BaseMessage } from '@langchain/core/messages';\nimport type { StructuredTool } from '@langchain/core/tools';\nimport type { TransactionReceipt } from '@hashgraph/sdk';\nimport {\n HederaAgentKit,\n ServerSigner,\n TokenUsageCallbackHandler,\n TokenUsage,\n BasePlugin,\n} from 'hedera-agent-kit';\nimport type { CostCalculation } from 'hedera-agent-kit';\nimport type { AIProvider, VercelAIProvider, BAMLProvider } from './providers';\nimport { Logger } from '@hashgraphonline/standards-sdk';\nimport type { MCPServerConfig, MCPConnectionStatus } from './mcp/types';\n\nexport interface ToolFilterConfig {\n namespaceWhitelist?: string[];\n toolBlacklist?: string[];\n toolPredicate?: (tool: StructuredTool) => boolean;\n}\n\nexport type ExecutionMode = 'direct' | 'bytes';\nexport type OperationalMode = 'autonomous' | 'returnBytes';\n\nexport interface HederaAgentConfiguration {\n signer: ServerSigner;\n execution?: {\n mode?: ExecutionMode;\n operationalMode?: OperationalMode;\n userAccountId?: string;\n scheduleUserTransactions?: boolean;\n scheduleUserTransactionsInBytesMode?: boolean;\n };\n ai?: {\n provider?: AIProvider;\n llm?: unknown;\n apiKey?: string;\n modelName?: string;\n temperature?: number;\n };\n filtering?: ToolFilterConfig;\n messaging?: {\n systemPreamble?: string;\n systemPostamble?: string;\n conciseMode?: boolean;\n };\n extensions?: {\n plugins?: BasePlugin[];\n mirrorConfig?: Record<string, unknown>;\n modelCapability?: string;\n };\n mcp?: {\n servers?: MCPServerConfig[];\n autoConnect?: boolean;\n };\n debug?: {\n verbose?: boolean;\n silent?: boolean;\n };\n}\n\nexport interface ConversationContext {\n messages: BaseMessage[];\n metadata?: Record<string, unknown>;\n}\n\nexport interface ChatResponse {\n output: string;\n message?: string;\n transactionBytes?: string;\n receipt?: TransactionReceipt | object;\n scheduleId?: string;\n transactionId?: string;\n notes?: string[];\n error?: string;\n intermediateSteps?: unknown;\n rawToolOutput?: unknown;\n tokenUsage?: TokenUsage;\n cost?: CostCalculation;\n metadata?: Record<string, unknown>;\n tool_calls?: Array<{\n id: string;\n name: string;\n args: Record<string, unknown>;\n output?: string;\n }>;\n formMessage?: unknown;\n requiresForm?: boolean;\n [key: string]: unknown;\n}\n\nexport interface UsageStats extends TokenUsage {\n cost: CostCalculation;\n}\n\nexport abstract class BaseAgent {\n protected logger: Logger;\n protected agentKit: HederaAgentKit | undefined;\n protected tools: StructuredTool[] = [];\n protected initialized = false;\n protected tokenTracker: TokenUsageCallbackHandler | undefined;\n\n constructor(protected config: HederaAgentConfiguration) {\n this.logger = new Logger({\n module: 'BaseAgent',\n silent: config.debug?.silent || false,\n });\n }\n\n abstract boot(): Promise<void>;\n abstract chat(\n message: string,\n context?: ConversationContext\n ): Promise<ChatResponse>;\n abstract shutdown(): Promise<void>;\n abstract switchMode(mode: OperationalMode): void;\n abstract getUsageStats(): UsageStats;\n abstract getUsageLog(): UsageStats[];\n abstract clearUsageStats(): void;\n abstract connectMCPServers(): Promise<void>;\n abstract getMCPConnectionStatus(): Map<string, MCPConnectionStatus>;\n\n public getCore(): HederaAgentKit | undefined {\n return this.agentKit;\n }\n\n protected filterTools(tools: StructuredTool[]): StructuredTool[] {\n let filtered = [...tools];\n const filter = this.config.filtering;\n\n if (!filter) return filtered;\n\n if (filter.namespaceWhitelist?.length) {\n filtered = filtered.filter((tool) => {\n const namespace = (tool as StructuredTool & { namespace?: string })\n .namespace;\n return !namespace || filter.namespaceWhitelist!.includes(namespace);\n });\n }\n\n if (filter.toolBlacklist?.length) {\n filtered = filtered.filter(\n (tool) => !filter.toolBlacklist!.includes(tool.name)\n );\n }\n\n if (filter.toolPredicate) {\n filtered = filtered.filter(filter.toolPredicate);\n }\n\n this.logger.debug(`Filtered tools: ${tools.length} → ${filtered.length}`);\n return filtered;\n }\n\n protected buildSystemPrompt(): string {\n const parts: string[] = [];\n const operatorId = this.config.signer.getAccountId().toString();\n const userAccId = this.config.execution?.userAccountId;\n\n if (this.config.messaging?.systemPreamble) {\n parts.push(this.config.messaging.systemPreamble);\n }\n\n parts.push(\n `You are a helpful Hedera assistant. Your primary operator account is ${operatorId}. ` +\n `You have tools to interact with the Hedera Hashgraph. ` +\n `When using any tool, provide all necessary parameters as defined by that tool's schema and description.`\n );\n\n parts.push(\n `\\nMETADATA QUALITY PRINCIPLES: When collecting user input for metadata creation across any tool:` +\n `\\n• Prioritize meaningful, valuable content over technical file information` +\n `\\n• Focus on attributes that add value for end users and collectors` +\n `\\n• Avoid auto-generating meaningless technical attributes as user-facing metadata` +\n `\\n• When fields are missing or inadequate, use forms to collect quality metadata` +\n `\\n• Encourage descriptive names, collectible traits, and storytelling elements`\n );\n\n if (userAccId) {\n parts.push(\n `The user you are assisting has a personal Hedera account ID: ${userAccId}. ` +\n `IMPORTANT: When the user says things like \"I want to send HBAR\" or \"transfer my tokens\", you MUST use ${userAccId} as the sender/from account. ` +\n `For example, if user says \"I want to send 2 HBAR to 0.0.800\", you must set up a transfer where ${userAccId} sends the HBAR, not your operator account.`\n );\n }\n\n const operationalMode =\n this.config.execution?.operationalMode || 'returnBytes';\n if (operationalMode === 'autonomous') {\n parts.push(\n `\\nOPERATIONAL MODE: 'autonomous'. Your goal is to execute transactions directly using your tools. ` +\n `Your account ${operatorId} will be the payer for these transactions. ` +\n `Even if the user's account (${\n userAccId || 'a specified account'\n }) is the actor in the transaction body (e.g., sender of HBAR), ` +\n `you (the agent with operator ${operatorId}) are still executing and paying. For HBAR transfers, ensure the amounts in the 'transfers' array sum to zero (as per tool schema), balancing with your operator account if necessary.`\n );\n } else {\n if (\n this.config.execution?.scheduleUserTransactionsInBytesMode &&\n userAccId\n ) {\n parts.push(\n `\\nOPERATIONAL MODE: 'returnBytes' with scheduled transactions for user actions. ` +\n `When a user asks for a transaction to be prepared (e.g., creating a token, topic, transferring assets for them to sign, etc), ` +\n `you MUST default to creating a Scheduled Transaction using the appropriate tool with the metaOption 'schedule: true'. ` +\n `The user (with account ID ${userAccId}) will be the one to ultimately pay for and (if needed) sign the inner transaction. ` +\n `Your operator account (${operatorId}) will pay for creating the schedule entity itself. ` +\n `You MUST return the ScheduleId and details of the scheduled operation in a structured JSON format with these fields: success, op, schedule_id, description, payer_account_id_scheduled_tx, and scheduled_transaction_details.`\n );\n } else {\n parts.push(\n `\\nOPERATIONAL MODE: 'returnBytes'. Your goal is to provide transaction bytes when possible. ` +\n `When a user asks for a transaction to be prepared (e.g., for them to sign, or for scheduling without the default scheduling flow), ` +\n `you MUST call the appropriate tool. ` +\n `IMPORTANT: Only use metaOption 'returnBytes: true' for tools that explicitly support it (like HBAR transfers, token operations). ` +\n `Many tools (inscriptions, HCS-2, HCS-20, etc.) do NOT support returnBytes and will execute directly - this is expected behavior. ` +\n `For tools without returnBytes support, simply call them with their standard parameters. ` +\n `If you need raw bytes for the user to sign for their own account ${\n userAccId || 'if specified'\n }, ensure the tool constructs the transaction body accordingly when returnBytes IS supported.`\n );\n }\n }\n\n if (this.config.messaging?.conciseMode !== false) {\n parts.push(\n '\\nAlways be concise. If the tool provides a JSON string as its primary output (especially in returnBytes mode), make your accompanying text brief. If the tool does not provide JSON output or an error occurs, your narrative becomes primary; if notes were generated by the tool in such cases, append them to your textual response.'\n );\n }\n\n if (this.config.messaging?.systemPostamble) {\n parts.push(this.config.messaging.systemPostamble);\n }\n\n return parts.join('\\n');\n }\n\n isReady(): boolean {\n return this.initialized;\n }\n}\n\nexport type { AIProvider, VercelAIProvider, BAMLProvider };\n"],"names":[],"mappings":";AA+FO,MAAe,UAAU;AAAA,EAO9B,YAAsB,QAAkC;AAAlC,SAAA,SAAA;AAJtB,SAAU,QAA0B,CAAA;AACpC,SAAU,cAAc;AAItB,SAAK,SAAS,IAAI,OAAO;AAAA,MACvB,QAAQ;AAAA,MACR,QAAQ,OAAO,OAAO,UAAU;AAAA,IAAA,CACjC;AAAA,EACH;AAAA,EAeO,UAAsC;AAC3C,WAAO,KAAK;AAAA,EACd;AAAA,EAEU,YAAY,OAA2C;AAC/D,QAAI,WAAW,CAAC,GAAG,KAAK;AACxB,UAAM,SAAS,KAAK,OAAO;AAE3B,QAAI,CAAC,OAAQ,QAAO;AAEpB,QAAI,OAAO,oBAAoB,QAAQ;AACrC,iBAAW,SAAS,OAAO,CAAC,SAAS;AACnC,cAAM,YAAa,KAChB;AACH,eAAO,CAAC,aAAa,OAAO,mBAAoB,SAAS,SAAS;AAAA,MACpE,CAAC;AAAA,IACH;AAEA,QAAI,OAAO,eAAe,QAAQ;AAChC,iBAAW,SAAS;AAAA,QAClB,CAAC,SAAS,CAAC,OAAO,cAAe,SAAS,KAAK,IAAI;AAAA,MAAA;AAAA,IAEvD;AAEA,QAAI,OAAO,eAAe;AACxB,iBAAW,SAAS,OAAO,OAAO,aAAa;AAAA,IACjD;AAEA,SAAK,OAAO,MAAM,mBAAmB,MAAM,MAAM,MAAM,SAA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Content":["import type { BaseMessage } from '@langchain/core/messages';\nimport type { StructuredTool } from '@langchain/core/tools';\nimport type { TransactionReceipt } from '@hashgraph/sdk';\nimport {\n HederaAgentKit,\n ServerSigner,\n TokenUsageCallbackHandler,\n TokenUsage,\n BasePlugin,\n} from 'hedera-agent-kit';\nimport type { CostCalculation } from 'hedera-agent-kit';\nimport type { AIProvider, VercelAIProvider, BAMLProvider } from './providers';\nimport { Logger } from '@hashgraphonline/standards-sdk';\nimport type { MCPServerConfig, MCPConnectionStatus } from './mcp/types';\nimport type { FormSubmission } from './forms/types';\n\nexport interface ToolFilterConfig {\n namespaceWhitelist?: string[];\n toolBlacklist?: string[];\n toolPredicate?: (tool: StructuredTool) => boolean;\n}\n\nexport type ExecutionMode = 'direct' | 'bytes';\nexport type OperationalMode = 'autonomous' | 'returnBytes';\n\nexport interface HederaAgentConfiguration {\n signer: ServerSigner;\n execution?: {\n mode?: ExecutionMode;\n operationalMode?: OperationalMode;\n userAccountId?: string;\n scheduleUserTransactions?: boolean;\n scheduleUserTransactionsInBytesMode?: boolean;\n };\n ai?: {\n provider?: AIProvider;\n llm?: unknown;\n apiKey?: string;\n modelName?: string;\n temperature?: number;\n };\n filtering?: ToolFilterConfig;\n messaging?: {\n systemPreamble?: string;\n systemPostamble?: string;\n conciseMode?: boolean;\n };\n extensions?: {\n plugins?: BasePlugin[];\n mirrorConfig?: Record<string, unknown>;\n modelCapability?: string;\n };\n mcp?: {\n servers?: MCPServerConfig[];\n autoConnect?: boolean;\n };\n debug?: {\n verbose?: boolean;\n silent?: boolean;\n };\n}\n\nexport interface ConversationContext {\n messages: BaseMessage[];\n metadata?: Record<string, unknown>;\n}\n\nexport interface ChatResponse {\n output: string;\n message?: string;\n transactionBytes?: string;\n receipt?: TransactionReceipt | object;\n scheduleId?: string;\n transactionId?: string;\n notes?: string[];\n error?: string;\n intermediateSteps?: unknown;\n rawToolOutput?: unknown;\n tokenUsage?: TokenUsage;\n cost?: CostCalculation;\n metadata?: Record<string, unknown>;\n tool_calls?: Array<{\n id: string;\n name: string;\n args: Record<string, unknown>;\n output?: string;\n }>;\n formMessage?: unknown;\n requiresForm?: boolean;\n [key: string]: unknown;\n}\n\nexport interface UsageStats extends TokenUsage {\n cost: CostCalculation;\n}\n\nexport abstract class BaseAgent {\n protected logger: Logger;\n protected agentKit: HederaAgentKit | undefined;\n protected tools: StructuredTool[] = [];\n protected initialized = false;\n protected tokenTracker: TokenUsageCallbackHandler | undefined;\n\n constructor(protected config: HederaAgentConfiguration) {\n this.logger = new Logger({\n module: 'BaseAgent',\n silent: config.debug?.silent || false,\n });\n }\n\n abstract boot(): Promise<void>;\n abstract chat(\n message: string,\n context?: ConversationContext\n ): Promise<ChatResponse>;\n abstract processFormSubmission(\n submission: FormSubmission\n ): Promise<ChatResponse>;\n abstract shutdown(): Promise<void>;\n abstract switchMode(mode: OperationalMode): void;\n abstract getUsageStats(): UsageStats;\n abstract getUsageLog(): UsageStats[];\n abstract clearUsageStats(): void;\n abstract connectMCPServers(): Promise<void>;\n abstract getMCPConnectionStatus(): Map<string, MCPConnectionStatus>;\n\n public getCore(): HederaAgentKit | undefined {\n return this.agentKit;\n }\n\n protected filterTools(tools: StructuredTool[]): StructuredTool[] {\n let filtered = [...tools];\n const filter = this.config.filtering;\n\n if (!filter) return filtered;\n\n if (filter.namespaceWhitelist?.length) {\n filtered = filtered.filter((tool) => {\n const namespace = (tool as StructuredTool & { namespace?: string })\n .namespace;\n return !namespace || filter.namespaceWhitelist!.includes(namespace);\n });\n }\n\n if (filter.toolBlacklist?.length) {\n filtered = filtered.filter(\n (tool) => !filter.toolBlacklist!.includes(tool.name)\n );\n }\n\n if (filter.toolPredicate) {\n filtered = filtered.filter(filter.toolPredicate);\n }\n\n this.logger.debug(`Filtered tools: ${tools.length} → ${filtered.length}`);\n return filtered;\n }\n\n protected buildSystemPrompt(): string {\n const parts: string[] = [];\n const operatorId = this.config.signer.getAccountId().toString();\n const userAccId = this.config.execution?.userAccountId;\n\n if (this.config.messaging?.systemPreamble) {\n parts.push(this.config.messaging.systemPreamble);\n }\n\n parts.push(\n `You are a helpful Hedera assistant. Your primary operator account is ${operatorId}. ` +\n `You have tools to interact with the Hedera Hashgraph. ` +\n `When using any tool, provide all necessary parameters as defined by that tool's schema and description.`\n );\n\n parts.push(\n `\\nMETADATA QUALITY PRINCIPLES: When collecting user input for metadata creation across any tool:` +\n `\\n• Prioritize meaningful, valuable content over technical file information` +\n `\\n• Focus on attributes that add value for end users and collectors` +\n `\\n• Avoid auto-generating meaningless technical attributes as user-facing metadata` +\n `\\n• When fields are missing or inadequate, use forms to collect quality metadata` +\n `\\n• Encourage descriptive names, collectible traits, and storytelling elements`\n );\n\n if (userAccId) {\n parts.push(\n `The user you are assisting has a personal Hedera account ID: ${userAccId}. ` +\n `IMPORTANT: When the user says things like \"I want to send HBAR\" or \"transfer my tokens\", you MUST use ${userAccId} as the sender/from account. ` +\n `For example, if user says \"I want to send 2 HBAR to 0.0.800\", you must set up a transfer where ${userAccId} sends the HBAR, not your operator account.`\n );\n }\n\n const operationalMode =\n this.config.execution?.operationalMode || 'returnBytes';\n if (operationalMode === 'autonomous') {\n parts.push(\n `\\nOPERATIONAL MODE: 'autonomous'. Your goal is to execute transactions directly using your tools. ` +\n `Your account ${operatorId} will be the payer for these transactions. ` +\n `Even if the user's account (${\n userAccId || 'a specified account'\n }) is the actor in the transaction body (e.g., sender of HBAR), ` +\n `you (the agent with operator ${operatorId}) are still executing and paying. For HBAR transfers, ensure the amounts in the 'transfers' array sum to zero (as per tool schema), balancing with your operator account if necessary.`\n );\n } else {\n if (\n this.config.execution?.scheduleUserTransactionsInBytesMode &&\n userAccId\n ) {\n parts.push(\n `\\nOPERATIONAL MODE: 'returnBytes' with scheduled transactions for user actions. ` +\n `When a user asks for a transaction to be prepared (e.g., creating a token, topic, transferring assets for them to sign, etc), ` +\n `you MUST default to creating a Scheduled Transaction using the appropriate tool with the metaOption 'schedule: true'. ` +\n `The user (with account ID ${userAccId}) will be the one to ultimately pay for and (if needed) sign the inner transaction. ` +\n `Your operator account (${operatorId}) will pay for creating the schedule entity itself. ` +\n `You MUST return the ScheduleId and details of the scheduled operation in a structured JSON format with these fields: success, op, schedule_id, description, payer_account_id_scheduled_tx, and scheduled_transaction_details.`\n );\n } else {\n parts.push(\n `\\nOPERATIONAL MODE: 'returnBytes'. Your goal is to provide transaction bytes when possible. ` +\n `When a user asks for a transaction to be prepared (e.g., for them to sign, or for scheduling without the default scheduling flow), ` +\n `you MUST call the appropriate tool. ` +\n `IMPORTANT: Only use metaOption 'returnBytes: true' for tools that explicitly support it (like HBAR transfers, token operations). ` +\n `Many tools (inscriptions, HCS-2, HCS-20, etc.) do NOT support returnBytes and will execute directly - this is expected behavior. ` +\n `For tools without returnBytes support, simply call them with their standard parameters. ` +\n `If you need raw bytes for the user to sign for their own account ${\n userAccId || 'if specified'\n }, ensure the tool constructs the transaction body accordingly when returnBytes IS supported.`\n );\n }\n }\n\n if (this.config.messaging?.conciseMode !== false) {\n parts.push(\n '\\nAlways be concise. If the tool provides a JSON string as its primary output (especially in returnBytes mode), make your accompanying text brief. If the tool does not provide JSON output or an error occurs, your narrative becomes primary; if notes were generated by the tool in such cases, append them to your textual response.'\n );\n }\n\n if (this.config.messaging?.systemPostamble) {\n parts.push(this.config.messaging.systemPostamble);\n }\n\n return parts.join('\\n');\n }\n\n isReady(): boolean {\n return this.initialized;\n }\n}\n\nexport type { AIProvider, VercelAIProvider, BAMLProvider };\n"],"names":[],"mappings":";AAgGO,MAAe,UAAU;AAAA,EAO9B,YAAsB,QAAkC;AAAlC,SAAA,SAAA;AAJtB,SAAU,QAA0B,CAAA;AACpC,SAAU,cAAc;AAItB,SAAK,SAAS,IAAI,OAAO;AAAA,MACvB,QAAQ;AAAA,MACR,QAAQ,OAAO,OAAO,UAAU;AAAA,IAAA,CACjC;AAAA,EACH;AAAA,EAkBO,UAAsC;AAC3C,WAAO,KAAK;AAAA,EACd;AAAA,EAEU,YAAY,OAA2C;AA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AO,WAAW,uCACvB,WACA;AACA,cAAM;AAAA,UACJ;AAAA,8VAG+B,SAAS,8GACZ,UAAU;AAAA,QAAA;AAAA,MAG1C,OAAO;AACL,cAAM;AAAA,UACJ;AAAA,8pBAOI,aAAa,cACf;AAAA,QAAA;AAAA,MAEN;AAAA,IACF;AAEA,QAAI,KAAK,OAAO,WAAW,gBAAgB,OAAO;AAChD,YAAM;AAAA,QACJ;AAAA,MAAA;AAAA,IAEJ;AAEA,QAAI,KAAK,OAAO,WAAW,iBAAiB;AAC1C,YAAM,KAAK,KAAK,OAAO,UAAU,eAAe;AAAA,IAClD;AAEA,WAAO,MAAM,KAAK,IAAI;AAAA,EACxB;AAAA,EAEA,UAAmB;AACjB,WAAO,KAAK;AAAA,EACd;AACF;"}
|
|
@@ -5,6 +5,7 @@ import { HederaAgentKit, ServerSigner, TokenUsageCallbackHandler, TokenUsage, Ba
|
|
|
5
5
|
import { AIProvider, VercelAIProvider, BAMLProvider } from './providers';
|
|
6
6
|
import { Logger } from '@hashgraphonline/standards-sdk';
|
|
7
7
|
import { MCPServerConfig, MCPConnectionStatus } from './mcp/types';
|
|
8
|
+
import { FormSubmission } from './forms/types';
|
|
8
9
|
|
|
9
10
|
export interface ToolFilterConfig {
|
|
10
11
|
namespaceWhitelist?: string[];
|
|
@@ -90,6 +91,7 @@ export declare abstract class BaseAgent {
|
|
|
90
91
|
constructor(config: HederaAgentConfiguration);
|
|
91
92
|
abstract boot(): Promise<void>;
|
|
92
93
|
abstract chat(message: string, context?: ConversationContext): Promise<ChatResponse>;
|
|
94
|
+
abstract processFormSubmission(submission: FormSubmission): Promise<ChatResponse>;
|
|
93
95
|
abstract shutdown(): Promise<void>;
|
|
94
96
|
abstract switchMode(mode: OperationalMode): void;
|
|
95
97
|
abstract getUsageStats(): UsageStats;
|
|
@@ -5,15 +5,18 @@ import { ChainValues } from '@langchain/core/utils/types';
|
|
|
5
5
|
import { CallbackManagerForChainRun } from '@langchain/core/callbacks/manager';
|
|
6
6
|
import { RunnableConfig } from '@langchain/core/runnables';
|
|
7
7
|
|
|
8
|
+
interface ToolWithOriginal {
|
|
9
|
+
originalTool?: {
|
|
10
|
+
call?: (args: Record<string, unknown>) => Promise<string>;
|
|
11
|
+
};
|
|
12
|
+
}
|
|
8
13
|
interface PendingFormData {
|
|
9
14
|
toolName: string;
|
|
10
15
|
originalInput: unknown;
|
|
11
16
|
originalToolInput?: unknown;
|
|
12
17
|
schema: unknown;
|
|
13
18
|
toolRef?: ToolInterface | undefined;
|
|
14
|
-
originalToolRef?:
|
|
15
|
-
call?: (args: Record<string, unknown>) => Promise<string>;
|
|
16
|
-
} | undefined;
|
|
19
|
+
originalToolRef?: ToolWithOriginal['originalTool'];
|
|
17
20
|
}
|
|
18
21
|
/**
|
|
19
22
|
* Parameter preprocessing callback interface
|