@hashgraphonline/conversational-agent 0.2.0 → 0.2.101

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/README.md +3 -3
  2. package/dist/cjs/conversational-agent.d.ts +11 -1
  3. package/dist/cjs/index.cjs +1 -1
  4. package/dist/cjs/index.cjs.map +1 -1
  5. package/dist/cjs/services/attachment-processor.d.ts +41 -0
  6. package/dist/cjs/services/index.d.ts +2 -0
  7. package/dist/cjs/services/parameter-service.d.ts +43 -0
  8. package/dist/cjs/tools/entity-resolver-tool.d.ts +5 -3
  9. package/dist/esm/index.js +9 -5
  10. package/dist/esm/index.js.map +1 -1
  11. package/dist/esm/index10.js +2 -2
  12. package/dist/esm/index21.js +1 -1
  13. package/dist/esm/index23.js +3 -3
  14. package/dist/esm/index24.js +20 -4
  15. package/dist/esm/index24.js.map +1 -1
  16. package/dist/esm/index29.js +248 -903
  17. package/dist/esm/index29.js.map +1 -1
  18. package/dist/esm/index30.js +98 -219
  19. package/dist/esm/index30.js.map +1 -1
  20. package/dist/esm/index31.js +834 -1085
  21. package/dist/esm/index31.js.map +1 -1
  22. package/dist/esm/index32.js +228 -115
  23. package/dist/esm/index32.js.map +1 -1
  24. package/dist/esm/index33.js +1185 -79
  25. package/dist/esm/index33.js.map +1 -1
  26. package/dist/esm/index34.js +119 -39
  27. package/dist/esm/index34.js.map +1 -1
  28. package/dist/esm/index35.js +103 -96
  29. package/dist/esm/index35.js.map +1 -1
  30. package/dist/esm/index36.js +46 -21
  31. package/dist/esm/index36.js.map +1 -1
  32. package/dist/esm/index37.js +104 -24
  33. package/dist/esm/index37.js.map +1 -1
  34. package/dist/esm/index38.js +21 -12
  35. package/dist/esm/index38.js.map +1 -1
  36. package/dist/esm/index39.js +4 -6
  37. package/dist/esm/index39.js.map +1 -1
  38. package/dist/esm/index40.js +11 -4
  39. package/dist/esm/index40.js.map +1 -1
  40. package/dist/esm/index41.js +1 -1
  41. package/dist/esm/index43.js +24 -89
  42. package/dist/esm/index43.js.map +1 -1
  43. package/dist/esm/index44.js +10 -0
  44. package/dist/esm/index44.js.map +1 -0
  45. package/dist/esm/index45.js +95 -0
  46. package/dist/esm/index45.js.map +1 -0
  47. package/dist/esm/index5.js +2 -2
  48. package/dist/esm/index6.js +76 -6
  49. package/dist/esm/index6.js.map +1 -1
  50. package/dist/esm/index8.js +1 -1
  51. package/dist/types/conversational-agent.d.ts +11 -1
  52. package/dist/types/services/attachment-processor.d.ts +41 -0
  53. package/dist/types/services/index.d.ts +2 -0
  54. package/dist/types/services/parameter-service.d.ts +43 -0
  55. package/dist/types/tools/entity-resolver-tool.d.ts +5 -3
  56. package/package.json +3 -2
  57. package/src/conversational-agent.ts +97 -5
  58. package/src/langchain/langchain-agent.ts +9 -1
  59. package/src/services/attachment-processor.ts +163 -0
  60. package/src/services/content-store-manager.ts +32 -4
  61. package/src/services/index.ts +2 -0
  62. package/src/services/parameter-service.ts +430 -0
  63. package/src/tools/entity-resolver-tool.ts +12 -18
@@ -1,117 +1,1223 @@
1
- class ResponseFormatter {
1
+ import { createOpenAIToolsAgent } from "langchain/agents";
2
+ import { FormAwareAgentExecutor } from "./index31.js";
3
+ import { ChatPromptTemplate, MessagesPlaceholder } from "@langchain/core/prompts";
4
+ import { ChatOpenAI } from "@langchain/openai";
5
+ import { calculateTokenCostSync, TokenUsageCallbackHandler, getAllHederaCorePlugins, HederaAgentKit } from "hedera-agent-kit";
6
+ import { BaseAgent } from "./index7.js";
7
+ import { MCPClientManager } from "./index15.js";
8
+ import { convertMCPToolToLangChain } from "./index17.js";
9
+ import { SmartMemoryManager } from "./index18.js";
10
+ import { ResponseFormatter } from "./index35.js";
11
+ import { ERROR_MESSAGES } from "./index39.js";
12
+ import "./index40.js";
13
+ import { SystemMessage, AIMessage, HumanMessage } from "@langchain/core/messages";
14
+ import { ToolRegistry } from "./index41.js";
15
+ import { ExecutionPipeline } from "./index42.js";
16
+ import { FormEngine } from "./index11.js";
17
+ function hasHashLinkBlock(metadata) {
18
+ if (!metadata || typeof metadata !== "object") {
19
+ return false;
20
+ }
21
+ const meta = metadata;
22
+ if (!("hashLinkBlock" in meta) || !meta.hashLinkBlock || typeof meta.hashLinkBlock !== "object") {
23
+ return false;
24
+ }
25
+ const block = meta.hashLinkBlock;
26
+ return "blockId" in block && "hashLink" in block && "template" in block && "attributes" in block && typeof block.blockId === "string" && typeof block.hashLink === "string" && typeof block.template === "string" && typeof block.attributes === "object";
27
+ }
28
+ class LangChainAgent extends BaseAgent {
29
+ constructor() {
30
+ super(...arguments);
31
+ this.systemMessage = "";
32
+ this.mcpConnectionStatus = /* @__PURE__ */ new Map();
33
+ }
34
+ addToolRawToMemory(name, payload) {
35
+ try {
36
+ const content = `[tool-raw:${name}] ${payload}`;
37
+ this.smartMemory.addMessage(new SystemMessage(content));
38
+ } catch {
39
+ }
40
+ }
41
+ persistToolRaw(toolName, output) {
42
+ try {
43
+ let payload = "";
44
+ if (typeof output === "string") {
45
+ payload = this.isJSON(output) ? output : JSON.stringify({ output });
46
+ } else if (output !== void 0) {
47
+ try {
48
+ payload = JSON.stringify(output);
49
+ } catch {
50
+ payload = String(output);
51
+ }
52
+ } else {
53
+ payload = JSON.stringify({ observation: null });
54
+ }
55
+ this.addToolRawToMemory(toolName, payload);
56
+ } catch {
57
+ }
58
+ }
59
+ persistIntermediateSteps(steps) {
60
+ if (!steps || !Array.isArray(steps)) {
61
+ return;
62
+ }
63
+ try {
64
+ for (const step of steps) {
65
+ const name = step?.action?.tool || "unknown";
66
+ const obs = step?.observation;
67
+ this.persistToolRaw(name, obs);
68
+ }
69
+ } catch {
70
+ }
71
+ }
2
72
  /**
3
- * Checks if a parsed response contains HashLink block data for interactive rendering
73
+ * Get inscription tool by capability instead of hardcoded name
4
74
  */
5
- static isHashLinkResponse(parsed) {
6
- if (!parsed || typeof parsed !== "object") {
7
- return false;
75
+ getInscriptionTool() {
76
+ const criticalTools = this.toolRegistry.getToolsByCapability(
77
+ "priority",
78
+ "critical"
79
+ );
80
+ for (const entry of criticalTools) {
81
+ const tool = entry.tool;
82
+ const name = tool.name.toLowerCase();
83
+ const desc = tool.description?.toLowerCase() || "";
84
+ if (name.includes("inscribe") || name.includes("hashinal") || desc.includes("inscribe") || desc.includes("hashinal")) {
85
+ return tool;
86
+ }
87
+ }
88
+ const allTools = this.toolRegistry.getAllRegistryEntries();
89
+ for (const entry of allTools) {
90
+ const tool = entry.tool;
91
+ const name = tool.name.toLowerCase();
92
+ const desc = tool.description?.toLowerCase() || "";
93
+ if (name.includes("inscribe") || name.includes("hashinal") || desc.includes("inscribe") || desc.includes("hashinal")) {
94
+ return tool;
95
+ }
8
96
  }
9
- const responseObj = parsed;
10
- return !!(responseObj.success === true && responseObj.type === "inscription" && responseObj.hashLinkBlock && typeof responseObj.hashLinkBlock === "object");
97
+ return null;
11
98
  }
12
99
  /**
13
- * Formats HashLink block response with simple text confirmation
14
- * HTML template rendering is handled by HashLinkBlockRenderer component via metadata
100
+ * Execute a tool directly with parameters, optionally using ExecutionPipeline
15
101
  */
16
- static formatHashLinkResponse(parsed) {
17
- const hashLinkBlock = parsed.hashLinkBlock;
18
- const metadata = parsed.metadata || {};
19
- const inscription = parsed.inscription || {};
20
- let message = "✅ Interactive content created successfully!\n\n";
21
- if (metadata.name) {
22
- message += `**${metadata.name}**
23
- `;
102
+ async executeToolDirect(toolName, parameters, useExecutionPipeline = false) {
103
+ if (useExecutionPipeline && this.executionPipeline && this.smartMemory) {
104
+ const sessionContext = {
105
+ sessionId: `session-${Date.now()}`,
106
+ timestamp: Date.now()
107
+ };
108
+ const result = await this.executionPipeline.execute(
109
+ toolName,
110
+ parameters,
111
+ sessionContext
112
+ );
113
+ if (!result.success) {
114
+ throw new Error(result.error || "Pipeline execution failed");
115
+ }
116
+ return result.output;
117
+ }
118
+ const entry = this.toolRegistry.getTool(toolName);
119
+ if (!entry) {
120
+ throw new Error(`Tool not found: ${toolName}`);
24
121
  }
25
- if (metadata.description) {
26
- message += `${metadata.description}
27
-
28
- `;
122
+ let processedParameters = { ...parameters };
123
+ if (this.pendingParameterPreprocessingCallback) {
124
+ this.logger.info(
125
+ "Applying parameter preprocessing in executeToolDirect",
126
+ {
127
+ toolName,
128
+ hasCallback: true,
129
+ parameterKeys: Object.keys(parameters)
130
+ }
131
+ );
132
+ try {
133
+ processedParameters = await this.pendingParameterPreprocessingCallback(
134
+ toolName,
135
+ parameters
136
+ );
137
+ if (JSON.stringify(processedParameters) !== JSON.stringify(parameters)) {
138
+ this.logger.info("Parameters preprocessed successfully", {
139
+ toolName,
140
+ originalKeys: Object.keys(parameters),
141
+ processedKeys: Object.keys(processedParameters),
142
+ changes: Object.keys(processedParameters).filter(
143
+ (key) => processedParameters[key] !== parameters[key]
144
+ )
145
+ });
146
+ }
147
+ } catch (error) {
148
+ this.logger.warn(
149
+ "Parameter preprocessing failed, using original parameters",
150
+ {
151
+ toolName,
152
+ error: error instanceof Error ? error.message : "Unknown error"
153
+ }
154
+ );
155
+ processedParameters = parameters;
156
+ }
157
+ }
158
+ const mergedArgs = { ...processedParameters, renderForm: false };
159
+ if (entry.wrapper) {
160
+ const maybeWrapper = entry.tool;
161
+ if (maybeWrapper.originalTool?.call) {
162
+ return await maybeWrapper.originalTool.call(mergedArgs);
163
+ }
29
164
  }
30
- if (inscription.topicId || hashLinkBlock.attributes.topicId) {
31
- message += `📍 **Topic ID:** ${inscription.topicId || hashLinkBlock.attributes.topicId}
32
- `;
165
+ return await entry.tool.call(mergedArgs);
166
+ }
167
+ /**
168
+ * Create a standard ChatResponse from tool output
169
+ */
170
+ createToolResponse(toolOutput) {
171
+ return {
172
+ output: toolOutput,
173
+ message: toolOutput,
174
+ notes: []
175
+ };
176
+ }
177
+ /**
178
+ * Handle TOOL_EXECUTION format messages
179
+ */
180
+ async handleToolExecution(message, context) {
181
+ let isToolExecution = false;
182
+ let toolExecutionData = null;
183
+ try {
184
+ if (message.includes("TOOL_EXECUTION")) {
185
+ const parsed = JSON.parse(message);
186
+ if (parsed.type === "TOOL_EXECUTION") {
187
+ isToolExecution = true;
188
+ toolExecutionData = parsed;
189
+ }
190
+ }
191
+ } catch {
33
192
  }
34
- if (inscription.hrl || hashLinkBlock.attributes.hrl) {
35
- message += `🔗 **HRL:** ${inscription.hrl || hashLinkBlock.attributes.hrl}
36
- `;
193
+ if (!isToolExecution || !toolExecutionData?.formId) {
194
+ return null;
37
195
  }
38
- if (inscription.cdnUrl) {
39
- message += `🌐 **CDN URL:** ${inscription.cdnUrl}
40
- `;
196
+ try {
197
+ const params = toolExecutionData.parameters || {};
198
+ const toolName = toolExecutionData.toolName;
199
+ if (toolName) {
200
+ const toolOutput = await this.executeToolDirect(toolName, params);
201
+ try {
202
+ const payload = this.isJSON(toolOutput) ? toolOutput : JSON.stringify({ output: toolOutput });
203
+ this.addToolRawToMemory(toolName, payload);
204
+ } catch {
205
+ }
206
+ return this.createToolResponse(toolOutput);
207
+ }
208
+ } catch {
41
209
  }
42
- if (metadata.creator) {
43
- message += `👤 **Creator:** ${metadata.creator}
44
- `;
210
+ const formSubmission = {
211
+ formId: toolExecutionData.formId,
212
+ toolName: toolExecutionData.toolName || "",
213
+ parameters: toolExecutionData.parameters || {},
214
+ timestamp: Date.now()
215
+ };
216
+ if (this.executor && "processFormSubmission" in this.executor && typeof this.executor.processFormSubmission === "function") {
217
+ return this.processFormSubmission(formSubmission, context);
45
218
  }
46
- message += "\n⚡ Interactive content will load below";
47
- return message.trim();
219
+ return null;
48
220
  }
49
221
  /**
50
- * Checks if a parsed response is an inscription response that needs formatting
222
+ * Handle direct tool execution commands
51
223
  */
52
- static isInscriptionResponse(parsed) {
53
- if (!parsed || typeof parsed !== "object") {
54
- return false;
224
+ async handleDirectToolExecution(message) {
225
+ if (typeof message !== "string" || !message.includes("Please execute the following tool:")) {
226
+ return null;
55
227
  }
56
- const responseObj = parsed;
57
- return !!(responseObj.success === true && responseObj.type === "inscription" && responseObj.inscription && typeof responseObj.inscription === "object");
228
+ try {
229
+ const toolLineMatch = message.match(/Tool:\s*(.+)/);
230
+ const argsLineIndex = message.indexOf("Arguments:");
231
+ if (toolLineMatch && argsLineIndex !== -1) {
232
+ const toolName = toolLineMatch[1].trim();
233
+ const argsText = message.slice(argsLineIndex + "Arguments:".length).trim();
234
+ let args = {};
235
+ try {
236
+ args = JSON.parse(argsText);
237
+ } catch {
238
+ }
239
+ const toolOutput = await this.executeToolDirect(toolName, args);
240
+ try {
241
+ const payload = this.isJSON(toolOutput) ? toolOutput : JSON.stringify({ output: toolOutput });
242
+ this.addToolRawToMemory(toolName, payload);
243
+ } catch {
244
+ }
245
+ return this.createToolResponse(toolOutput);
246
+ }
247
+ } catch {
248
+ }
249
+ return null;
250
+ }
251
+ /**
252
+ * Handle JSON format tool calls and form submissions
253
+ */
254
+ async handleJsonToolCalls(message, context) {
255
+ if (typeof message !== "string") {
256
+ return null;
257
+ }
258
+ try {
259
+ const trimmed = message.trim();
260
+ if (!(trimmed.startsWith("{") && trimmed.endsWith("}")) && !(trimmed.startsWith("[") && trimmed.endsWith("]"))) {
261
+ return null;
262
+ }
263
+ const obj = JSON.parse(trimmed);
264
+ const formId = obj["formId"];
265
+ const toolName = obj["toolName"] || "";
266
+ const parameters = obj["parameters"] || {};
267
+ if (formId && this.executor && "processFormSubmission" in this.executor && typeof this.executor.processFormSubmission === "function") {
268
+ return this.processFormSubmission(
269
+ { formId, toolName, parameters, timestamp: Date.now() },
270
+ context
271
+ );
272
+ }
273
+ if (toolName) {
274
+ const toolOutput = await this.executeToolDirect(toolName, parameters);
275
+ try {
276
+ const payload = this.isJSON(toolOutput) ? toolOutput : JSON.stringify({ output: toolOutput });
277
+ this.addToolRawToMemory(toolName, payload);
278
+ } catch {
279
+ }
280
+ return this.createToolResponse(toolOutput);
281
+ }
282
+ } catch {
283
+ }
284
+ return null;
58
285
  }
59
286
  /**
60
- * Formats inscription response into user-friendly message
287
+ * Handle content-ref messages for inscription tools
61
288
  */
62
- static formatInscriptionResponse(parsed) {
63
- const inscription = parsed.inscription;
64
- const metadata = parsed.metadata || {};
65
- const title = parsed.title || "Inscription Complete";
66
- let message = `✅ ${title}
67
-
68
- `;
69
- if (metadata.name) {
70
- message += `**${metadata.name}**
71
- `;
289
+ async handleContentRefMessages(message) {
290
+ if (typeof message !== "string" || !message.includes("content-ref:")) {
291
+ return null;
72
292
  }
73
- if (metadata.description) {
74
- message += `${metadata.description}
75
-
76
- `;
293
+ try {
294
+ const tool = this.getInscriptionTool();
295
+ if (!tool) {
296
+ return null;
297
+ }
298
+ const idMatch = message.match(/content-ref:([A-Za-z0-9_\-]+)/i) || message.match(/content-ref:([^\s)]+)/i);
299
+ const contentRef = idMatch && idMatch[1] ? `content-ref:${idMatch[1]}` : message.match(/content-ref:[^\s)]+/i)?.[0] || void 0;
300
+ const args = contentRef ? { contentRef, renderForm: true, withHashLinkBlocks: true } : { renderForm: true, withHashLinkBlocks: true };
301
+ const toolOutput = await tool.call(args);
302
+ let parsed;
303
+ try {
304
+ parsed = typeof toolOutput === "string" ? JSON.parse(toolOutput) : toolOutput;
305
+ } catch {
306
+ }
307
+ if (parsed && parsed["requiresForm"] && parsed["formMessage"]) {
308
+ const pending = /* @__PURE__ */ new Map();
309
+ const originalInput = {
310
+ input: message,
311
+ chat_history: this.smartMemory.getMessages()
312
+ };
313
+ const formMessage = parsed["formMessage"];
314
+ pending.set(formMessage.id, {
315
+ toolName: tool.name,
316
+ originalInput,
317
+ originalToolInput: args,
318
+ schema: null
319
+ });
320
+ const maybeRestore = this.executor;
321
+ if (typeof maybeRestore.restorePendingForms === "function") {
322
+ maybeRestore.restorePendingForms(pending);
323
+ }
324
+ const outputMsg = parsed["message"] || "Please complete the form to continue.";
325
+ return {
326
+ output: outputMsg,
327
+ message: outputMsg,
328
+ notes: [],
329
+ requiresForm: true,
330
+ formMessage
331
+ };
332
+ }
333
+ } catch {
77
334
  }
78
- if (inscription.topicId) {
79
- message += `📍 **Topic ID:** ${inscription.topicId}
80
- `;
335
+ return null;
336
+ }
337
+ /**
338
+ * Process executor result and format response
339
+ */
340
+ async processExecutorResult(result) {
341
+ let outputStr = "";
342
+ if (typeof result.output === "string") {
343
+ outputStr = result.output;
344
+ } else if (result.output) {
345
+ try {
346
+ outputStr = JSON.stringify(result.output);
347
+ } catch {
348
+ outputStr = String(result.output);
349
+ }
81
350
  }
82
- if (inscription.hrl) {
83
- message += `🔗 **HRL:** ${inscription.hrl}
84
- `;
351
+ let response = {
352
+ output: outputStr,
353
+ message: outputStr,
354
+ notes: [],
355
+ intermediateSteps: result.intermediateSteps
356
+ };
357
+ if (result.requiresForm && result.formMessage) {
358
+ response.formMessage = result.formMessage;
359
+ response.requiresForm = true;
85
360
  }
86
- if (inscription.cdnUrl) {
87
- message += `🌐 **CDN URL:** ${inscription.cdnUrl}
88
- `;
361
+ if (result.intermediateSteps && Array.isArray(result.intermediateSteps)) {
362
+ const toolCalls = result.intermediateSteps.map(
363
+ (step, index) => ({
364
+ id: `call_${index}`,
365
+ name: step.action?.tool || "unknown",
366
+ args: step.action?.toolInput || {},
367
+ output: typeof step.observation === "string" ? step.observation : JSON.stringify(step.observation)
368
+ })
369
+ );
370
+ if (toolCalls.length > 0) {
371
+ response.tool_calls = toolCalls;
372
+ }
373
+ this.persistIntermediateSteps(
374
+ result.intermediateSteps
375
+ );
89
376
  }
90
- if (metadata.creator) {
91
- message += `👤 **Creator:** ${metadata.creator}
92
- `;
377
+ const parsedSteps = result?.intermediateSteps?.[0]?.observation;
378
+ if (parsedSteps && typeof parsedSteps === "string" && this.isJSON(parsedSteps)) {
379
+ try {
380
+ const parsed = JSON.parse(parsedSteps);
381
+ if (ResponseFormatter.isInscriptionResponse(parsed)) {
382
+ const formattedMessage = ResponseFormatter.formatInscriptionResponse(parsed);
383
+ response.output = formattedMessage;
384
+ response.message = formattedMessage;
385
+ if (parsed.inscription) {
386
+ response.inscription = parsed.inscription;
387
+ }
388
+ if (parsed.metadata) {
389
+ response.metadata = {
390
+ ...response.metadata,
391
+ ...parsed.metadata
392
+ };
393
+ }
394
+ } else {
395
+ response = { ...response, ...parsed };
396
+ }
397
+ const blockMetadata = this.processHashLinkBlocks(parsed);
398
+ if (blockMetadata.hashLinkBlock) {
399
+ response.metadata = {
400
+ ...response.metadata,
401
+ ...blockMetadata
402
+ };
403
+ }
404
+ } catch (error) {
405
+ this.logger.error("Error parsing intermediate steps:", error);
406
+ }
93
407
  }
94
- return message.trim();
408
+ if (!response.output || response.output.trim() === "") {
409
+ response.output = "Agent action complete.";
410
+ }
411
+ if (response.output) {
412
+ this.smartMemory.addMessage(new AIMessage(response.output));
413
+ }
414
+ if (this.tokenTracker) {
415
+ const tokenUsage = this.tokenTracker.getLatestTokenUsage();
416
+ if (tokenUsage) {
417
+ response.tokenUsage = tokenUsage;
418
+ response.cost = calculateTokenCostSync(tokenUsage);
419
+ }
420
+ }
421
+ const finalMemoryStats = this.smartMemory.getMemoryStats();
422
+ response.metadata = {
423
+ ...response.metadata,
424
+ memoryStats: {
425
+ activeMessages: finalMemoryStats.totalActiveMessages,
426
+ tokenUsage: finalMemoryStats.currentTokenCount,
427
+ maxTokens: finalMemoryStats.maxTokens,
428
+ usagePercentage: finalMemoryStats.usagePercentage
429
+ }
430
+ };
431
+ this.logger.info("LangChainAgent.chat returning response:", response);
432
+ return response;
95
433
  }
96
434
  /**
97
- * Main formatting method that determines the best response format
435
+ * Normalize context messages into LangChain message instances and load into memory
98
436
  */
99
- static formatResponse(toolOutput) {
437
+ /**
438
+ * Loads context messages into memory, merging with existing messages
439
+ */
440
+ loadContextMessages(context) {
441
+ if (!this.smartMemory || !context?.messages || context.messages.length === 0) {
442
+ return;
443
+ }
444
+ const existingMessages = this.smartMemory.getMessages();
445
+ const existingContent = new Set(
446
+ existingMessages.map((m) => `${m.constructor.name}:${m.content}`)
447
+ );
448
+ for (const msg of context.messages) {
449
+ let messageClass;
450
+ let content;
451
+ if (msg instanceof HumanMessage || msg instanceof AIMessage || msg instanceof SystemMessage) {
452
+ messageClass = msg.constructor;
453
+ content = msg.content;
454
+ } else if (msg && typeof msg === "object" && "content" in msg && "type" in msg) {
455
+ content = String(msg.content);
456
+ const type = String(msg.type);
457
+ if (type === "human") messageClass = HumanMessage;
458
+ else if (type === "ai") messageClass = AIMessage;
459
+ else if (type === "system") messageClass = SystemMessage;
460
+ else continue;
461
+ } else {
462
+ continue;
463
+ }
464
+ const key = `${messageClass.name}:${content}`;
465
+ if (!existingContent.has(key)) {
466
+ this.smartMemory.addMessage(new messageClass(content));
467
+ existingContent.add(key);
468
+ }
469
+ }
470
+ }
471
+ async boot() {
472
+ this.logger.info("🚨🚨🚨 LANGCHAIN AGENT BOOT METHOD CALLED 🚨🚨🚨");
473
+ if (this.initialized) {
474
+ this.logger.warn("Agent already initialized");
475
+ return;
476
+ }
100
477
  try {
101
- const parsed = JSON.parse(toolOutput);
102
- if (ResponseFormatter.isHashLinkResponse(parsed)) {
103
- return ResponseFormatter.formatHashLinkResponse(parsed);
478
+ this.agentKit = await this.createAgentKit();
479
+ await this.agentKit.initialize();
480
+ const modelName = this.config.ai?.modelName || process.env.OPENAI_MODEL_NAME || "gpt-4o-mini";
481
+ try {
482
+ if (typeof TokenUsageCallbackHandler === "function") {
483
+ this.tokenTracker = new TokenUsageCallbackHandler(modelName);
484
+ } else {
485
+ this.logger.warn("TokenUsageCallbackHandler unavailable or not a constructor; skipping token tracking");
486
+ }
487
+ } catch {
488
+ this.logger.warn("TokenUsageCallbackHandler threw; skipping token tracking");
489
+ }
490
+ this.toolRegistry = new ToolRegistry(this.logger);
491
+ const allTools = this.agentKit.getAggregatedLangChainTools();
492
+ this.logger.info("=== TOOL REGISTRATION START ===");
493
+ this.logger.info(
494
+ "All tools from agentKit:",
495
+ allTools.map((t) => t.name)
496
+ );
497
+ const filteredTools = this.filterTools(allTools);
498
+ this.logger.info(
499
+ "Filtered tools for registration:",
500
+ filteredTools.map((t) => t.name)
501
+ );
502
+ for (const tool of filteredTools) {
503
+ this.logger.info(`🔧 Registering tool: ${tool.name}`);
504
+ const options = {};
505
+ const name = tool.name.toLowerCase();
506
+ const desc = tool.description?.toLowerCase() || "";
507
+ if (tool.name === "hedera-hts-mint-nft") {
508
+ const originalCall = tool.call.bind(tool);
509
+ tool.call = async (args) => {
510
+ if (args.metaOptions && typeof args.metaOptions === "object") {
511
+ const metaOptions = args.metaOptions;
512
+ if (metaOptions.transactionMemo) {
513
+ console.warn(
514
+ "🚨 WORKAROUND: Stripping transactionMemo from hedera-hts-mint-nft to avoid bug",
515
+ { originalMemo: metaOptions.transactionMemo }
516
+ );
517
+ delete metaOptions.transactionMemo;
518
+ }
519
+ }
520
+ return originalCall(args);
521
+ };
522
+ }
523
+ if (name.includes("inscribe") || name.includes("hashinal") || desc.includes("inscribe") || desc.includes("hashinal")) {
524
+ options.forceWrapper = true;
525
+ options.metadata = {
526
+ category: "core",
527
+ version: "1.0.0",
528
+ dependencies: []
529
+ };
530
+ this.logger.info(`🎯 CRITICAL TOOL DEBUG - ${tool.name} schema:`, {
531
+ hasSchema: !!tool.schema,
532
+ schemaType: tool.schema?.constructor?.name,
533
+ hasRenderConfig: !!tool.schema?._renderConfig,
534
+ renderConfig: tool.schema?._renderConfig
535
+ });
536
+ }
537
+ this.toolRegistry.registerTool(tool, options);
538
+ }
539
+ this.tools = this.toolRegistry.getAllTools();
540
+ this.logger.info(`🚀 TOOLS REGISTERED: ${this.tools.length} tools`);
541
+ const stats = this.toolRegistry.getStatistics();
542
+ this.logger.info("📊 Tool Registry Statistics:", {
543
+ total: stats.totalTools,
544
+ wrapped: stats.wrappedTools,
545
+ unwrapped: stats.unwrappedTools,
546
+ categories: stats.categoryCounts,
547
+ priorities: stats.priorityCounts
548
+ });
549
+ const inscriptionTool = this.getInscriptionTool();
550
+ if (inscriptionTool) {
551
+ const entry = this.toolRegistry.getTool(inscriptionTool.name);
552
+ if (entry) {
553
+ this.logger.info(
554
+ `✅ Inscription tool registered: ${inscriptionTool.name}`
555
+ );
556
+ }
557
+ }
558
+ const toolNames = this.toolRegistry.getToolNames();
559
+ const uniqueNames = new Set(toolNames);
560
+ if (toolNames.length !== uniqueNames.size) {
561
+ this.logger.error("DUPLICATE TOOL NAMES DETECTED in registry!");
562
+ const duplicates = toolNames.filter(
563
+ (name, index) => toolNames.indexOf(name) !== index
564
+ );
565
+ throw new Error(
566
+ `Duplicate tool names detected: ${duplicates.join(", ")}`
567
+ );
104
568
  }
105
- if (ResponseFormatter.isInscriptionResponse(parsed)) {
106
- return ResponseFormatter.formatInscriptionResponse(parsed);
569
+ if (this.config.mcp?.servers && this.config.mcp.servers.length > 0) {
570
+ if (this.config.mcp.autoConnect !== false) {
571
+ await this.initializeMCP();
572
+ } else {
573
+ this.logger.info(
574
+ "MCP servers configured but autoConnect=false, skipping synchronous connection"
575
+ );
576
+ this.mcpManager = new MCPClientManager(this.logger);
577
+ }
578
+ }
579
+ this.smartMemory = new SmartMemoryManager({
580
+ modelName,
581
+ maxTokens: 9e4,
582
+ reserveTokens: 1e4,
583
+ storageLimit: 1e3
584
+ });
585
+ this.logger.info("SmartMemoryManager initialized:", {
586
+ modelName,
587
+ toolsCount: this.tools.length,
588
+ maxTokens: 9e4,
589
+ reserveTokens: 1e4
590
+ });
591
+ this.formEngine = new FormEngine(this.logger);
592
+ this.executionPipeline = new ExecutionPipeline(
593
+ this.toolRegistry,
594
+ this.formEngine,
595
+ this.smartMemory,
596
+ this.logger
597
+ );
598
+ this.systemMessage = this.buildSystemPrompt();
599
+ this.smartMemory.setSystemPrompt(this.systemMessage);
600
+ await this.createExecutor();
601
+ this.initialized = true;
602
+ this.logger.info("LangChain Hedera agent initialized with ToolRegistry");
603
+ } catch (error) {
604
+ this.logger.error("Failed to initialize agent:", error);
605
+ throw error;
606
+ }
607
+ }
608
+ async chat(message, context) {
609
+ if (!this.initialized || !this.executor || !this.smartMemory) {
610
+ throw new Error("Agent not initialized. Call boot() first.");
611
+ }
612
+ try {
613
+ const toolExecutionResult = await this.handleToolExecution(
614
+ message,
615
+ context
616
+ );
617
+ if (toolExecutionResult) {
618
+ return toolExecutionResult;
107
619
  }
108
- return toolOutput;
620
+ const directToolResult = await this.handleDirectToolExecution(message);
621
+ if (directToolResult) {
622
+ return directToolResult;
623
+ }
624
+ const jsonToolResult = await this.handleJsonToolCalls(message, context);
625
+ if (jsonToolResult) {
626
+ return jsonToolResult;
627
+ }
628
+ const contentRefResult = await this.handleContentRefMessages(message);
629
+ if (contentRefResult) {
630
+ return contentRefResult;
631
+ }
632
+ this.logger.info("LangChainAgent.chat called with:", {
633
+ message,
634
+ contextLength: context?.messages?.length || 0
635
+ });
636
+ this.loadContextMessages(context);
637
+ this.smartMemory.addMessage(new HumanMessage(message));
638
+ const memoryStats = this.smartMemory.getMemoryStats();
639
+ this.logger.info("Memory stats before execution:", {
640
+ totalMessages: memoryStats.totalActiveMessages,
641
+ currentTokens: memoryStats.currentTokenCount,
642
+ maxTokens: memoryStats.maxTokens,
643
+ usagePercentage: memoryStats.usagePercentage,
644
+ toolsCount: this.tools.length
645
+ });
646
+ const currentMessages = this.smartMemory.getMessages();
647
+ this.logger.info("Current messages in memory:", {
648
+ count: currentMessages.length
649
+ });
650
+ try {
651
+ const instr = currentMessages.map((m) => String(m.content || "")).filter(
652
+ (c) => typeof c === "string" && (c.includes("[instruction:") || c.includes("[tool-next-steps:"))
653
+ );
654
+ if (instr.length > 0) {
655
+ this.logger.info("Instruction/next-steps messages in memory:", {
656
+ messages: instr
657
+ });
658
+ }
659
+ } catch {
660
+ }
661
+ const result = await this.executor.invoke({
662
+ input: message,
663
+ chat_history: currentMessages
664
+ });
665
+ this.logger.info("LangChainAgent executor result:", result);
666
+ return this.processExecutorResult(result);
667
+ } catch (error) {
668
+ this.logger.error("LangChainAgent.chat error:", error);
669
+ return this.handleError(error);
670
+ }
671
+ }
672
+ async shutdown() {
673
+ if (this.mcpManager) {
674
+ await this.mcpManager.disconnectAll();
675
+ }
676
+ if (this.smartMemory) {
677
+ this.smartMemory.dispose();
678
+ this.smartMemory = void 0;
679
+ }
680
+ if (this.toolRegistry) {
681
+ this.toolRegistry.clear();
682
+ }
683
+ this.executor = void 0;
684
+ this.agentKit = void 0;
685
+ this.tools = [];
686
+ this.initialized = false;
687
+ this.logger.info("Agent cleaned up");
688
+ }
689
+ switchMode(mode) {
690
+ if (this.config.execution) {
691
+ this.config.execution.operationalMode = mode;
692
+ } else {
693
+ this.config.execution = { operationalMode: mode };
694
+ }
695
+ if (this.agentKit) {
696
+ this.agentKit.operationalMode = mode;
697
+ }
698
+ this.systemMessage = this.buildSystemPrompt();
699
+ this.logger.info(`Operational mode switched to: ${mode}`);
700
+ }
701
+ getUsageStats() {
702
+ if (!this.tokenTracker) {
703
+ return {
704
+ promptTokens: 0,
705
+ completionTokens: 0,
706
+ totalTokens: 0,
707
+ cost: { totalCost: 0 }
708
+ };
709
+ }
710
+ const usage = this.tokenTracker.getTotalTokenUsage();
711
+ const cost = calculateTokenCostSync(usage);
712
+ return { ...usage, cost };
713
+ }
714
+ getUsageLog() {
715
+ if (!this.tokenTracker) {
716
+ return [];
717
+ }
718
+ return this.tokenTracker.getTokenUsageHistory().map((usage) => ({
719
+ ...usage,
720
+ cost: calculateTokenCostSync(usage)
721
+ }));
722
+ }
723
+ clearUsageStats() {
724
+ if (this.tokenTracker) {
725
+ this.tokenTracker.reset();
726
+ this.logger.info("Usage statistics cleared");
727
+ }
728
+ }
729
+ getMCPConnectionStatus() {
730
+ return new Map(this.mcpConnectionStatus);
731
+ }
732
+ /**
733
+ * Processes form submission and continues with tool execution
734
+ */
735
+ async processFormSubmission(submission, context) {
736
+ if (!this.initialized || !this.executor || !this.smartMemory) {
737
+ throw new Error("Agent not initialized. Call boot() first.");
738
+ }
739
+ try {
740
+ if (!submission.parameters || typeof submission.parameters !== "object") {
741
+ this.logger.error("Invalid form submission parameters:", {
742
+ parameters: submission.parameters,
743
+ type: typeof submission.parameters
744
+ });
745
+ const errorInfo = JSON.stringify(submission, null, 2);
746
+ return this.handleError(
747
+ new Error(`Invalid form submission parameters: ${errorInfo}`)
748
+ );
749
+ }
750
+ this.loadContextMessages(context);
751
+ const safeSubmission = {
752
+ ...submission,
753
+ parameters: submission.parameters || {}
754
+ };
755
+ const result = await this.executor.processFormSubmission(safeSubmission);
756
+ const preservedMetadata = result?.metadata ? { ...result.metadata } : {};
757
+ try {
758
+ const maybeRaw = result.rawToolOutput;
759
+ const toolName = result.toolName || "unknown";
760
+ if (typeof maybeRaw === "string" && maybeRaw.trim().length > 0) {
761
+ const payload = this.isJSON(maybeRaw) ? maybeRaw : JSON.stringify({ output: maybeRaw });
762
+ this.addToolRawToMemory(toolName, payload);
763
+ }
764
+ } catch {
765
+ }
766
+ let outputMessage = "Form processed successfully.";
767
+ if (typeof result.output === "string") {
768
+ outputMessage = result.output;
769
+ } else if (result.output) {
770
+ try {
771
+ outputMessage = JSON.stringify(result.output);
772
+ } catch {
773
+ outputMessage = String(result.output);
774
+ }
775
+ }
776
+ let response = {
777
+ output: outputMessage,
778
+ message: outputMessage,
779
+ notes: [],
780
+ intermediateSteps: result.intermediateSteps
781
+ };
782
+ if (result.metadata) {
783
+ response.metadata = {
784
+ ...response.metadata,
785
+ ...result.metadata
786
+ };
787
+ this.logger.info("🔍 DEBUG: Metadata after merge from result:", {
788
+ hasMetadata: !!response.metadata,
789
+ metadataKeys: response.metadata ? Object.keys(response.metadata) : [],
790
+ hasHashLinkBlock: hasHashLinkBlock(response.metadata),
791
+ hashLinkBlockContent: hasHashLinkBlock(response.metadata) ? response.metadata.hashLinkBlock : void 0
792
+ });
793
+ }
794
+ if (result.requiresForm && result.formMessage) {
795
+ response.formMessage = result.formMessage;
796
+ response.requiresForm = true;
797
+ }
798
+ if (result.intermediateSteps && Array.isArray(result.intermediateSteps)) {
799
+ const toolCalls = result.intermediateSteps.map(
800
+ (step, index) => {
801
+ const name = step?.action?.tool || "unknown";
802
+ const args = step?.action?.toolInput || {};
803
+ const obs = step?.observation;
804
+ let output = "";
805
+ if (typeof obs === "string") {
806
+ output = obs;
807
+ } else if (obs && typeof obs === "object") {
808
+ try {
809
+ output = JSON.stringify(obs);
810
+ } catch {
811
+ output = String(obs);
812
+ }
813
+ } else if (obs !== void 0) {
814
+ output = String(obs);
815
+ }
816
+ return { id: `call_${index}`, name, args, output };
817
+ }
818
+ );
819
+ if (toolCalls.length > 0) {
820
+ response.tool_calls = toolCalls;
821
+ }
822
+ this.persistIntermediateSteps(
823
+ result.intermediateSteps
824
+ );
825
+ }
826
+ const parsedSteps = result?.intermediateSteps?.[0]?.observation;
827
+ if (parsedSteps && typeof parsedSteps === "string" && this.isJSON(parsedSteps)) {
828
+ try {
829
+ const parsed = JSON.parse(parsedSteps);
830
+ response = { ...response, ...parsed };
831
+ const blockMetadata = this.processHashLinkBlocks(parsed);
832
+ if (blockMetadata.hashLinkBlock) {
833
+ response.metadata = {
834
+ ...response.metadata,
835
+ ...blockMetadata
836
+ };
837
+ }
838
+ } catch (error) {
839
+ this.logger.error("Error parsing intermediate steps:", error);
840
+ }
841
+ }
842
+ if (response.output) {
843
+ this.smartMemory.addMessage(new AIMessage(response.output));
844
+ }
845
+ if (this.tokenTracker) {
846
+ const tokenUsage = this.tokenTracker.getLatestTokenUsage();
847
+ if (tokenUsage) {
848
+ response.tokenUsage = tokenUsage;
849
+ response.cost = calculateTokenCostSync(tokenUsage);
850
+ }
851
+ }
852
+ const finalMemoryStats = this.smartMemory.getMemoryStats();
853
+ this.logger.info("🔍 DEBUG: Metadata before memoryStats merge:", {
854
+ hasMetadata: !!response.metadata,
855
+ metadataKeys: response.metadata ? Object.keys(response.metadata) : [],
856
+ hasHashLinkBlock: hasHashLinkBlock(response.metadata)
857
+ });
858
+ response.metadata = {
859
+ ...preservedMetadata,
860
+ ...response.metadata,
861
+ memoryStats: {
862
+ activeMessages: finalMemoryStats.totalActiveMessages,
863
+ tokenUsage: finalMemoryStats.currentTokenCount,
864
+ maxTokens: finalMemoryStats.maxTokens,
865
+ usagePercentage: finalMemoryStats.usagePercentage
866
+ }
867
+ };
868
+ this.logger.info("🔍 DEBUG: Final response metadata before return:", {
869
+ hasMetadata: !!response.metadata,
870
+ metadataKeys: response.metadata ? Object.keys(response.metadata) : [],
871
+ hasHashLinkBlock: hasHashLinkBlock(response.metadata),
872
+ fullMetadata: response.metadata
873
+ });
874
+ if (hasHashLinkBlock(preservedMetadata) && !hasHashLinkBlock(response.metadata)) {
875
+ this.logger.error(
876
+ "❌ CRITICAL: HashLink metadata was lost during processing!"
877
+ );
878
+ this.logger.error(
879
+ "Original metadata had hashLinkBlock:",
880
+ preservedMetadata.hashLinkBlock
881
+ );
882
+ this.logger.error("Final metadata missing hashLinkBlock");
883
+ }
884
+ return response;
885
+ } catch (error) {
886
+ this.logger.error("Form submission processing error:", error);
887
+ return this.handleError(error);
888
+ }
889
+ }
890
+ /**
891
+ * Check if the agent has pending forms that need to be completed
892
+ */
893
+ hasPendingForms() {
894
+ return this.executor ? this.executor.hasPendingForms() : false;
895
+ }
896
+ /**
897
+ * Get information about pending forms
898
+ */
899
+ getPendingFormsInfo() {
900
+ return this.executor ? this.executor.getPendingFormsInfo() : [];
901
+ }
902
+ async createAgentKit() {
903
+ const corePlugins = getAllHederaCorePlugins();
904
+ const extensionPlugins = this.config.extensions?.plugins || [];
905
+ const plugins = [...corePlugins, ...extensionPlugins];
906
+ const operationalMode = this.config.execution?.operationalMode || "returnBytes";
907
+ const modelName = this.config.ai?.modelName || "gpt-4o";
908
+ return new HederaAgentKit(
909
+ this.config.signer,
910
+ { plugins },
911
+ operationalMode,
912
+ this.config.execution?.userAccountId,
913
+ this.config.execution?.scheduleUserTransactionsInBytesMode ?? false,
914
+ void 0,
915
+ modelName,
916
+ this.config.extensions?.mirrorConfig,
917
+ this.config.debug?.silent ?? false
918
+ );
919
+ }
920
+ async createExecutor() {
921
+ const existingPendingForms = this.executor?.getPendingForms() || /* @__PURE__ */ new Map();
922
+ let llm;
923
+ if (this.config.ai?.provider && this.config.ai.provider.getModel) {
924
+ llm = this.config.ai.provider.getModel();
925
+ } else if (this.config.ai?.llm) {
926
+ llm = this.config.ai.llm;
927
+ } else {
928
+ const apiKey = this.config.ai?.apiKey || process.env.OPENAI_API_KEY;
929
+ if (!apiKey) {
930
+ throw new Error("OpenAI API key required");
931
+ }
932
+ const modelName = this.config.ai?.modelName || "gpt-4o-mini";
933
+ const isGPT5Model = modelName.toLowerCase().includes("gpt-5") || modelName.toLowerCase().includes("gpt5");
934
+ llm = new ChatOpenAI({
935
+ apiKey,
936
+ modelName,
937
+ callbacks: this.tokenTracker ? [this.tokenTracker] : [],
938
+ ...isGPT5Model ? { temperature: 1 } : {}
939
+ });
940
+ }
941
+ const prompt = ChatPromptTemplate.fromMessages([
942
+ ["system", this.systemMessage],
943
+ new MessagesPlaceholder("chat_history"),
944
+ ["human", "{input}"],
945
+ new MessagesPlaceholder("agent_scratchpad")
946
+ ]);
947
+ const langchainTools = this.tools;
948
+ const inscriptionTool = this.getInscriptionTool();
949
+ if (inscriptionTool) {
950
+ const entry = this.toolRegistry.getTool(inscriptionTool.name);
951
+ if (entry) {
952
+ this.logger.info(
953
+ `✅ Inscription tool registered: ${inscriptionTool.name}`
954
+ );
955
+ }
956
+ }
957
+ const stats = this.toolRegistry.getStatistics();
958
+ this.logger.info("🛡️ TOOL SECURITY REPORT:", {
959
+ totalTools: stats.totalTools,
960
+ wrappedTools: stats.wrappedTools,
961
+ unwrappedTools: stats.unwrappedTools,
962
+ categories: stats.categoryCounts,
963
+ priorities: stats.priorityCounts
964
+ });
965
+ this.logger.info(
966
+ `📊 Tool Security Summary: ${stats.wrappedTools} wrapped, ${stats.unwrappedTools} unwrapped`
967
+ );
968
+ const agent = await createOpenAIToolsAgent({
969
+ llm,
970
+ tools: langchainTools,
971
+ prompt
972
+ });
973
+ this.executor = new FormAwareAgentExecutor({
974
+ agent,
975
+ tools: langchainTools,
976
+ verbose: this.config.debug?.verbose ?? false,
977
+ returnIntermediateSteps: true
978
+ });
979
+ if (this.pendingParameterPreprocessingCallback) {
980
+ this.executor.setParameterPreprocessingCallback(
981
+ this.pendingParameterPreprocessingCallback
982
+ );
983
+ this.logger.info(
984
+ "Parameter preprocessing callback re-applied to new executor",
985
+ { hasCallback: true }
986
+ );
987
+ }
988
+ if (existingPendingForms.size > 0) {
989
+ this.logger.info(
990
+ `Restoring ${existingPendingForms.size} pending forms to new executor`
991
+ );
992
+ this.executor.restorePendingForms(existingPendingForms);
993
+ }
994
+ this.logger.info("FormAwareAgentExecutor initialization complete");
995
+ }
996
+ /**
997
+ * Set parameter preprocessing callback for tool parameter format conversion
998
+ */
999
+ setParameterPreprocessingCallback(callback) {
1000
+ this.pendingParameterPreprocessingCallback = callback;
1001
+ if (this.executor) {
1002
+ this.executor.setParameterPreprocessingCallback(callback);
1003
+ this.logger.info("Parameter preprocessing callback configured", {
1004
+ hasCallback: !!callback
1005
+ });
1006
+ } else {
1007
+ this.logger.warn(
1008
+ "Cannot set parameter preprocessing callback: executor not initialized"
1009
+ );
1010
+ }
1011
+ }
1012
+ handleError(error) {
1013
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
1014
+ this.logger.error("Chat error:", error);
1015
+ let tokenUsage;
1016
+ let cost;
1017
+ if (this.tokenTracker) {
1018
+ tokenUsage = this.tokenTracker.getLatestTokenUsage();
1019
+ if (tokenUsage) {
1020
+ cost = calculateTokenCostSync(tokenUsage);
1021
+ }
1022
+ }
1023
+ let userFriendlyMessage = errorMessage;
1024
+ let userFriendlyOutput = errorMessage;
1025
+ if (errorMessage.includes("429")) {
1026
+ if (errorMessage.includes("quota")) {
1027
+ userFriendlyMessage = "API quota exceeded. Please check your OpenAI billing and usage limits.";
1028
+ userFriendlyOutput = "I'm currently unable to respond because the API quota has been exceeded. Please check your OpenAI account billing and usage limits, then try again.";
1029
+ } else {
1030
+ userFriendlyMessage = ERROR_MESSAGES.TOO_MANY_REQUESTS;
1031
+ userFriendlyOutput = ERROR_MESSAGES.RATE_LIMITED;
1032
+ }
1033
+ } else if (errorMessage.includes("401") || errorMessage.includes("unauthorized")) {
1034
+ userFriendlyMessage = "API authentication failed. Please check your API key configuration.";
1035
+ userFriendlyOutput = "There's an issue with the API authentication. Please check your OpenAI API key configuration in settings.";
1036
+ } else if (errorMessage.includes("timeout")) {
1037
+ userFriendlyMessage = "Request timed out. Please try again.";
1038
+ userFriendlyOutput = "The request took too long to process. Please try again.";
1039
+ } else if (errorMessage.includes("network") || errorMessage.includes("fetch")) {
1040
+ userFriendlyMessage = "Network error. Please check your internet connection and try again.";
1041
+ userFriendlyOutput = "There was a network error. Please check your internet connection and try again.";
1042
+ } else if (errorMessage.includes("400")) {
1043
+ userFriendlyMessage = errorMessage;
1044
+ userFriendlyOutput = errorMessage;
1045
+ }
1046
+ const errorResponse = {
1047
+ output: userFriendlyOutput,
1048
+ message: userFriendlyMessage,
1049
+ error: errorMessage,
1050
+ notes: []
1051
+ };
1052
+ if (tokenUsage) {
1053
+ errorResponse.tokenUsage = tokenUsage;
1054
+ }
1055
+ if (cost) {
1056
+ errorResponse.cost = cost;
1057
+ }
1058
+ return errorResponse;
1059
+ }
1060
+ async initializeMCP() {
1061
+ this.mcpManager = new MCPClientManager(this.logger);
1062
+ for (const serverConfig of this.config.mcp.servers) {
1063
+ if (serverConfig.autoConnect === false) {
1064
+ this.logger.info(
1065
+ `Skipping MCP server ${serverConfig.name} (autoConnect=false)`
1066
+ );
1067
+ continue;
1068
+ }
1069
+ const status = await this.mcpManager.connectServer(serverConfig);
1070
+ if (status.connected) {
1071
+ this.logger.info(
1072
+ `Connected to MCP server ${status.serverName} with ${status.tools.length} tools`
1073
+ );
1074
+ for (const mcpTool of status.tools) {
1075
+ const langchainTool = convertMCPToolToLangChain(
1076
+ mcpTool,
1077
+ this.mcpManager,
1078
+ serverConfig
1079
+ );
1080
+ this.toolRegistry.registerTool(langchainTool, {
1081
+ metadata: {
1082
+ category: "mcp",
1083
+ version: "1.0.0",
1084
+ dependencies: [serverConfig.name]
1085
+ }
1086
+ });
1087
+ }
1088
+ this.tools = this.toolRegistry.getAllTools();
1089
+ } else {
1090
+ this.logger.error(
1091
+ `Failed to connect to MCP server ${status.serverName}: ${status.error}`
1092
+ );
1093
+ }
1094
+ }
1095
+ }
1096
+ /**
1097
+ * Connect to MCP servers asynchronously after agent boot with background timeout pattern
1098
+ */
1099
+ async connectMCPServers() {
1100
+ if (!this.config.mcp?.servers || this.config.mcp.servers.length === 0) {
1101
+ return;
1102
+ }
1103
+ if (!this.mcpManager) {
1104
+ this.mcpManager = new MCPClientManager(this.logger);
1105
+ }
1106
+ this.logger.info(
1107
+ `Starting background MCP server connections for ${this.config.mcp.servers.length} servers...`
1108
+ );
1109
+ this.config.mcp.servers.forEach((serverConfig) => {
1110
+ this.connectServerInBackground(serverConfig);
1111
+ });
1112
+ this.logger.info("MCP server connections initiated in background");
1113
+ }
1114
+ /**
1115
+ * Connect to a single MCP server in background with timeout
1116
+ */
1117
+ connectServerInBackground(serverConfig) {
1118
+ const serverName = serverConfig.name;
1119
+ setTimeout(async () => {
1120
+ try {
1121
+ this.logger.info(`Background connecting to MCP server: ${serverName}`);
1122
+ const status = await this.mcpManager.connectServer(serverConfig);
1123
+ this.mcpConnectionStatus.set(serverName, status);
1124
+ if (status.connected) {
1125
+ this.logger.info(
1126
+ `Successfully connected to MCP server ${status.serverName} with ${status.tools.length} tools`
1127
+ );
1128
+ for (const mcpTool of status.tools) {
1129
+ const langchainTool = convertMCPToolToLangChain(
1130
+ mcpTool,
1131
+ this.mcpManager,
1132
+ serverConfig
1133
+ );
1134
+ this.toolRegistry.registerTool(langchainTool, {
1135
+ metadata: {
1136
+ category: "mcp",
1137
+ version: "1.0.0",
1138
+ dependencies: [serverConfig.name]
1139
+ }
1140
+ });
1141
+ }
1142
+ this.tools = this.toolRegistry.getAllTools();
1143
+ if (this.initialized && this.executor) {
1144
+ this.logger.info(
1145
+ `Recreating executor with ${this.tools.length} total tools`
1146
+ );
1147
+ await this.createExecutor();
1148
+ }
1149
+ } else {
1150
+ this.logger.error(
1151
+ `Failed to connect to MCP server ${status.serverName}: ${status.error}`
1152
+ );
1153
+ }
1154
+ } catch (error) {
1155
+ this.logger.error(
1156
+ `Background connection failed for MCP server ${serverName}:`,
1157
+ error
1158
+ );
1159
+ this.mcpConnectionStatus.set(serverName, {
1160
+ connected: false,
1161
+ serverName,
1162
+ tools: [],
1163
+ error: error instanceof Error ? error.message : "Connection failed"
1164
+ });
1165
+ }
1166
+ }, 1e3);
1167
+ }
1168
+ /**
1169
+ * Detects and processes HashLink blocks from tool responses
1170
+ * @param parsedResponse - The parsed JSON response from a tool
1171
+ * @returns Metadata object containing hashLinkBlock if detected
1172
+ */
1173
+ processHashLinkBlocks(parsedResponse) {
1174
+ try {
1175
+ const responseRecord = parsedResponse;
1176
+ if (parsedResponse && typeof parsedResponse === "object" && responseRecord.hashLinkBlock && typeof responseRecord.hashLinkBlock === "object") {
1177
+ const block = responseRecord.hashLinkBlock;
1178
+ if (block.blockId && block.hashLink && block.template && block.attributes && typeof block.blockId === "string" && typeof block.hashLink === "string" && typeof block.template === "string" && typeof block.attributes === "object") {
1179
+ this.logger.info("HashLink block detected:", {
1180
+ blockId: block.blockId,
1181
+ hashLink: block.hashLink,
1182
+ template: block.template,
1183
+ attributeKeys: Object.keys(block.attributes)
1184
+ });
1185
+ return {
1186
+ hashLinkBlock: {
1187
+ blockId: block.blockId,
1188
+ hashLink: block.hashLink,
1189
+ template: block.template,
1190
+ attributes: block.attributes
1191
+ }
1192
+ };
1193
+ } else {
1194
+ this.logger.warn("Invalid HashLink block structure detected:", block);
1195
+ }
1196
+ }
1197
+ } catch (error) {
1198
+ this.logger.error("Error processing HashLink blocks:", error);
1199
+ }
1200
+ return {};
1201
+ }
1202
+ /**
1203
+ * Check if a string is valid JSON
1204
+ */
1205
+ isJSON(str) {
1206
+ if (typeof str !== "string") return false;
1207
+ const trimmed = str.trim();
1208
+ if (!trimmed) return false;
1209
+ if (!(trimmed.startsWith("{") && trimmed.endsWith("}")) && !(trimmed.startsWith("[") && trimmed.endsWith("]"))) {
1210
+ return false;
1211
+ }
1212
+ try {
1213
+ JSON.parse(trimmed);
1214
+ return true;
109
1215
  } catch {
110
- return toolOutput;
1216
+ return false;
111
1217
  }
112
1218
  }
113
1219
  }
114
1220
  export {
115
- ResponseFormatter
1221
+ LangChainAgent
116
1222
  };
117
1223
  //# sourceMappingURL=index33.js.map