@hashgraphonline/conversational-agent 0.1.220 → 0.1.221

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.
@@ -1,5 +1,5 @@
1
1
  import { ReferenceIdGenerator } from "./index22.js";
2
- import { DEFAULT_CONTENT_REFERENCE_CONFIG, ContentReferenceError } from "./index42.js";
2
+ import { DEFAULT_CONTENT_REFERENCE_CONFIG, ContentReferenceError } from "./index39.js";
3
3
  const _ContentStorage = class _ContentStorage {
4
4
  constructor(maxStorage = _ContentStorage.DEFAULT_MAX_STORAGE, referenceConfig) {
5
5
  this.messages = [];
@@ -8,11 +8,11 @@ import { MCPClientManager } from "./index15.js";
8
8
  import { convertMCPToolToLangChain } from "./index17.js";
9
9
  import { SmartMemoryManager } from "./index18.js";
10
10
  import { ResponseFormatter } from "./index33.js";
11
- import { ERROR_MESSAGES } from "./index39.js";
11
+ import { ERROR_MESSAGES } from "./index40.js";
12
12
  import "./index37.js";
13
13
  import { SystemMessage, AIMessage, HumanMessage } from "@langchain/core/messages";
14
- import { ToolRegistry } from "./index40.js";
15
- import { ExecutionPipeline } from "./index41.js";
14
+ import { ToolRegistry } from "./index41.js";
15
+ import { ExecutionPipeline } from "./index42.js";
16
16
  import { FormEngine } from "./index11.js";
17
17
  function hasHashLinkBlock(metadata) {
18
18
  if (!metadata || typeof metadata !== "object") {
@@ -1,8 +1,30 @@
1
- const ERROR_MESSAGES = {
2
- TOO_MANY_REQUESTS: "Too many requests. Please wait a moment and try again.",
3
- RATE_LIMITED: "I'm receiving too many requests right now. Please wait a moment and try again."
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
+ }
4
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
+ }
5
26
  export {
6
- ERROR_MESSAGES
27
+ ContentReferenceError,
28
+ DEFAULT_CONTENT_REFERENCE_CONFIG
7
29
  };
8
30
  //# sourceMappingURL=index39.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index39.js","sources":["../../src/constants/messages.ts"],"sourcesContent":["/**\n * Common error messages and user feedback strings\n */\nexport const ERROR_MESSAGES = {\n TOO_MANY_REQUESTS: 'Too many requests. Please wait a moment and try again.',\n RATE_LIMITED: \"I'm receiving too many requests right now. Please wait a moment and try again.\",\n SYSTEM_ERROR: 'System error occurred',\n INVALID_INPUT: 'Invalid input provided',\n NETWORK_ERROR: 'Network error occurred',\n} as const;\n\n/**\n * Common success and status messages\n */\nexport const STATUS_MESSAGES = {\n OPERATION_SUCCESSFUL: 'Operation completed successfully',\n PROCESSING: 'Processing your request...',\n READY: 'Ready to process requests',\n INITIALIZING: 'Initializing...',\n} as const;"],"names":[],"mappings":"AAGO,MAAM,iBAAiB;AAAA,EAC5B,mBAAmB;AAAA,EACnB,cAAc;AAIhB;"}
1
+ {"version":3,"file":"index39.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,258 +1,8 @@
1
- import { z } from "zod";
2
- import { Logger } from "@hashgraphonline/standards-sdk";
3
- import { wrapToolWithFormValidation } from "./index30.js";
4
- import { FormGenerator } from "./index10.js";
5
- import { isFormValidatable } from "@hashgraphonline/standards-agent-kit";
6
- class ToolRegistry {
7
- constructor(logger) {
8
- this.tools = /* @__PURE__ */ new Map();
9
- this.formGenerator = new FormGenerator();
10
- this.logger = logger || new Logger({ module: "ToolRegistry" });
11
- }
12
- /**
13
- * Register a tool with the registry
14
- */
15
- registerTool(tool, options = {}) {
16
- const capabilities = this.analyzeToolCapabilities(tool);
17
- const metadata = {
18
- name: tool.name,
19
- version: "1.0.0",
20
- category: options.metadata?.category || "core",
21
- description: tool.description,
22
- capabilities,
23
- dependencies: [],
24
- schema: tool.schema,
25
- ...options.metadata
26
- };
27
- try {
28
- if (!metadata.entityResolutionPreferences) {
29
- const schemaRecord = tool.schema;
30
- const rawPrefs = schemaRecord && typeof schemaRecord === "object" && schemaRecord["_entityResolutionPreferences"];
31
- if (rawPrefs && typeof rawPrefs === "object") {
32
- metadata.entityResolutionPreferences = rawPrefs;
33
- }
34
- }
35
- } catch {
36
- }
37
- try {
38
- const schemaRecord = tool.schema;
39
- const schemaDef = schemaRecord && schemaRecord._def;
40
- if (schemaDef?.typeName === "ZodObject") {
41
- const shape = typeof schemaDef.shape === "function" ? schemaDef.shape?.() || {} : schemaDef.shape || {};
42
- const metadataField = shape["metadata"];
43
- const isStringArray = !!metadataField && metadataField._def?.typeName === "ZodArray" && metadataField._def?.type?._def?.typeName === "ZodString";
44
- if (isStringArray && typeof tool.description === "string") {
45
- if (!metadata.entityResolutionPreferences) {
46
- metadata.entityResolutionPreferences = {
47
- inscription: "hrl"
48
- };
49
- }
50
- const note = " NOTE: When referencing inscriptions or media, provide canonical Hashlink Resource Locators (e.g., hcs://<standard>/<topicId>) rather than external URLs or embedded JSON.";
51
- if (!tool.description.includes("Hashlink Resource Locators")) {
52
- tool.description = `${tool.description}${note}`;
53
- }
54
- }
55
- }
56
- } catch {
57
- }
58
- let finalTool = tool;
59
- let wrapper;
60
- if (this.shouldWrapTool(tool, capabilities, options)) {
61
- wrapper = wrapToolWithFormValidation(
62
- tool,
63
- this.formGenerator,
64
- {
65
- requireAllFields: false,
66
- skipFields: ["metaOptions"],
67
- ...options.wrapperConfig
68
- }
69
- );
70
- finalTool = wrapper;
71
- }
72
- try {
73
- if (metadata.entityResolutionPreferences) {
74
- finalTool["entityResolutionPreferences"] = metadata.entityResolutionPreferences;
75
- }
76
- } catch {
77
- }
78
- const entry = {
79
- tool: finalTool,
80
- metadata,
81
- wrapper,
82
- originalTool: tool
83
- };
84
- this.tools.set(tool.name, entry);
85
- }
86
- /**
87
- * Get a tool by name
88
- */
89
- getTool(name) {
90
- return this.tools.get(name) || null;
91
- }
92
- /**
93
- * Get tools by capability
94
- */
95
- getToolsByCapability(capability, value) {
96
- const results = [];
97
- for (const entry of this.tools.values()) {
98
- if (value !== void 0) {
99
- if (entry.metadata.capabilities[capability] === value) {
100
- results.push(entry);
101
- }
102
- } else if (entry.metadata.capabilities[capability]) {
103
- results.push(entry);
104
- }
105
- }
106
- return results;
107
- }
108
- /**
109
- * Get tools by query
110
- */
111
- getToolsByQuery(query) {
112
- const results = [];
113
- for (const entry of this.tools.values()) {
114
- let matches = true;
115
- if (query.name && entry.metadata.name !== query.name) {
116
- matches = false;
117
- }
118
- if (query.category && entry.metadata.category !== query.category) {
119
- matches = false;
120
- }
121
- if (query.capabilities) {
122
- for (const [key, value] of Object.entries(query.capabilities)) {
123
- if (entry.metadata.capabilities[key] !== value) {
124
- matches = false;
125
- break;
126
- }
127
- }
128
- }
129
- if (matches) {
130
- results.push(entry);
131
- }
132
- }
133
- return results;
134
- }
135
- /**
136
- * Get all registered tools
137
- */
138
- getAllTools() {
139
- return Array.from(this.tools.values()).map((entry) => entry.tool);
140
- }
141
- /**
142
- * Get all registry entries
143
- */
144
- getAllRegistryEntries() {
145
- return Array.from(this.tools.values());
146
- }
147
- /**
148
- * Get all tool names
149
- */
150
- getToolNames() {
151
- return Array.from(this.tools.keys());
152
- }
153
- /**
154
- * Check if a tool is registered
155
- */
156
- hasTool(name) {
157
- return this.tools.has(name);
158
- }
159
- /**
160
- * Unregister a tool
161
- */
162
- unregisterTool(name) {
163
- return this.tools.delete(name);
164
- }
165
- /**
166
- * Clear all tools
167
- */
168
- clear() {
169
- this.tools.clear();
170
- }
171
- /**
172
- * Analyze tool capabilities
173
- */
174
- analyzeToolCapabilities(tool) {
175
- const implementsFormValidatable = isFormValidatable(tool);
176
- const hasRenderConfig = this.hasRenderConfig(tool);
177
- const isZodObjectLike = this.isZodObjectLike(tool.schema);
178
- const supportsFormValidation = implementsFormValidatable || hasRenderConfig;
179
- const requiresWrapper = supportsFormValidation && isZodObjectLike;
180
- let priority = "medium";
181
- let category = "core";
182
- if (supportsFormValidation && requiresWrapper) {
183
- priority = "critical";
184
- } else if (supportsFormValidation) {
185
- priority = "high";
186
- } else if (tool.description?.toLowerCase().includes("query") || tool.description?.toLowerCase().includes("search")) {
187
- priority = "low";
188
- }
189
- const toolAsAny = tool;
190
- if (tool.constructor.name.includes("MCP") || toolAsAny.isMCPTool) {
191
- category = "mcp";
192
- } else if (toolAsAny.isExtension || tool.constructor.name.includes("Extension")) {
193
- category = "extension";
194
- }
195
- return {
196
- supportsFormValidation,
197
- requiresWrapper,
198
- priority,
199
- category
200
- };
201
- }
202
- /**
203
- * Check if tool has render configuration
204
- */
205
- hasRenderConfig(tool) {
206
- const schema = tool.schema;
207
- return !!(schema && schema._renderConfig);
208
- }
209
- /**
210
- * Determine if tool should be wrapped
211
- */
212
- shouldWrapTool(tool, capabilities, options) {
213
- if (options.skipWrapper) {
214
- return false;
215
- }
216
- if (options.forceWrapper) {
217
- return true;
218
- }
219
- return capabilities.requiresWrapper;
220
- }
221
- /**
222
- * Check if schema is ZodObject-like
223
- */
224
- isZodObjectLike(schema) {
225
- if (!schema || typeof schema !== "object") {
226
- return false;
227
- }
228
- const schemaRecord = schema;
229
- const schemaDef = schemaRecord._def;
230
- return schema instanceof z.ZodObject || schemaDef?.typeName === "ZodObject" || "shape" in schemaRecord && typeof schemaRecord.shape === "object";
231
- }
232
- /**
233
- * Get statistics about the registry
234
- */
235
- getStatistics() {
236
- const stats = {
237
- totalTools: this.tools.size,
238
- wrappedTools: 0,
239
- unwrappedTools: 0,
240
- categoryCounts: { core: 0, extension: 0, mcp: 0 },
241
- priorityCounts: { low: 0, medium: 0, high: 0, critical: 0 }
242
- };
243
- for (const entry of this.tools.values()) {
244
- if (entry.wrapper) {
245
- stats.wrappedTools++;
246
- } else {
247
- stats.unwrappedTools++;
248
- }
249
- stats.categoryCounts[entry.metadata.category]++;
250
- stats.priorityCounts[entry.metadata.capabilities.priority]++;
251
- }
252
- return stats;
253
- }
254
- }
1
+ const ERROR_MESSAGES = {
2
+ TOO_MANY_REQUESTS: "Too many requests. Please wait a moment and try again.",
3
+ RATE_LIMITED: "I'm receiving too many requests right now. Please wait a moment and try again."
4
+ };
255
5
  export {
256
- ToolRegistry
6
+ ERROR_MESSAGES
257
7
  };
258
8
  //# sourceMappingURL=index40.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index40.js","sources":["../../src/core/tool-registry.ts"],"sourcesContent":["import { StructuredTool } from '@langchain/core/tools';\nimport { z } from 'zod';\nimport { Logger } from '@hashgraphonline/standards-sdk';\nimport {\n FormValidatingToolWrapper,\n wrapToolWithFormValidation,\n} from '../langchain/form-validating-tool-wrapper';\nimport { FormGenerator } from '../forms/form-generator';\nimport { isFormValidatable } from '@hashgraphonline/standards-agent-kit';\n\n/**\n * Tool capabilities configuration for registry entries\n */\nexport interface ToolCapabilities {\n supportsFormValidation: boolean;\n requiresWrapper: boolean;\n priority: 'low' | 'medium' | 'high' | 'critical';\n category: 'core' | 'extension' | 'mcp';\n}\n\n/**\n * Entity resolution format preferences for tools\n */\nexport interface EntityResolutionPreferences {\n inscription?: 'hrl' | 'topicId' | 'metadata' | 'any';\n token?: 'tokenId' | 'address' | 'symbol' | 'any';\n nft?: 'serialNumber' | 'metadata' | 'hrl' | 'any';\n account?: 'accountId' | 'alias' | 'evmAddress' | 'any';\n}\n\n/**\n * Tool metadata for comprehensive tool information\n */\nexport interface ToolMetadata {\n name: string;\n version: string;\n category: ToolCapabilities['category'];\n description: string;\n capabilities: ToolCapabilities;\n dependencies: string[];\n schema: unknown;\n entityResolutionPreferences?: EntityResolutionPreferences;\n}\n\n/**\n * Registry entry containing tool instance and metadata\n */\nexport interface ToolRegistryEntry {\n tool: StructuredTool;\n metadata: ToolMetadata;\n wrapper?: FormValidatingToolWrapper<z.ZodObject<z.ZodRawShape>> | undefined;\n originalTool: StructuredTool;\n}\n\n/**\n * Options for tool registration\n */\nexport interface ToolRegistrationOptions {\n forceWrapper?: boolean;\n skipWrapper?: boolean;\n wrapperConfig?: {\n requireAllFields?: boolean;\n skipFields?: string[];\n };\n metadata?: Partial<ToolMetadata>;\n}\n\n/**\n * Query interface for finding tools\n */\nexport interface ToolQuery {\n name?: string;\n category?: ToolMetadata['category'];\n capabilities?: Partial<ToolCapabilities>;\n}\n\n/**\n * Centralized tool registry for managing tool lifecycle\n */\nexport class ToolRegistry {\n private tools = new Map<string, ToolRegistryEntry>();\n private formGenerator: FormGenerator;\n private logger: Logger;\n\n constructor(logger?: Logger) {\n this.formGenerator = new FormGenerator();\n this.logger = logger || new Logger({ module: 'ToolRegistry' });\n }\n\n /**\n * Register a tool with the registry\n */\n registerTool(\n tool: StructuredTool,\n options: ToolRegistrationOptions = {}\n ): void {\n const capabilities = this.analyzeToolCapabilities(tool);\n const metadata: ToolMetadata = {\n name: tool.name,\n version: '1.0.0',\n category: options.metadata?.category || 'core',\n description: tool.description,\n capabilities,\n dependencies: [],\n schema: tool.schema,\n ...options.metadata,\n };\n\n try {\n if (!metadata.entityResolutionPreferences) {\n const schemaRecord = tool.schema as unknown as Record<string, unknown>;\n const rawPrefs =\n schemaRecord &&\n typeof schemaRecord === 'object' &&\n (schemaRecord as Record<string, unknown>)[\n '_entityResolutionPreferences'\n ];\n if (rawPrefs && typeof rawPrefs === 'object') {\n metadata.entityResolutionPreferences = rawPrefs as unknown as EntityResolutionPreferences;\n }\n }\n } catch {\n }\n\n try {\n const schemaRecord = tool.schema as unknown as Record<string, unknown>;\n const schemaDef = (schemaRecord && (schemaRecord as Record<string, unknown>)._def) as\n | { typeName?: string; shape?: unknown }\n | undefined;\n if (schemaDef?.typeName === 'ZodObject') {\n const shape: Record<string, unknown> =\n typeof (schemaDef as { shape?: () => Record<string, unknown> }).shape === 'function'\n ? ((schemaDef as { shape: () => Record<string, unknown> }).shape?.() || {})\n : ((schemaDef as { shape?: Record<string, unknown> }).shape || {});\n\n const metadataField = shape['metadata'] as\n | { _def?: { typeName?: string; type?: { _def?: { typeName?: string } } } }\n | undefined;\n const isStringArray =\n !!metadataField &&\n metadataField._def?.typeName === 'ZodArray' &&\n metadataField._def?.type?._def?.typeName === 'ZodString';\n\n if (isStringArray && typeof tool.description === 'string') {\n if (!metadata.entityResolutionPreferences) {\n metadata.entityResolutionPreferences = {\n inscription: 'hrl',\n } as EntityResolutionPreferences;\n }\n const note =\n ' NOTE: When referencing inscriptions or media, provide canonical Hashlink Resource Locators (e.g., hcs://<standard>/<topicId>) rather than external URLs or embedded JSON.';\n if (!tool.description.includes('Hashlink Resource Locators')) {\n (tool as unknown as { description: string }).description = `${tool.description}${note}`;\n }\n }\n }\n } catch {}\n\n let finalTool: StructuredTool = tool;\n let wrapper:\n | FormValidatingToolWrapper<z.ZodObject<z.ZodRawShape>>\n | undefined;\n\n if (this.shouldWrapTool(tool, capabilities, options)) {\n wrapper = wrapToolWithFormValidation(\n tool as StructuredTool<z.ZodObject<z.ZodRawShape>>,\n this.formGenerator,\n {\n requireAllFields: false,\n skipFields: ['metaOptions'],\n ...options.wrapperConfig,\n }\n ) as FormValidatingToolWrapper<z.ZodObject<z.ZodRawShape>>;\n finalTool = wrapper as StructuredTool;\n }\n\n try {\n if (metadata.entityResolutionPreferences) {\n (finalTool as unknown as Record<string, unknown>)[\n 'entityResolutionPreferences'\n ] = metadata.entityResolutionPreferences;\n }\n } catch {\n }\n\n const entry: ToolRegistryEntry = {\n tool: finalTool,\n metadata,\n wrapper,\n originalTool: tool,\n };\n\n this.tools.set(tool.name, entry);\n }\n\n /**\n * Get a tool by name\n */\n getTool(name: string): ToolRegistryEntry | null {\n return this.tools.get(name) || null;\n }\n\n /**\n * Get tools by capability\n */\n getToolsByCapability(\n capability: keyof ToolCapabilities,\n value?: unknown\n ): ToolRegistryEntry[] {\n const results: ToolRegistryEntry[] = [];\n\n for (const entry of this.tools.values()) {\n if (value !== undefined) {\n if (entry.metadata.capabilities[capability] === value) {\n results.push(entry);\n }\n } else if (entry.metadata.capabilities[capability]) {\n results.push(entry);\n }\n }\n\n return results;\n }\n\n /**\n * Get tools by query\n */\n getToolsByQuery(query: ToolQuery): ToolRegistryEntry[] {\n const results: ToolRegistryEntry[] = [];\n\n for (const entry of this.tools.values()) {\n let matches = true;\n\n if (query.name && entry.metadata.name !== query.name) {\n matches = false;\n }\n\n if (query.category && entry.metadata.category !== query.category) {\n matches = false;\n }\n\n if (query.capabilities) {\n for (const [key, value] of Object.entries(query.capabilities)) {\n if (\n entry.metadata.capabilities[key as keyof ToolCapabilities] !== value\n ) {\n matches = false;\n break;\n }\n }\n }\n\n if (matches) {\n results.push(entry);\n }\n }\n\n return results;\n }\n\n /**\n * Get all registered tools\n */\n getAllTools(): StructuredTool[] {\n return Array.from(this.tools.values()).map((entry) => entry.tool);\n }\n\n /**\n * Get all registry entries\n */\n getAllRegistryEntries(): ToolRegistryEntry[] {\n return Array.from(this.tools.values());\n }\n\n /**\n * Get all tool names\n */\n getToolNames(): string[] {\n return Array.from(this.tools.keys());\n }\n\n /**\n * Check if a tool is registered\n */\n hasTool(name: string): boolean {\n return this.tools.has(name);\n }\n\n /**\n * Unregister a tool\n */\n unregisterTool(name: string): boolean {\n return this.tools.delete(name);\n }\n\n /**\n * Clear all tools\n */\n clear(): void {\n this.tools.clear();\n }\n\n /**\n * Analyze tool capabilities\n */\n private analyzeToolCapabilities(tool: StructuredTool): ToolCapabilities {\n const implementsFormValidatable = isFormValidatable(tool);\n const hasRenderConfig = this.hasRenderConfig(tool);\n const isZodObjectLike = this.isZodObjectLike(tool.schema);\n\n const supportsFormValidation = implementsFormValidatable || hasRenderConfig;\n const requiresWrapper = supportsFormValidation && isZodObjectLike;\n\n let priority: ToolCapabilities['priority'] = 'medium';\n let category: ToolCapabilities['category'] = 'core';\n\n if (supportsFormValidation && requiresWrapper) {\n priority = 'critical';\n } else if (supportsFormValidation) {\n priority = 'high';\n } else if (\n tool.description?.toLowerCase().includes('query') ||\n tool.description?.toLowerCase().includes('search')\n ) {\n priority = 'low';\n }\n\n const toolAsAny = tool as unknown as Record<string, unknown>;\n if (tool.constructor.name.includes('MCP') || toolAsAny.isMCPTool) {\n category = 'mcp';\n } else if (\n toolAsAny.isExtension ||\n tool.constructor.name.includes('Extension')\n ) {\n category = 'extension';\n }\n\n return {\n supportsFormValidation,\n requiresWrapper,\n priority,\n category,\n };\n }\n\n /**\n * Check if tool has render configuration\n */\n private hasRenderConfig(tool: StructuredTool): boolean {\n const schema = tool.schema as Record<string, unknown>;\n return !!(schema && schema._renderConfig);\n }\n\n /**\n * Determine if tool should be wrapped\n */\n private shouldWrapTool(\n tool: StructuredTool,\n capabilities: ToolCapabilities,\n options: ToolRegistrationOptions\n ): boolean {\n if (options.skipWrapper) {\n return false;\n }\n\n if (options.forceWrapper) {\n return true;\n }\n\n return capabilities.requiresWrapper;\n }\n\n /**\n * Check if schema is ZodObject-like\n */\n private isZodObjectLike(schema: unknown): boolean {\n if (!schema || typeof schema !== 'object') {\n return false;\n }\n\n const schemaRecord = schema as Record<string, unknown>;\n const schemaDef = schemaRecord._def as Record<string, unknown> | undefined;\n\n return (\n schema instanceof z.ZodObject ||\n schemaDef?.typeName === 'ZodObject' ||\n ('shape' in schemaRecord && typeof schemaRecord.shape === 'object')\n );\n }\n\n /**\n * Get statistics about the registry\n */\n getStatistics(): {\n totalTools: number;\n wrappedTools: number;\n unwrappedTools: number;\n categoryCounts: Record<ToolCapabilities['category'], number>;\n priorityCounts: Record<ToolCapabilities['priority'], number>;\n } {\n const stats = {\n totalTools: this.tools.size,\n wrappedTools: 0,\n unwrappedTools: 0,\n categoryCounts: { core: 0, extension: 0, mcp: 0 } as Record<\n ToolCapabilities['category'],\n number\n >,\n priorityCounts: { low: 0, medium: 0, high: 0, critical: 0 } as Record<\n ToolCapabilities['priority'],\n number\n >,\n };\n\n for (const entry of this.tools.values()) {\n if (entry.wrapper) {\n stats.wrappedTools++;\n } else {\n stats.unwrappedTools++;\n }\n\n stats.categoryCounts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vB,cAAc;AAAA,MACd,gBAAgB;AAAA,MAChB,gBAAgB,EAAE,MAAM,GAAG,WAAW,GAAG,KAAK,EAAA;AAAA,MAI9C,gBAAgB,EAAE,KAAK,GAAG,QAAQ,GAAG,MAAM,GAAG,UAAU,EAAA;AAAA,IAAE;AAM5D,eAAW,SAAS,KAAK,MAAM,OAAA,GAAU;AACvC,UAAI,MAAM,SAAS;AACjB,cAAM;AAAA,MACR,OAAO;AACL,cAAM;AAAA,MACR;AAEA,YAAM,eAAe,MAAM,SAAS,QAAQ;AAC5C,YAAM,eAAe,MAAM,SAAS,aAAa,QAAQ;AAAA,IAC3D;AAEA,WAAO;AAAA,EACT;AACF;"}
1
+ {"version":3,"file":"index40.js","sources":["../../src/constants/messages.ts"],"sourcesContent":["/**\n * Common error messages and user feedback strings\n */\nexport const ERROR_MESSAGES = {\n TOO_MANY_REQUESTS: 'Too many requests. Please wait a moment and try again.',\n RATE_LIMITED: \"I'm receiving too many requests right now. Please wait a moment and try again.\",\n SYSTEM_ERROR: 'System error occurred',\n INVALID_INPUT: 'Invalid input provided',\n NETWORK_ERROR: 'Network error occurred',\n} as const;\n\n/**\n * Common success and status messages\n */\nexport const STATUS_MESSAGES = {\n OPERATION_SUCCESSFUL: 'Operation completed successfully',\n PROCESSING: 'Processing your request...',\n READY: 'Ready to process requests',\n INITIALIZING: 'Initializing...',\n} as const;"],"names":[],"mappings":"AAGO,MAAM,iBAAiB;AAAA,EAC5B,mBAAmB;AAAA,EACnB,cAAc;AAIhB;"}
@@ -1,187 +1,258 @@
1
- import { ZodError } from "zod";
1
+ import { z } from "zod";
2
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" });
3
+ import { wrapToolWithFormValidation } from "./index30.js";
4
+ import { FormGenerator } from "./index10.js";
5
+ import { isFormValidatable } from "@hashgraphonline/standards-agent-kit";
6
+ class ToolRegistry {
7
+ constructor(logger) {
8
+ this.tools = /* @__PURE__ */ new Map();
9
+ this.formGenerator = new FormGenerator();
10
+ this.logger = logger || new Logger({ module: "ToolRegistry" });
9
11
  }
10
12
  /**
11
- * Execute a tool through the pipeline
13
+ * Register a tool with the registry
12
14
  */
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
15
+ registerTool(tool, options = {}) {
16
+ const capabilities = this.analyzeToolCapabilities(tool);
17
+ const metadata = {
18
+ name: tool.name,
19
+ version: "1.0.0",
20
+ category: options.metadata?.category || "core",
21
+ description: tool.description,
22
+ capabilities,
23
+ dependencies: [],
24
+ schema: tool.schema,
25
+ ...options.metadata
27
26
  };
28
27
  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
- };
28
+ if (!metadata.entityResolutionPreferences) {
29
+ const schemaRecord = tool.schema;
30
+ const rawPrefs = schemaRecord && typeof schemaRecord === "object" && schemaRecord["_entityResolutionPreferences"];
31
+ if (rawPrefs && typeof rawPrefs === "object") {
32
+ metadata.entityResolutionPreferences = rawPrefs;
33
+ }
34
+ }
35
+ } catch {
36
+ }
37
+ try {
38
+ const schemaRecord = tool.schema;
39
+ const schemaDef = schemaRecord && schemaRecord._def;
40
+ if (schemaDef?.typeName === "ZodObject") {
41
+ const shape = typeof schemaDef.shape === "function" ? schemaDef.shape?.() || {} : schemaDef.shape || {};
42
+ const metadataField = shape["metadata"];
43
+ const isStringArray = !!metadataField && metadataField._def?.typeName === "ZodArray" && metadataField._def?.type?._def?.typeName === "ZodString";
44
+ if (isStringArray && typeof tool.description === "string") {
45
+ if (!metadata.entityResolutionPreferences) {
46
+ metadata.entityResolutionPreferences = {
47
+ inscription: "hrl"
48
+ };
49
+ }
50
+ const note = " NOTE: When referencing inscriptions or media, provide canonical Hashlink Resource Locators (e.g., hcs://<standard>/<topicId>) rather than external URLs or embedded JSON.";
51
+ if (!tool.description.includes("Hashlink Resource Locators")) {
52
+ tool.description = `${tool.description}${note}`;
53
+ }
54
+ }
39
55
  }
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
56
+ } catch {
57
+ }
58
+ let finalTool = tool;
59
+ let wrapper;
60
+ if (this.shouldWrapTool(tool, capabilities, options)) {
61
+ wrapper = wrapToolWithFormValidation(
62
+ tool,
63
+ this.formGenerator,
64
+ {
65
+ requireAllFields: false,
66
+ skipFields: ["metaOptions"],
67
+ ...options.wrapperConfig
68
+ }
53
69
  );
70
+ finalTool = wrapper;
54
71
  }
72
+ try {
73
+ if (metadata.entityResolutionPreferences) {
74
+ finalTool["entityResolutionPreferences"] = metadata.entityResolutionPreferences;
75
+ }
76
+ } catch {
77
+ }
78
+ const entry = {
79
+ tool: finalTool,
80
+ metadata,
81
+ wrapper,
82
+ originalTool: tool
83
+ };
84
+ this.tools.set(tool.name, entry);
55
85
  }
56
86
  /**
57
- * Execute tool with validation
87
+ * Get a tool by name
58
88
  */
59
- async executeWithValidation(toolName, input, sessionContext) {
60
- return this.execute(toolName, input, sessionContext);
89
+ getTool(name) {
90
+ return this.tools.get(name) || null;
61
91
  }
62
92
  /**
63
- * Process form submission
93
+ * Get tools by capability
64
94
  */
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
- };
95
+ getToolsByCapability(capability, value) {
96
+ const results = [];
97
+ for (const entry of this.tools.values()) {
98
+ if (value !== void 0) {
99
+ if (entry.metadata.capabilities[capability] === value) {
100
+ results.push(entry);
101
+ }
102
+ } else if (entry.metadata.capabilities[capability]) {
103
+ results.push(entry);
104
+ }
87
105
  }
106
+ return results;
88
107
  }
89
108
  /**
90
- * Check if form generation is required
109
+ * Get tools by query
91
110
  */
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 };
111
+ getToolsByQuery(query) {
112
+ const results = [];
113
+ for (const entry of this.tools.values()) {
114
+ let matches = true;
115
+ if (query.name && entry.metadata.name !== query.name) {
116
+ matches = false;
117
+ }
118
+ if (query.category && entry.metadata.category !== query.category) {
119
+ matches = false;
120
+ }
121
+ if (query.capabilities) {
122
+ for (const [key, value] of Object.entries(query.capabilities)) {
123
+ if (entry.metadata.capabilities[key] !== value) {
124
+ matches = false;
125
+ break;
126
+ }
127
+ }
128
+ }
129
+ if (matches) {
130
+ results.push(entry);
131
+ }
107
132
  }
108
- return { requiresForm: false };
133
+ return results;
109
134
  }
110
135
  /**
111
- * Execute tool directly
136
+ * Get all registered tools
112
137
  */
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);
138
+ getAllTools() {
139
+ return Array.from(this.tools.values()).map((entry) => entry.tool);
121
140
  }
122
141
  /**
123
- * Execute wrapped tool
142
+ * Get all registry entries
124
143
  */
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);
144
+ getAllRegistryEntries() {
145
+ return Array.from(this.tools.values());
146
+ }
147
+ /**
148
+ * Get all tool names
149
+ */
150
+ getToolNames() {
151
+ return Array.from(this.tools.keys());
138
152
  }
139
153
  /**
140
- * Handle execution error
154
+ * Check if a tool is registered
141
155
  */
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
- };
156
+ hasTool(name) {
157
+ return this.tools.has(name);
158
+ }
159
+ /**
160
+ * Unregister a tool
161
+ */
162
+ unregisterTool(name) {
163
+ return this.tools.delete(name);
164
+ }
165
+ /**
166
+ * Clear all tools
167
+ */
168
+ clear() {
169
+ this.tools.clear();
170
+ }
171
+ /**
172
+ * Analyze tool capabilities
173
+ */
174
+ analyzeToolCapabilities(tool) {
175
+ const implementsFormValidatable = isFormValidatable(tool);
176
+ const hasRenderConfig = this.hasRenderConfig(tool);
177
+ const isZodObjectLike = this.isZodObjectLike(tool.schema);
178
+ const supportsFormValidation = implementsFormValidatable || hasRenderConfig;
179
+ const requiresWrapper = supportsFormValidation && isZodObjectLike;
180
+ let priority = "medium";
181
+ let category = "core";
182
+ if (supportsFormValidation && requiresWrapper) {
183
+ priority = "critical";
184
+ } else if (supportsFormValidation) {
185
+ priority = "high";
186
+ } else if (tool.description?.toLowerCase().includes("query") || tool.description?.toLowerCase().includes("search")) {
187
+ priority = "low";
188
+ }
189
+ const toolAsAny = tool;
190
+ if (tool.constructor.name.includes("MCP") || toolAsAny.isMCPTool) {
191
+ category = "mcp";
192
+ } else if (toolAsAny.isExtension || tool.constructor.name.includes("Extension")) {
193
+ category = "extension";
152
194
  }
153
- this.logger.error(`Tool execution failed: ${context.toolName}`, {
154
- traceId,
155
- error: errorMessage
156
- });
157
195
  return {
158
- success: false,
159
- output: "Tool execution failed",
160
- error: errorMessage,
161
- traceId,
162
- executionTime
196
+ supportsFormValidation,
197
+ requiresWrapper,
198
+ priority,
199
+ category
163
200
  };
164
201
  }
165
202
  /**
166
- * Build default session context
203
+ * Check if tool has render configuration
167
204
  */
168
- buildDefaultSession() {
169
- return {
170
- sessionId: `session-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
171
- timestamp: Date.now()
172
- };
205
+ hasRenderConfig(tool) {
206
+ const schema = tool.schema;
207
+ return !!(schema && schema._renderConfig);
173
208
  }
174
209
  /**
175
- * Get statistics about the pipeline
210
+ * Determine if tool should be wrapped
211
+ */
212
+ shouldWrapTool(tool, capabilities, options) {
213
+ if (options.skipWrapper) {
214
+ return false;
215
+ }
216
+ if (options.forceWrapper) {
217
+ return true;
218
+ }
219
+ return capabilities.requiresWrapper;
220
+ }
221
+ /**
222
+ * Check if schema is ZodObject-like
223
+ */
224
+ isZodObjectLike(schema) {
225
+ if (!schema || typeof schema !== "object") {
226
+ return false;
227
+ }
228
+ const schemaRecord = schema;
229
+ const schemaDef = schemaRecord._def;
230
+ return schema instanceof z.ZodObject || schemaDef?.typeName === "ZodObject" || "shape" in schemaRecord && typeof schemaRecord.shape === "object";
231
+ }
232
+ /**
233
+ * Get statistics about the registry
176
234
  */
177
235
  getStatistics() {
178
- return {
179
- totalMiddleware: 0,
180
- registeredMiddleware: []
236
+ const stats = {
237
+ totalTools: this.tools.size,
238
+ wrappedTools: 0,
239
+ unwrappedTools: 0,
240
+ categoryCounts: { core: 0, extension: 0, mcp: 0 },
241
+ priorityCounts: { low: 0, medium: 0, high: 0, critical: 0 }
181
242
  };
243
+ for (const entry of this.tools.values()) {
244
+ if (entry.wrapper) {
245
+ stats.wrappedTools++;
246
+ } else {
247
+ stats.unwrappedTools++;
248
+ }
249
+ stats.categoryCounts[entry.metadata.category]++;
250
+ stats.priorityCounts[entry.metadata.capabilities.priority]++;
251
+ }
252
+ return stats;
182
253
  }
183
254
  }
184
255
  export {
185
- ExecutionPipeline
256
+ ToolRegistry
186
257
  };
187
258
  //# sourceMappingURL=index41.js.map
@@ -1 +1 @@
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,gBAC0B;AAC1B,UAAM,UAAU,SAAS,KAAK,IAAA,CAAK,IAAI,KAAK,OAAA,EACzC,SAAS,EAAE,EACX,OAAO,GAAG,CAAC,CAAC;AACf,UAAM,YAAY,KAAK,IAAA;AAEvB,UAAM,YAAY,KAAK,aAAa,QAAQ,QAAQ;AACpD,QAAI,CAAC,WAAW;AACd,YAAM,IAAI,MAAM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C,aAAO,MAAM,aAAa,gBAAgB,UAAU;AAAA,IACtD;AAEA,QAAI,aAAa,cAAc,MAAM;AACnC,aAAO,MAAM,aAAa,aAAa,KAAK,UAAU;AAAA,IACxD;AAEA,WAAO,MAAM,UAAU,aAAa,KAAK,UAAU;AAAA,EACrD;AAAA;AAAA;AAAA;AAAA,EAKQ,qBACN,OACA,SACA,SACA,eACiB;AACjB,UAAM,eAAe,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAE1E,QAAI,iBAAiB,UAAU;AAC7B,aAAO;AAAA,QACL,SAAS;AAAA,QACT,QAAQ;AAAA,QACR,OAAO;AAAA,QACP;AAAA,QACA;AAAA,MAAA;AAAA,IAEJ;AAEA,SAAK,OAAO,MAAM,0BAA0B,QAAQ,QAAQ,IAAI;AAAA,MAC9D;AAAA,MACA,OAAO;AAAA,IAAA,CACR;AAED,WAAO;AAAA,MACL,SAAS;AAAA,MACT,QAAQ;AAAA,MACR,OAAO;AAAA,MACP;AAAA,MACA;AAAA,IAAA;AAAA,EAEJ;AAAA;AAAA;AAAA;AAAA,EAKQ,sBAAsC;AAC5C,WAAO;AAAA,MACL,WAAW,WAAW,KAAK,IAAA,CAAK,IAAI,KAAK,OAAA,EACtC,SAAS,EAAE,EACX,OAAO,GAAG,CAAC,CAAC;AAAA,MACf,WAAW,KAAK,IAAA;AAAA,IAAI;AAAA,EAExB;AAAA;AAAA;AAAA;AAAA,EAKA,gBAGE;AACA,WAAO;AAAA,MACL,iBAAiB;AAAA,MACjB,sBAAsB,CAAA;AAAA,IAAC;AAAA,EAE3B;AACF;"}
1
+ {"version":3,"file":"index41.js","sources":["../../src/core/tool-registry.ts"],"sourcesContent":["import { StructuredTool } from '@langchain/core/tools';\nimport { z } from 'zod';\nimport { Logger } from '@hashgraphonline/standards-sdk';\nimport {\n FormValidatingToolWrapper,\n wrapToolWithFormValidation,\n} from '../langchain/form-validating-tool-wrapper';\nimport { FormGenerator } from '../forms/form-generator';\nimport { isFormValidatable } from '@hashgraphonline/standards-agent-kit';\n\n/**\n * Tool capabilities configuration for registry entries\n */\nexport interface ToolCapabilities {\n supportsFormValidation: boolean;\n requiresWrapper: boolean;\n priority: 'low' | 'medium' | 'high' | 'critical';\n category: 'core' | 'extension' | 'mcp';\n}\n\n/**\n * Entity resolution format preferences for tools\n */\nexport interface EntityResolutionPreferences {\n inscription?: 'hrl' | 'topicId' | 'metadata' | 'any';\n token?: 'tokenId' | 'address' | 'symbol' | 'any';\n nft?: 'serialNumber' | 'metadata' | 'hrl' | 'any';\n account?: 'accountId' | 'alias' | 'evmAddress' | 'any';\n}\n\n/**\n * Tool metadata for comprehensive tool information\n */\nexport interface ToolMetadata {\n name: string;\n version: string;\n category: ToolCapabilities['category'];\n description: string;\n capabilities: ToolCapabilities;\n dependencies: string[];\n schema: unknown;\n entityResolutionPreferences?: EntityResolutionPreferences;\n}\n\n/**\n * Registry entry containing tool instance and metadata\n */\nexport interface ToolRegistryEntry {\n tool: StructuredTool;\n metadata: ToolMetadata;\n wrapper?: FormValidatingToolWrapper<z.ZodObject<z.ZodRawShape>> | undefined;\n originalTool: StructuredTool;\n}\n\n/**\n * Options for tool registration\n */\nexport interface ToolRegistrationOptions {\n forceWrapper?: boolean;\n skipWrapper?: boolean;\n wrapperConfig?: {\n requireAllFields?: boolean;\n skipFields?: string[];\n };\n metadata?: Partial<ToolMetadata>;\n}\n\n/**\n * Query interface for finding tools\n */\nexport interface ToolQuery {\n name?: string;\n category?: ToolMetadata['category'];\n capabilities?: Partial<ToolCapabilities>;\n}\n\n/**\n * Centralized tool registry for managing tool lifecycle\n */\nexport class ToolRegistry {\n private tools = new Map<string, ToolRegistryEntry>();\n private formGenerator: FormGenerator;\n private logger: Logger;\n\n constructor(logger?: Logger) {\n this.formGenerator = new FormGenerator();\n this.logger = logger || new Logger({ module: 'ToolRegistry' });\n }\n\n /**\n * Register a tool with the registry\n */\n registerTool(\n tool: StructuredTool,\n options: ToolRegistrationOptions = {}\n ): void {\n const capabilities = this.analyzeToolCapabilities(tool);\n const metadata: ToolMetadata = {\n name: tool.name,\n version: '1.0.0',\n category: options.metadata?.category || 'core',\n description: tool.description,\n capabilities,\n dependencies: [],\n schema: tool.schema,\n ...options.metadata,\n };\n\n try {\n if (!metadata.entityResolutionPreferences) {\n const schemaRecord = tool.schema as unknown as Record<string, unknown>;\n const rawPrefs =\n schemaRecord &&\n typeof schemaRecord === 'object' &&\n (schemaRecord as Record<string, unknown>)[\n '_entityResolutionPreferences'\n ];\n if (rawPrefs && typeof rawPrefs === 'object') {\n metadata.entityResolutionPreferences = rawPrefs as unknown as EntityResolutionPreferences;\n }\n }\n } catch {\n }\n\n try {\n const schemaRecord = tool.schema as unknown as Record<string, unknown>;\n const schemaDef = (schemaRecord && (schemaRecord as Record<string, unknown>)._def) as\n | { typeName?: string; shape?: unknown }\n | undefined;\n if (schemaDef?.typeName === 'ZodObject') {\n const shape: Record<string, unknown> =\n typeof (schemaDef as { shape?: () => Record<string, unknown> }).shape === 'function'\n ? ((schemaDef as { shape: () => Record<string, unknown> }).shape?.() || {})\n : ((schemaDef as { shape?: Record<string, unknown> }).shape || {});\n\n const metadataField = shape['metadata'] as\n | { _def?: { typeName?: string; type?: { _def?: { typeName?: string } } } }\n | undefined;\n const isStringArray =\n !!metadataField &&\n metadataField._def?.typeName === 'ZodArray' &&\n metadataField._def?.type?._def?.typeName === 'ZodString';\n\n if (isStringArray && typeof tool.description === 'string') {\n if (!metadata.entityResolutionPreferences) {\n metadata.entityResolutionPreferences = {\n inscription: 'hrl',\n } as EntityResolutionPreferences;\n }\n const note =\n ' NOTE: When referencing inscriptions or media, provide canonical Hashlink Resource Locators (e.g., hcs://<standard>/<topicId>) rather than external URLs or embedded JSON.';\n if (!tool.description.includes('Hashlink Resource Locators')) {\n (tool as unknown as { description: string }).description = `${tool.description}${note}`;\n }\n }\n }\n } catch {}\n\n let finalTool: StructuredTool = tool;\n let wrapper:\n | FormValidatingToolWrapper<z.ZodObject<z.ZodRawShape>>\n | undefined;\n\n if (this.shouldWrapTool(tool, capabilities, options)) {\n wrapper = wrapToolWithFormValidation(\n tool as StructuredTool<z.ZodObject<z.ZodRawShape>>,\n this.formGenerator,\n {\n requireAllFields: false,\n skipFields: ['metaOptions'],\n ...options.wrapperConfig,\n }\n ) as FormValidatingToolWrapper<z.ZodObject<z.ZodRawShape>>;\n finalTool = wrapper as StructuredTool;\n }\n\n try {\n if (metadata.entityResolutionPreferences) {\n (finalTool as unknown as Record<string, unknown>)[\n 'entityResolutionPreferences'\n ] = metadata.entityResolutionPreferences;\n }\n } catch {\n }\n\n const entry: ToolRegistryEntry = {\n tool: finalTool,\n metadata,\n wrapper,\n originalTool: tool,\n };\n\n this.tools.set(tool.name, entry);\n }\n\n /**\n * Get a tool by name\n */\n getTool(name: string): ToolRegistryEntry | null {\n return this.tools.get(name) || null;\n }\n\n /**\n * Get tools by capability\n */\n getToolsByCapability(\n capability: keyof ToolCapabilities,\n value?: unknown\n ): ToolRegistryEntry[] {\n const results: ToolRegistryEntry[] = [];\n\n for (const entry of this.tools.values()) {\n if (value !== undefined) {\n if (entry.metadata.capabilities[capability] === value) {\n results.push(entry);\n }\n } else if (entry.metadata.capabilities[capability]) {\n results.push(entry);\n }\n }\n\n return results;\n }\n\n /**\n * Get tools by query\n */\n getToolsByQuery(query: ToolQuery): ToolRegistryEntry[] {\n const results: ToolRegistryEntry[] = [];\n\n for (const entry of this.tools.values()) {\n let matches = true;\n\n if (query.name && entry.metadata.name !== query.name) {\n matches = false;\n }\n\n if (query.category && entry.metadata.category !== query.category) {\n matches = false;\n }\n\n if (query.capabilities) {\n for (const [key, value] of Object.entries(query.capabilities)) {\n if (\n entry.metadata.capabilities[key as keyof ToolCapabilities] !== value\n ) {\n matches = false;\n break;\n }\n }\n }\n\n if (matches) {\n results.push(entry);\n }\n }\n\n return results;\n }\n\n /**\n * Get all registered tools\n */\n getAllTools(): StructuredTool[] {\n return Array.from(this.tools.values()).map((entry) => entry.tool);\n }\n\n /**\n * Get all registry entries\n */\n getAllRegistryEntries(): ToolRegistryEntry[] {\n return Array.from(this.tools.values());\n }\n\n /**\n * Get all tool names\n */\n getToolNames(): string[] {\n return Array.from(this.tools.keys());\n }\n\n /**\n * Check if a tool is registered\n */\n hasTool(name: string): boolean {\n return this.tools.has(name);\n }\n\n /**\n * Unregister a tool\n */\n unregisterTool(name: string): boolean {\n return this.tools.delete(name);\n }\n\n /**\n * Clear all tools\n */\n clear(): void {\n this.tools.clear();\n }\n\n /**\n * Analyze tool capabilities\n */\n private analyzeToolCapabilities(tool: StructuredTool): ToolCapabilities {\n const implementsFormValidatable = isFormValidatable(tool);\n const hasRenderConfig = this.hasRenderConfig(tool);\n const isZodObjectLike = this.isZodObjectLike(tool.schema);\n\n const supportsFormValidation = implementsFormValidatable || hasRenderConfig;\n const requiresWrapper = supportsFormValidation && isZodObjectLike;\n\n let priority: ToolCapabilities['priority'] = 'medium';\n let category: ToolCapabilities['category'] = 'core';\n\n if (supportsFormValidation && requiresWrapper) {\n priority = 'critical';\n } else if (supportsFormValidation) {\n priority = 'high';\n } else if (\n tool.description?.toLowerCase().includes('query') ||\n tool.description?.toLowerCase().includes('search')\n ) {\n priority = 'low';\n }\n\n const toolAsAny = tool as unknown as Record<string, unknown>;\n if (tool.constructor.name.includes('MCP') || toolAsAny.isMCPTool) {\n category = 'mcp';\n } else if (\n toolAsAny.isExtension ||\n tool.constructor.name.includes('Extension')\n ) {\n category = 'extension';\n }\n\n return {\n supportsFormValidation,\n requiresWrapper,\n priority,\n category,\n };\n }\n\n /**\n * Check if tool has render configuration\n */\n private hasRenderConfig(tool: StructuredTool): boolean {\n const schema = tool.schema as Record<string, unknown>;\n return !!(schema && schema._renderConfig);\n }\n\n /**\n * Determine if tool should be wrapped\n */\n private shouldWrapTool(\n tool: StructuredTool,\n capabilities: ToolCapabilities,\n options: ToolRegistrationOptions\n ): boolean {\n if (options.skipWrapper) {\n return false;\n }\n\n if (options.forceWrapper) {\n return true;\n }\n\n return capabilities.requiresWrapper;\n }\n\n /**\n * Check if schema is ZodObject-like\n */\n private isZodObjectLike(schema: unknown): boolean {\n if (!schema || typeof schema !== 'object') {\n return false;\n }\n\n const schemaRecord = schema as Record<string, unknown>;\n const schemaDef = schemaRecord._def as Record<string, unknown> | undefined;\n\n return (\n schema instanceof z.ZodObject ||\n schemaDef?.typeName === 'ZodObject' ||\n ('shape' in schemaRecord && typeof schemaRecord.shape === 'object')\n );\n }\n\n /**\n * Get statistics about the registry\n */\n getStatistics(): {\n totalTools: number;\n wrappedTools: number;\n unwrappedTools: number;\n categoryCounts: Record<ToolCapabilities['category'], number>;\n priorityCounts: Record<ToolCapabilities['priority'], number>;\n } {\n const stats = {\n totalTools: this.tools.size,\n wrappedTools: 0,\n unwrappedTools: 0,\n categoryCounts: { core: 0, extension: 0, mcp: 0 } as Record<\n ToolCapabilities['category'],\n number\n >,\n priorityCounts: { low: 0, medium: 0, high: 0, critical: 0 } as Record<\n ToolCapabilities['priority'],\n number\n >,\n };\n\n for (const entry of this.tools.values()) {\n if (entry.wrapper) {\n stats.wrappedTools++;\n } else {\n stats.unwrappedTools++;\n }\n\n stats.categoryCounts[entry.metadata.category]++;\n stats.priorityCounts[entry.metadata.capabilities.priority]++;\n }\n\n return stats;\n }\n}\n"],"names":[],"mappings":";;;;;AA+EO,MAAM,aAAa;AAAA,EAKxB,YAAY,QAAiB;AAJ7B,SAAQ,4BAAY,IAAA;AAKlB,SAAK,gBAAgB,IAAI,cAAA;AACzB,SAAK,SAAS,UAAU,IAAI,OAAO,EAAE,QAAQ,gBAAgB;AAAA,EAC/D;AAAA;AAAA;AAAA;AAAA,EAKA,aACE,MACA,UAAmC,IAC7B;AACN,UAAM,eAAe,KAAK,wBAAwB,IAAI;AACtD,UAAM,WAAyB;AAAA,MAC7B,MAAM,KAAK;AAAA,MACX,SAAS;AAAA,MACT,UAAU,QAAQ,UAAU,YAAY;AAAA,MACxC,aAAa,KAAK;AAAA,MAClB;AAAA,MACA,cAAc,CAAA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eMs: 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 }
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
- 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";
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
- ContentReferenceError,
28
- DEFAULT_CONTENT_REFERENCE_CONFIG
185
+ ExecutionPipeline
29
186
  };
30
187
  //# sourceMappingURL=index42.js.map
@@ -1 +1 @@
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;"}
1
+ {"version":3,"file":"index42.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,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"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hashgraphonline/conversational-agent",
3
- "version": "0.1.220",
3
+ "version": "0.1.221",
4
4
  "type": "module",
5
5
  "main": "./dist/cjs/index.cjs",
6
6
  "module": "./dist/esm/index.js",
@@ -98,15 +98,14 @@
98
98
  "@hashgraphonline/standards-agent-kit": "0.2.135",
99
99
  "@hashgraphonline/standards-sdk": "0.0.187",
100
100
  "@langchain/anthropic": "^0.3.26",
101
- "@langchain/core": "^0.3.71",
102
- "@langchain/openai": "^0.6.7",
103
- "@modelcontextprotocol/sdk": "^1.17.0",
101
+ "@langchain/core": "^0.3.72",
102
+ "@langchain/openai": "^0.6.9",
103
+ "@modelcontextprotocol/sdk": "^1.17.4",
104
104
  "axios": "^1.11.0",
105
105
  "bignumber.js": "^9.3.1",
106
- "electron-log": "^5.4.2",
107
106
  "ethers": "^6.15.0",
108
107
  "hedera-agent-kit": "^2.0.3",
109
- "langchain": "^0.3.30",
108
+ "langchain": "^0.3.31",
110
109
  "tiktoken": "^1.0.22",
111
110
  "zod": "^3.25.0",
112
111
  "zod-to-json-schema": "^3.24.6"