@hashgraphonline/conversational-agent 0.1.214 → 0.1.217
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli/dist/CLIApp.d.ts +9 -0
- package/cli/dist/CLIApp.js +127 -0
- package/cli/dist/LocalConversationalAgent.d.ts +37 -0
- package/cli/dist/LocalConversationalAgent.js +58 -0
- package/cli/dist/app.d.ts +16 -0
- package/cli/dist/app.js +13 -0
- package/cli/dist/cli.d.ts +2 -0
- package/cli/dist/cli.js +51 -0
- package/cli/dist/components/AppContainer.d.ts +16 -0
- package/cli/dist/components/AppContainer.js +24 -0
- package/cli/dist/components/AppScreens.d.ts +2 -0
- package/cli/dist/components/AppScreens.js +259 -0
- package/cli/dist/components/ChatScreen.d.ts +15 -0
- package/cli/dist/components/ChatScreen.js +39 -0
- package/cli/dist/components/DebugLoadingScreen.d.ts +5 -0
- package/cli/dist/components/DebugLoadingScreen.js +31 -0
- package/cli/dist/components/LoadingScreen.d.ts +2 -0
- package/cli/dist/components/LoadingScreen.js +16 -0
- package/cli/dist/components/LoadingScreenDebug.d.ts +5 -0
- package/cli/dist/components/LoadingScreenDebug.js +27 -0
- package/cli/dist/components/MCPConfigScreen.d.ts +28 -0
- package/cli/dist/components/MCPConfigScreen.js +168 -0
- package/cli/dist/components/ScreenRouter.d.ts +12 -0
- package/cli/dist/components/ScreenRouter.js +22 -0
- package/cli/dist/components/SetupScreen.d.ts +15 -0
- package/cli/dist/components/SetupScreen.js +65 -0
- package/cli/dist/components/SingleLoadingScreen.d.ts +5 -0
- package/cli/dist/components/SingleLoadingScreen.js +27 -0
- package/cli/dist/components/StatusBadge.d.ts +7 -0
- package/cli/dist/components/StatusBadge.js +28 -0
- package/cli/dist/components/TerminalWindow.d.ts +8 -0
- package/cli/dist/components/TerminalWindow.js +24 -0
- package/cli/dist/components/WelcomeScreen.d.ts +11 -0
- package/cli/dist/components/WelcomeScreen.js +47 -0
- package/cli/dist/context/AppContext.d.ts +68 -0
- package/cli/dist/context/AppContext.js +363 -0
- package/cli/dist/hooks/useInitializeAgent.d.ts +19 -0
- package/cli/dist/hooks/useInitializeAgent.js +28 -0
- package/cli/dist/hooks/useStableState.d.ts +38 -0
- package/cli/dist/hooks/useStableState.js +68 -0
- package/cli/dist/managers/AgentManager.d.ts +57 -0
- package/cli/dist/managers/AgentManager.js +119 -0
- package/cli/dist/managers/ConfigManager.d.ts +53 -0
- package/cli/dist/managers/ConfigManager.js +173 -0
- package/cli/dist/types.d.ts +31 -0
- package/cli/dist/types.js +19 -0
- package/dist/cjs/base-agent.d.ts +2 -0
- package/dist/cjs/conversational-agent.d.ts +8 -0
- package/dist/cjs/core/ToolRegistry.d.ts +130 -0
- package/dist/cjs/execution/ExecutionPipeline.d.ts +81 -0
- package/dist/cjs/forms/FormEngine.d.ts +121 -0
- package/dist/cjs/forms/field-type-registry.d.ts +51 -0
- package/dist/cjs/forms/form-generator.d.ts +123 -0
- package/dist/cjs/forms/index.d.ts +2 -0
- package/dist/cjs/forms/types.d.ts +108 -0
- package/dist/cjs/index.cjs +1 -1
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/index.d.ts +5 -0
- package/dist/cjs/langchain/FormAwareAgentExecutor.d.ts +108 -0
- package/dist/cjs/langchain/FormValidatingToolWrapper.d.ts +81 -0
- package/dist/cjs/langchain-agent.d.ts +65 -0
- package/dist/cjs/memory/ContentStorage.d.ts +7 -0
- package/dist/cjs/memory/SmartMemoryManager.d.ts +1 -0
- package/dist/cjs/services/ContentStoreManager.d.ts +11 -1
- package/dist/cjs/utils/ResponseFormatter.d.ts +26 -0
- package/dist/esm/index.js +8 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/index12.js +1 -1
- package/dist/esm/index12.js.map +1 -1
- package/dist/esm/index14.js +23 -5
- package/dist/esm/index14.js.map +1 -1
- package/dist/esm/index15.js +25 -4
- package/dist/esm/index15.js.map +1 -1
- package/dist/esm/index16.js +4 -2
- package/dist/esm/index16.js.map +1 -1
- package/dist/esm/index17.js +2 -7
- package/dist/esm/index17.js.map +1 -1
- package/dist/esm/index18.js +609 -36
- package/dist/esm/index18.js.map +1 -1
- package/dist/esm/index19.js +229 -84
- package/dist/esm/index19.js.map +1 -1
- package/dist/esm/index20.js +111 -17
- package/dist/esm/index20.js.map +1 -1
- package/dist/esm/index21.js +44 -7
- package/dist/esm/index21.js.map +1 -1
- package/dist/esm/index22.js +86 -157
- package/dist/esm/index22.js.map +1 -1
- package/dist/esm/index23.js +32 -150
- package/dist/esm/index23.js.map +1 -1
- package/dist/esm/index24.js +746 -80
- package/dist/esm/index24.js.map +1 -1
- package/dist/esm/index25.js +154 -45
- package/dist/esm/index25.js.map +1 -1
- package/dist/esm/index26.js +149 -24
- package/dist/esm/index26.js.map +1 -1
- package/dist/esm/index27.js +196 -217
- package/dist/esm/index27.js.map +1 -1
- package/dist/esm/index28.js +187 -0
- package/dist/esm/index28.js.map +1 -0
- package/dist/esm/index29.js +308 -0
- package/dist/esm/index29.js.map +1 -0
- package/dist/esm/index30.js +159 -0
- package/dist/esm/index30.js.map +1 -0
- package/dist/esm/index31.js +68 -0
- package/dist/esm/index31.js.map +1 -0
- package/dist/esm/index32.js +30 -0
- package/dist/esm/index32.js.map +1 -0
- package/dist/esm/index33.js +95 -0
- package/dist/esm/index33.js.map +1 -0
- package/dist/esm/index34.js +245 -0
- package/dist/esm/index34.js.map +1 -0
- package/dist/esm/index5.js +2 -2
- package/dist/esm/index5.js.map +1 -1
- package/dist/esm/index6.js +68 -25
- package/dist/esm/index6.js.map +1 -1
- package/dist/esm/index7.js.map +1 -1
- package/dist/esm/index8.js +744 -70
- package/dist/esm/index8.js.map +1 -1
- package/dist/types/base-agent.d.ts +2 -0
- package/dist/types/conversational-agent.d.ts +8 -0
- package/dist/types/core/ToolRegistry.d.ts +130 -0
- package/dist/types/execution/ExecutionPipeline.d.ts +81 -0
- package/dist/types/forms/FormEngine.d.ts +121 -0
- package/dist/types/forms/field-type-registry.d.ts +51 -0
- package/dist/types/forms/form-generator.d.ts +123 -0
- package/dist/types/forms/index.d.ts +2 -0
- package/dist/types/forms/types.d.ts +108 -0
- package/dist/types/index.d.ts +5 -0
- package/dist/types/langchain/FormAwareAgentExecutor.d.ts +108 -0
- package/dist/types/langchain/FormValidatingToolWrapper.d.ts +81 -0
- package/dist/types/langchain-agent.d.ts +65 -0
- package/dist/types/memory/ContentStorage.d.ts +7 -0
- package/dist/types/memory/SmartMemoryManager.d.ts +1 -0
- package/dist/types/services/ContentStoreManager.d.ts +11 -1
- package/dist/types/utils/ResponseFormatter.d.ts +26 -0
- package/package.json +35 -34
- package/src/base-agent.ts +2 -0
- package/src/config/system-message.ts +14 -0
- package/src/context/ReferenceContextManager.ts +1 -1
- package/src/conversational-agent.ts +95 -38
- package/src/core/ToolRegistry.ts +358 -0
- package/src/execution/ExecutionPipeline.ts +301 -0
- package/src/forms/FormEngine.ts +443 -0
- package/src/forms/field-type-registry.ts +203 -0
- package/src/forms/form-generator.ts +841 -0
- package/src/forms/index.ts +2 -0
- package/src/forms/types.ts +125 -0
- package/src/index.ts +9 -0
- package/src/langchain/FormAwareAgentExecutor.ts +971 -0
- package/src/langchain/FormValidatingToolWrapper.ts +355 -0
- package/src/langchain-agent.ts +1034 -87
- package/src/mcp/ContentProcessor.ts +20 -4
- package/src/mcp/MCPClientManager.ts +1 -1
- package/src/mcp/adapters/langchain.ts +1 -1
- package/src/memory/ContentStorage.ts +25 -5
- package/src/memory/SmartMemoryManager.ts +27 -4
- package/src/memory/TokenCounter.ts +1 -1
- package/src/plugins/hbar/HbarPlugin.ts +0 -1
- package/src/scripts/test-external-tool-wrapper.ts +103 -0
- package/src/scripts/test-hedera-kit-wrapper.ts +265 -0
- package/src/scripts/test-inscribe-form-generation.ts +494 -0
- package/src/scripts/test-inscribe-wrapper-verification.ts +220 -0
- package/src/services/ContentStoreManager.ts +23 -9
- package/src/services/EntityResolver.ts +2 -9
- package/src/tools/EntityResolverTool.ts +5 -8
- package/src/utils/ResponseFormatter.ts +146 -0
- package/cli/readme.md +0 -181
- package/dist/cjs/langchain/ContentAwareAgentExecutor.d.ts +0 -14
- package/dist/types/langchain/ContentAwareAgentExecutor.d.ts +0 -14
- package/src/langchain/ContentAwareAgentExecutor.ts +0 -19
|
@@ -0,0 +1,187 @@
|
|
|
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" });
|
|
9
|
+
}
|
|
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
|
+
};
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
export {
|
|
185
|
+
ExecutionPipeline
|
|
186
|
+
};
|
|
187
|
+
//# sourceMappingURL=index28.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index28.js","sources":["../../src/execution/ExecutionPipeline.ts"],"sourcesContent":["import { ZodError } from 'zod';\nimport { Logger } from '@hashgraphonline/standards-sdk';\nimport { SmartMemoryManager } from '../memory/SmartMemoryManager';\nimport { FormEngine, ToolExecutionResult } from '../forms/FormEngine';\nimport type { FormMessage, FormSubmission } from '../forms/types';\nimport type { ToolRegistry, ToolRegistryEntry } from '../core/ToolRegistry';\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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BAAsB,CAAA;AAAA,IAAC;AAAA,EAE3B;AACF;"}
|
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
import { ZodError } from "zod";
|
|
2
|
+
import { Logger } from "@hashgraphonline/standards-sdk";
|
|
3
|
+
import { FormGenerator } from "./index18.js";
|
|
4
|
+
import { isFormValidatable } from "@hashgraphonline/standards-agent-kit";
|
|
5
|
+
class FormEngine {
|
|
6
|
+
constructor(logger) {
|
|
7
|
+
this.formGenerator = new FormGenerator();
|
|
8
|
+
this.logger = logger || new Logger({ module: "FormEngine" });
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Generate a form for a tool with the given input
|
|
12
|
+
*/
|
|
13
|
+
async generateForm(toolName, tool, input, context) {
|
|
14
|
+
const fullContext = {
|
|
15
|
+
tool,
|
|
16
|
+
input,
|
|
17
|
+
...context
|
|
18
|
+
};
|
|
19
|
+
try {
|
|
20
|
+
if (isFormValidatable(tool)) {
|
|
21
|
+
return await this.generateFormValidatableForm(tool, input, fullContext);
|
|
22
|
+
}
|
|
23
|
+
if (input instanceof ZodError) {
|
|
24
|
+
return await this.generateErrorBasedForm(tool, input, fullContext);
|
|
25
|
+
}
|
|
26
|
+
if (this.hasRenderConfig(tool)) {
|
|
27
|
+
return await this.generateRenderConfigForm(tool, input, fullContext);
|
|
28
|
+
}
|
|
29
|
+
if (this.isZodObject(tool.schema)) {
|
|
30
|
+
return await this.generateSchemaBasedForm(tool, input, fullContext);
|
|
31
|
+
}
|
|
32
|
+
return null;
|
|
33
|
+
} catch (error) {
|
|
34
|
+
this.logger.error(`Failed to generate form for tool: ${toolName}`, {
|
|
35
|
+
error: error instanceof Error ? error.message : String(error)
|
|
36
|
+
});
|
|
37
|
+
throw error;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Process a form submission
|
|
42
|
+
*/
|
|
43
|
+
async processSubmission(submission, context) {
|
|
44
|
+
this.validateSubmission(submission);
|
|
45
|
+
const baseToolInput = this.extractBaseToolInput(context);
|
|
46
|
+
const submissionData = this.extractSubmissionData(submission);
|
|
47
|
+
return this.mergeInputData(baseToolInput, submissionData);
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Check if a tool requires form generation based on input
|
|
51
|
+
*/
|
|
52
|
+
shouldGenerateForm(tool, input) {
|
|
53
|
+
const inputRecord = input;
|
|
54
|
+
if (inputRecord?.__fromForm === true || inputRecord?.renderForm === false) {
|
|
55
|
+
return false;
|
|
56
|
+
}
|
|
57
|
+
if (isFormValidatable(tool)) {
|
|
58
|
+
try {
|
|
59
|
+
const formValidatableTool = tool;
|
|
60
|
+
return formValidatableTool.shouldGenerateForm(input);
|
|
61
|
+
} catch (error) {
|
|
62
|
+
this.logger.error(`Error calling shouldGenerateForm() on ${tool.name}:`, error);
|
|
63
|
+
return false;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
const validation = this.validateInput(tool, input);
|
|
67
|
+
return !validation.isValid;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Generate form from error context
|
|
71
|
+
*/
|
|
72
|
+
async generateFormFromError(error, toolName, toolSchema, originalPrompt) {
|
|
73
|
+
return this.formGenerator.generateFormFromError(
|
|
74
|
+
error,
|
|
75
|
+
toolSchema,
|
|
76
|
+
toolName,
|
|
77
|
+
originalPrompt
|
|
78
|
+
);
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Generate form for FormValidatable tools
|
|
82
|
+
*/
|
|
83
|
+
async generateFormValidatableForm(tool, input, _context) {
|
|
84
|
+
const { schemaToUse, isFocusedSchema } = this.resolveFormSchema(tool);
|
|
85
|
+
const missingFields = this.determineMissingFields(tool, input, schemaToUse, isFocusedSchema);
|
|
86
|
+
return this.generateFormWithSchema(tool, input, schemaToUse, missingFields);
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Generate form based on schema validation
|
|
90
|
+
*/
|
|
91
|
+
async generateSchemaBasedForm(tool, input, context) {
|
|
92
|
+
const schema = tool.schema;
|
|
93
|
+
const formMessage = await this.formGenerator.generateFormFromSchema(
|
|
94
|
+
schema,
|
|
95
|
+
input,
|
|
96
|
+
{
|
|
97
|
+
toolName: tool.name,
|
|
98
|
+
toolDescription: tool.description
|
|
99
|
+
},
|
|
100
|
+
context.missingFields
|
|
101
|
+
);
|
|
102
|
+
if (this.isZodObject(schema)) {
|
|
103
|
+
try {
|
|
104
|
+
const { jsonSchema, uiSchema } = this.formGenerator.generateJsonSchemaForm(
|
|
105
|
+
schema,
|
|
106
|
+
input,
|
|
107
|
+
context.missingFields || /* @__PURE__ */ new Set()
|
|
108
|
+
);
|
|
109
|
+
formMessage.jsonSchema = jsonSchema;
|
|
110
|
+
formMessage.uiSchema = uiSchema;
|
|
111
|
+
} catch (error) {
|
|
112
|
+
this.logger.warn("Failed to generate JSON Schema for schema-based tool:", error);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
formMessage.partialInput = input;
|
|
116
|
+
return formMessage;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Generate form based on render config
|
|
120
|
+
*/
|
|
121
|
+
async generateRenderConfigForm(tool, input, context) {
|
|
122
|
+
const schema = tool.schema;
|
|
123
|
+
const renderConfig = this.extractRenderConfig(tool);
|
|
124
|
+
const formMessage = await this.formGenerator.generateFormFromSchema(
|
|
125
|
+
schema,
|
|
126
|
+
input,
|
|
127
|
+
{
|
|
128
|
+
toolName: tool.name,
|
|
129
|
+
toolDescription: tool.description
|
|
130
|
+
},
|
|
131
|
+
context.missingFields
|
|
132
|
+
);
|
|
133
|
+
if (renderConfig) {
|
|
134
|
+
formMessage.formConfig.metadata = {
|
|
135
|
+
...formMessage.formConfig.metadata,
|
|
136
|
+
renderConfig
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
formMessage.partialInput = input;
|
|
140
|
+
return formMessage;
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Generate form from Zod validation error
|
|
144
|
+
*/
|
|
145
|
+
async generateErrorBasedForm(tool, error, context) {
|
|
146
|
+
return this.formGenerator.generateFormFromError(
|
|
147
|
+
error,
|
|
148
|
+
tool.schema,
|
|
149
|
+
tool.name,
|
|
150
|
+
context.input ? String(context.input) : ""
|
|
151
|
+
);
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Validate input against tool schema
|
|
155
|
+
*/
|
|
156
|
+
validateInput(tool, input) {
|
|
157
|
+
try {
|
|
158
|
+
const zodSchema = tool.schema;
|
|
159
|
+
zodSchema.parse(input);
|
|
160
|
+
return { isValid: true };
|
|
161
|
+
} catch (error) {
|
|
162
|
+
if (error instanceof ZodError) {
|
|
163
|
+
const errors = error.errors.map(
|
|
164
|
+
(err) => `${err.path.join(".")}: ${err.message}`
|
|
165
|
+
);
|
|
166
|
+
return { isValid: false, errors };
|
|
167
|
+
}
|
|
168
|
+
return { isValid: false, errors: ["Validation failed"] };
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* Check if schema is ZodObject
|
|
173
|
+
*/
|
|
174
|
+
isZodObject(schema) {
|
|
175
|
+
if (!schema || typeof schema !== "object") {
|
|
176
|
+
return false;
|
|
177
|
+
}
|
|
178
|
+
const candidate = schema;
|
|
179
|
+
return Boolean(candidate._def && candidate._def.typeName === "ZodObject");
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Check if tool has render configuration
|
|
183
|
+
*/
|
|
184
|
+
hasRenderConfig(tool) {
|
|
185
|
+
const schema = tool.schema;
|
|
186
|
+
return !!(schema && schema._renderConfig);
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Extract render configuration from tool
|
|
190
|
+
*/
|
|
191
|
+
extractRenderConfig(tool) {
|
|
192
|
+
const schema = tool.schema;
|
|
193
|
+
return schema?._renderConfig;
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Resolve form schema for FormValidatable tools
|
|
197
|
+
*/
|
|
198
|
+
resolveFormSchema(tool) {
|
|
199
|
+
const formValidatableTool = tool;
|
|
200
|
+
if (formValidatableTool.getFormSchema) {
|
|
201
|
+
const focusedSchema = formValidatableTool.getFormSchema();
|
|
202
|
+
if (focusedSchema) {
|
|
203
|
+
return { schemaToUse: focusedSchema, isFocusedSchema: true };
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
return { schemaToUse: tool.schema, isFocusedSchema: false };
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* Determine missing fields for form generation
|
|
210
|
+
*/
|
|
211
|
+
determineMissingFields(tool, input, _schema, _isFocusedSchema) {
|
|
212
|
+
const missingFields = /* @__PURE__ */ new Set();
|
|
213
|
+
if (!input || typeof input !== "object") {
|
|
214
|
+
return missingFields;
|
|
215
|
+
}
|
|
216
|
+
const inputRecord = input;
|
|
217
|
+
const formValidatableTool = tool;
|
|
218
|
+
if (formValidatableTool.getEssentialFields) {
|
|
219
|
+
const essentialFields = formValidatableTool.getEssentialFields();
|
|
220
|
+
for (const field of essentialFields) {
|
|
221
|
+
if (!(field in inputRecord) || formValidatableTool.isFieldEmpty && formValidatableTool.isFieldEmpty(field, inputRecord[field])) {
|
|
222
|
+
missingFields.add(field);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
return missingFields;
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* Generate form with resolved schema
|
|
230
|
+
*/
|
|
231
|
+
async generateFormWithSchema(tool, input, schema, missingFields) {
|
|
232
|
+
const formMessage = await this.formGenerator.generateFormFromSchema(
|
|
233
|
+
schema,
|
|
234
|
+
input,
|
|
235
|
+
{
|
|
236
|
+
toolName: tool.name,
|
|
237
|
+
toolDescription: tool.description
|
|
238
|
+
},
|
|
239
|
+
missingFields
|
|
240
|
+
);
|
|
241
|
+
if (this.isZodObject(schema)) {
|
|
242
|
+
try {
|
|
243
|
+
const { jsonSchema, uiSchema } = this.formGenerator.generateJsonSchemaForm(
|
|
244
|
+
schema,
|
|
245
|
+
input,
|
|
246
|
+
missingFields
|
|
247
|
+
);
|
|
248
|
+
formMessage.jsonSchema = jsonSchema;
|
|
249
|
+
formMessage.uiSchema = uiSchema;
|
|
250
|
+
} catch (error) {
|
|
251
|
+
this.logger.warn("Failed to generate JSON Schema:", error);
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
formMessage.partialInput = input;
|
|
255
|
+
return formMessage;
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* Validate form submission
|
|
259
|
+
*/
|
|
260
|
+
validateSubmission(submission) {
|
|
261
|
+
if (!submission.toolName) {
|
|
262
|
+
throw new Error("Tool name is required in form submission");
|
|
263
|
+
}
|
|
264
|
+
if (!submission.parameters) {
|
|
265
|
+
throw new Error("Parameters are required in form submission");
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* Extract base tool input from context
|
|
270
|
+
*/
|
|
271
|
+
extractBaseToolInput(context) {
|
|
272
|
+
return context?.originalInput || {};
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* Extract submission data
|
|
276
|
+
*/
|
|
277
|
+
extractSubmissionData(submission) {
|
|
278
|
+
return {
|
|
279
|
+
...submission.parameters,
|
|
280
|
+
__fromForm: true
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* Merge input data
|
|
285
|
+
*/
|
|
286
|
+
mergeInputData(baseInput, submissionData) {
|
|
287
|
+
return {
|
|
288
|
+
...baseInput,
|
|
289
|
+
...submissionData
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* Get registered strategies
|
|
294
|
+
*/
|
|
295
|
+
getRegisteredStrategies() {
|
|
296
|
+
return ["FormValidatable", "SchemaBased", "RenderConfig", "ZodErrorBased"];
|
|
297
|
+
}
|
|
298
|
+
/**
|
|
299
|
+
* Get registered middleware
|
|
300
|
+
*/
|
|
301
|
+
getRegisteredMiddleware() {
|
|
302
|
+
return ["FormSubmissionValidator"];
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
export {
|
|
306
|
+
FormEngine
|
|
307
|
+
};
|
|
308
|
+
//# sourceMappingURL=index29.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index29.js","sources":["../../src/forms/FormEngine.ts"],"sourcesContent":["import { StructuredTool } from '@langchain/core/tools';\nimport { ZodError, z } from 'zod';\nimport { Logger } from '@hashgraphonline/standards-sdk';\nimport { FormGenerator } from './form-generator';\nimport { isFormValidatable } from '@hashgraphonline/standards-agent-kit';\nimport type { FormMessage, FormSubmission } from './types';\n\n/**\n * Tool execution result with optional form requirement\n */\nexport interface ToolExecutionResult {\n success: boolean;\n output: string;\n metadata?: Record<string, unknown>;\n requiresForm?: boolean;\n formMessage?: FormMessage;\n error?: string;\n}\n\n/**\n * Context for form generation operations\n */\nexport interface FormGenerationContext {\n tool: StructuredTool;\n input: unknown;\n sessionId?: string;\n userId?: string;\n missingFields?: Set<string>;\n}\n\n/**\n * FormEngine handles all form generation and validation logic\n */\nexport class FormEngine {\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: 'FormEngine' });\n }\n\n /**\n * Generate a form for a tool with the given input\n */\n async generateForm(\n toolName: string,\n tool: StructuredTool,\n input: unknown,\n context?: Partial<FormGenerationContext>\n ): Promise<FormMessage | null> {\n const fullContext: FormGenerationContext = {\n tool,\n input,\n ...context\n };\n\n try {\n if (isFormValidatable(tool)) {\n return await this.generateFormValidatableForm(tool, input, fullContext);\n }\n\n if (input instanceof ZodError) {\n return await this.generateErrorBasedForm(tool, input, fullContext);\n }\n\n if (this.hasRenderConfig(tool)) {\n return await this.generateRenderConfigForm(tool, input, fullContext);\n }\n\n if (this.isZodObject(tool.schema)) {\n return await this.generateSchemaBasedForm(tool, input, fullContext);\n }\n\n return null;\n } catch (error) {\n this.logger.error(`Failed to generate form for tool: ${toolName}`, {\n error: error instanceof Error ? error.message : String(error)\n });\n throw error;\n }\n }\n\n /**\n * Process a form submission\n */\n async processSubmission(\n submission: FormSubmission,\n context?: {\n originalInput?: Record<string, unknown>;\n schema?: unknown;\n }\n ): Promise<Record<string, unknown>> {\n this.validateSubmission(submission);\n \n const baseToolInput = this.extractBaseToolInput(context);\n const submissionData = this.extractSubmissionData(submission);\n \n return this.mergeInputData(baseToolInput, submissionData);\n }\n\n /**\n * Check if a tool requires form generation based on input\n */\n shouldGenerateForm(tool: StructuredTool, input: unknown): boolean {\n const inputRecord = input as Record<string, unknown>;\n if (inputRecord?.__fromForm === true || inputRecord?.renderForm === false) {\n return false;\n }\n\n if (isFormValidatable(tool)) {\n try {\n const formValidatableTool = tool as {\n shouldGenerateForm: (input: unknown) => boolean;\n };\n return formValidatableTool.shouldGenerateForm(input);\n } catch (error) {\n this.logger.error(`Error calling shouldGenerateForm() on ${tool.name}:`, error);\n return false;\n }\n }\n\n const validation = this.validateInput(tool, input);\n return !validation.isValid;\n }\n\n /**\n * Generate form from error context\n */\n async generateFormFromError(\n error: ZodError,\n toolName: string,\n toolSchema: z.ZodSchema,\n originalPrompt: string\n ): Promise<FormMessage> {\n return this.formGenerator.generateFormFromError(\n error,\n toolSchema as z.ZodType<unknown, z.ZodTypeDef, unknown>,\n toolName,\n originalPrompt\n );\n }\n\n /**\n * Generate form for FormValidatable tools\n */\n private async generateFormValidatableForm(\n tool: StructuredTool,\n input: unknown,\n _context: FormGenerationContext\n ): Promise<FormMessage> {\n const { schemaToUse, isFocusedSchema } = this.resolveFormSchema(tool);\n const missingFields = this.determineMissingFields(tool, input, schemaToUse, isFocusedSchema);\n \n return this.generateFormWithSchema(tool, input, schemaToUse, missingFields);\n }\n\n /**\n * Generate form based on schema validation\n */\n private async generateSchemaBasedForm(\n tool: StructuredTool,\n input: unknown,\n context: FormGenerationContext\n ): Promise<FormMessage> {\n const schema = tool.schema;\n\n const formMessage = await this.formGenerator.generateFormFromSchema(\n schema as z.ZodType<unknown, z.ZodTypeDef, unknown>,\n input,\n {\n toolName: tool.name,\n toolDescription: tool.description\n },\n context.missingFields\n );\n\n if (this.isZodObject(schema)) {\n try {\n const { jsonSchema, uiSchema } = this.formGenerator.generateJsonSchemaForm(\n schema,\n input as Record<string, unknown> | undefined,\n context.missingFields || new Set()\n );\n formMessage.jsonSchema = jsonSchema;\n formMessage.uiSchema = uiSchema;\n } catch (error) {\n this.logger.warn('Failed to generate JSON Schema for schema-based tool:', error);\n }\n }\n\n formMessage.partialInput = input;\n return formMessage;\n }\n\n /**\n * Generate form based on render config\n */\n private async generateRenderConfigForm(\n tool: StructuredTool,\n input: unknown,\n context: FormGenerationContext\n ): Promise<FormMessage> {\n const schema = tool.schema;\n const renderConfig = this.extractRenderConfig(tool);\n\n const formMessage = await this.formGenerator.generateFormFromSchema(\n schema as z.ZodType<unknown, z.ZodTypeDef, unknown>,\n input,\n {\n toolName: tool.name,\n toolDescription: tool.description\n },\n context.missingFields\n );\n\n if (renderConfig) {\n formMessage.formConfig.metadata = {\n ...formMessage.formConfig.metadata,\n renderConfig\n };\n }\n \n formMessage.partialInput = input;\n return formMessage;\n }\n\n /**\n * Generate form from Zod validation error\n */\n private async generateErrorBasedForm(\n tool: StructuredTool,\n error: ZodError,\n context: FormGenerationContext\n ): Promise<FormMessage> {\n return this.formGenerator.generateFormFromError(\n error,\n tool.schema as z.ZodType<unknown, z.ZodTypeDef, unknown>,\n tool.name,\n context.input ? String(context.input) : ''\n );\n }\n\n /**\n * Validate input against tool schema\n */\n private validateInput(\n tool: StructuredTool,\n input: unknown\n ): { isValid: boolean; errors?: string[] } {\n try {\n const zodSchema = tool.schema as z.ZodType<unknown, z.ZodTypeDef, unknown>;\n zodSchema.parse(input);\n return { isValid: true };\n } catch (error) {\n if (error instanceof ZodError) {\n const errors = error.errors.map(\n (err) => `${err.path.join('.')}: ${err.message}`\n );\n return { isValid: false, errors };\n }\n return { isValid: false, errors: ['Validation failed'] };\n }\n }\n\n /**\n * Check if schema is ZodObject\n */\n private isZodObject(schema: unknown): schema is z.ZodObject<z.ZodRawShape> {\n if (!schema || typeof schema !== 'object') {\n return false;\n }\n const candidate = schema as { _def?: { typeName?: string } };\n return Boolean(candidate._def && candidate._def.typeName === 'ZodObject');\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 * Extract render configuration from tool\n */\n private extractRenderConfig(tool: StructuredTool): Record<string, unknown> | undefined {\n const schema = tool.schema as Record<string, unknown>;\n return schema?._renderConfig as Record<string, unknown> | undefined;\n }\n\n /**\n * Resolve form schema for FormValidatable tools\n */\n private resolveFormSchema(tool: StructuredTool): { \n schemaToUse: z.ZodSchema; \n isFocusedSchema: boolean \n } {\n const formValidatableTool = tool as {\n getFormSchema?: () => z.ZodSchema | null;\n };\n \n if (formValidatableTool.getFormSchema) {\n const focusedSchema = formValidatableTool.getFormSchema();\n if (focusedSchema) {\n return { schemaToUse: focusedSchema, isFocusedSchema: true };\n }\n }\n \n return { schemaToUse: tool.schema as z.ZodSchema, isFocusedSchema: false };\n }\n\n /**\n * Determine missing fields for form generation\n */\n private determineMissingFields(\n tool: StructuredTool,\n input: unknown,\n _schema: z.ZodSchema,\n _isFocusedSchema: boolean\n ): Set<string> {\n const missingFields = new Set<string>();\n \n if (!input || typeof input !== 'object') {\n return missingFields;\n }\n \n const inputRecord = input as Record<string, unknown>;\n const formValidatableTool = tool as {\n isFieldEmpty?: (fieldName: string, value: unknown) => boolean;\n getEssentialFields?: () => string[];\n };\n \n if (formValidatableTool.getEssentialFields) {\n const essentialFields = formValidatableTool.getEssentialFields();\n for (const field of essentialFields) {\n if (!(field in inputRecord) || \n (formValidatableTool.isFieldEmpty && \n formValidatableTool.isFieldEmpty(field, inputRecord[field]))) {\n missingFields.add(field);\n }\n }\n }\n \n return missingFields;\n }\n\n /**\n * Generate form with resolved schema\n */\n private async generateFormWithSchema(\n tool: StructuredTool,\n input: unknown,\n schema: z.ZodSchema,\n missingFields: Set<string>\n ): Promise<FormMessage> {\n const formMessage = await this.formGenerator.generateFormFromSchema(\n schema as z.ZodType<unknown, z.ZodTypeDef, unknown>,\n input,\n {\n toolName: tool.name,\n toolDescription: tool.description\n },\n missingFields\n );\n \n if (this.isZodObject(schema)) {\n try {\n const { jsonSchema, uiSchema } = this.formGenerator.generateJsonSchemaForm(\n schema,\n input as Record<string, unknown> | undefined,\n missingFields\n );\n formMessage.jsonSchema = jsonSchema;\n formMessage.uiSchema = uiSchema;\n } catch (error) {\n this.logger.warn('Failed to generate JSON Schema:', error);\n }\n }\n \n formMessage.partialInput = input;\n return formMessage;\n }\n\n /**\n * Validate form submission\n */\n private validateSubmission(submission: FormSubmission): void {\n if (!submission.toolName) {\n throw new Error('Tool name is required in form submission');\n }\n if (!submission.parameters) {\n throw new Error('Parameters are required in form submission');\n }\n }\n\n /**\n * Extract base tool input from context\n */\n private extractBaseToolInput(context?: {\n originalInput?: Record<string, unknown>;\n }): Record<string, unknown> {\n return context?.originalInput || {};\n }\n\n /**\n * Extract submission data\n */\n private extractSubmissionData(submission: FormSubmission): Record<string, unknown> {\n return {\n ...submission.parameters,\n __fromForm: true\n };\n }\n\n /**\n * Merge input data\n */\n private mergeInputData(\n baseInput: Record<string, unknown>,\n submissionData: Record<string, unknown>\n ): Record<string, unknown> {\n return {\n ...baseInput,\n ...submissionData\n };\n }\n\n /**\n * Get registered strategies\n */\n getRegisteredStrategies(): string[] {\n return ['FormValidatable', 'SchemaBased', 'RenderConfig', 'ZodErrorBased'];\n }\n\n /**\n * Get registered middleware\n */\n getRegisteredMiddleware(): string[] {\n return ['FormSubmissionValidator'];\n }\n}"],"names":[],"mappings":";;;;AAiCO,MAAM,WAAW;AAAA,EAItB,YAAY,QAAiB;AAC3B,SAAK,gBAAgB,IAAI,cAAA;AACzB,SAAK,SAAS,UAAU,IAAI,OAAO,EAAE,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