diff options
author | A.J. Shulman <Shulman.aj@gmail.com> | 2025-05-27 14:08:11 -0400 |
---|---|---|
committer | A.J. Shulman <Shulman.aj@gmail.com> | 2025-05-27 14:08:11 -0400 |
commit | 656dbe6dc64013215eb312173df398fe4606d788 (patch) | |
tree | 05c2d35e5f636091c637779d1c8352c25e9ce7f6 | |
parent | c3dba47bcda10bbcd72010c177afa8fd301e87e1 (diff) |
feat: implement dynamic tool creation with deferred webpack rebuild and AI integration
Added runtime tool registry to Agent.ts for dynamic tool lookup
Implemented CreateNewTool agent tool for AI-driven code analysis and tool generation
Enabled deferred saving to avoid interrupting AI workflows with immediate rebuilds
Introduced user-controlled modal for confirming tool installation and page reload
Added REST API and secure server-side persistence for dynamic tools
Built TypeScript validation, transpilation, and sandboxed execution for safe tool handling
UI enhancements: modal with blur, responsive design, clear messaging
Ensured compatibility with Webpack using dynamic require() calls
Full error handling, code validation, and secure storage on client and server sides
-rw-r--r-- | src/client/views/nodes/chatbot/agentsystem/Agent.ts | 252 | ||||
-rw-r--r-- | src/client/views/nodes/chatbot/chatboxcomponents/ChatBox.scss | 120 | ||||
-rw-r--r-- | src/client/views/nodes/chatbot/chatboxcomponents/ChatBox.tsx | 80 | ||||
-rw-r--r-- | src/client/views/nodes/chatbot/tools/CreateNewTool.ts | 599 | ||||
-rw-r--r-- | src/client/views/nodes/chatbot/tools/dynamic/CharacterCountTool.ts | 33 | ||||
-rw-r--r-- | src/server/api/dynamicTools.ts | 130 | ||||
-rw-r--r-- | src/server/index.ts | 1 | ||||
-rw-r--r-- | src/server/server_Initialization.ts | 5 | ||||
-rw-r--r-- | test_dynamic_tools.js | 44 |
9 files changed, 1247 insertions, 17 deletions
diff --git a/src/client/views/nodes/chatbot/agentsystem/Agent.ts b/src/client/views/nodes/chatbot/agentsystem/Agent.ts index 1a9df1a75..c3d37fd0e 100644 --- a/src/client/views/nodes/chatbot/agentsystem/Agent.ts +++ b/src/client/views/nodes/chatbot/agentsystem/Agent.ts @@ -29,6 +29,7 @@ import { CreateLinksTool } from '../tools/CreateLinksTool'; import { CodebaseSummarySearchTool } from '../tools/CodebaseSummarySearchTool'; import { FileContentTool } from '../tools/FileContentTool'; import { FileNamesTool } from '../tools/FileNamesTool'; +import { CreateNewTool } from '../tools/CreateNewTool'; //import { CreateTextDocTool } from '../tools/CreateTextDocumentTool'; dotenv.config(); @@ -52,6 +53,12 @@ export class Agent { private streamedAnswerParser: StreamedAnswerParser = new StreamedAnswerParser(); private tools: Record<string, BaseTool<ReadonlyArray<Parameter>>>; private _docManager: AgentDocumentManager; + // Dynamic tool registry for tools created at runtime + private dynamicToolRegistry: Map<string, BaseTool<ReadonlyArray<Parameter>>> = new Map(); + // Callback for notifying when tools are created and need reload + private onToolCreatedCallback?: (toolName: string) => void; + // Storage for deferred tool saving + private pendingToolSave?: { toolName: string; completeToolCode: string }; /** * The constructor initializes the agent with the vector store and toolset, and sets up the OpenAI client. @@ -79,6 +86,9 @@ export class Agent { this._csvData = csvData; this._docManager = docManager; + // Initialize dynamic tool registry + this.dynamicToolRegistry = new Map(); + // Define available tools for the assistant this.tools = { calculate: new CalculateTool(), @@ -94,6 +104,146 @@ export class Agent { fileContent: new FileContentTool(this.vectorstore), fileNames: new FileNamesTool(this.vectorstore), }; + + // Add the createNewTool after other tools are defined + this.tools.createNewTool = new CreateNewTool(this.dynamicToolRegistry, this.tools, this); + + // Load existing dynamic tools + this.loadExistingDynamicTools(); + } + + /** + * Loads existing dynamic tools by checking the current registry and ensuring all stored tools are available + */ + private async loadExistingDynamicTools(): Promise<void> { + try { + console.log('Loading dynamic tools...'); + + // Since we're in a browser environment, we can't use filesystem operations + // Instead, we'll maintain tools in the registry and try to load known tools + + // Try to manually load the known dynamic tools that exist + const knownDynamicTools = [ + { name: 'CharacterCountTool', actionName: 'charactercount' }, + { name: 'WordCountTool', actionName: 'wordcount' }, + { name: 'TestTool', actionName: 'test' }, + ]; + + let loadedCount = 0; + for (const toolInfo of knownDynamicTools) { + try { + // Check if tool is already in registry + if (this.dynamicToolRegistry.has(toolInfo.actionName)) { + console.log(`✓ Tool ${toolInfo.actionName} already loaded`); + loadedCount++; + continue; + } + + // Try to load the tool using require (works better in webpack environment) + let toolInstance = null; + try { + // Use require with the relative path + const toolModule = require(`../tools/dynamic/${toolInfo.name}`); + const ToolClass = toolModule[toolInfo.name]; + + if (ToolClass && typeof ToolClass === 'function') { + toolInstance = new ToolClass(); + + if (toolInstance instanceof BaseTool) { + this.dynamicToolRegistry.set(toolInfo.actionName, toolInstance); + loadedCount++; + console.log(`✓ Loaded dynamic tool: ${toolInfo.actionName} (from ${toolInfo.name})`); + } + } + } catch (requireError) { + // Tool file doesn't exist or can't be loaded, which is fine + console.log(`Tool ${toolInfo.name} not available:`, (requireError as Error).message); + } + } catch (error) { + console.warn(`⚠ Failed to load ${toolInfo.name}:`, error); + } + } + + console.log(`Successfully loaded ${loadedCount} dynamic tools`); + + // Log all currently registered dynamic tools + if (this.dynamicToolRegistry.size > 0) { + console.log('Currently registered dynamic tools:', Array.from(this.dynamicToolRegistry.keys())); + } + } catch (error) { + console.error('Error loading dynamic tools:', error); + } + } + + /** + * Manually registers a dynamic tool instance (called by CreateNewTool) + */ + public registerDynamicTool(toolName: string, toolInstance: BaseTool<ReadonlyArray<Parameter>>): void { + this.dynamicToolRegistry.set(toolName, toolInstance); + console.log(`Manually registered dynamic tool: ${toolName}`); + } + + /** + * Notifies that a tool has been created and saved to disk (called by CreateNewTool) + */ + public notifyToolCreated(toolName: string, completeToolCode: string): void { + // Store the tool data for deferred saving + this.pendingToolSave = { toolName, completeToolCode }; + + if (this.onToolCreatedCallback) { + this.onToolCreatedCallback(toolName); + } + } + + /** + * Performs the deferred tool save operation (called after user confirmation) + */ + public async performDeferredToolSave(): Promise<boolean> { + if (!this.pendingToolSave) { + console.warn('No pending tool save operation'); + return false; + } + + const { toolName, completeToolCode } = this.pendingToolSave; + + try { + // Get the CreateNewTool instance to perform the save + const createNewTool = this.tools.createNewTool as any; + if (createNewTool && typeof createNewTool.saveToolToServerDeferred === 'function') { + const success = await createNewTool.saveToolToServerDeferred(toolName, completeToolCode); + + if (success) { + console.log(`Tool ${toolName} saved to server successfully via deferred save.`); + // Clear the pending save + this.pendingToolSave = undefined; + return true; + } else { + console.warn(`Tool ${toolName} could not be saved to server via deferred save.`); + return false; + } + } else { + console.error('CreateNewTool instance not available for deferred save'); + return false; + } + } catch (error) { + console.error(`Error performing deferred tool save for ${toolName}:`, error); + return false; + } + } + + /** + * Sets the callback for when tools are created + */ + public setToolCreatedCallback(callback: (toolName: string) => void): void { + this.onToolCreatedCallback = callback; + } + + /** + * Public method to reload dynamic tools (called when new tools are created) + */ + public reloadDynamicTools(): void { + console.log('Reloading dynamic tools...'); + this.loadExistingDynamicTools(); } /** @@ -126,11 +276,8 @@ export class Agent { // Push sanitized user's question to message history this.messages.push({ role: 'user', content: sanitizedQuestion }); - // Retrieve chat history and generate system prompt - const chatHistory = this._history(); - // Get document summaries directly from document manager - // Generate the system prompt with the summaries - const systemPrompt = getReactPrompt(Object.values(this.tools), () => JSON.stringify(this._docManager.listDocs), chatHistory); + // Get system prompt with all tools (static + dynamic) + const systemPrompt = this.getSystemPromptWithAllTools(); // Initialize intermediate messages this.interMessages = [{ role: 'system', content: systemPrompt }]; @@ -193,22 +340,25 @@ export class Agent { currentAction = stage[key] as string; console.log(`Action: ${currentAction}`); - if (this.tools[currentAction]) { + // Check both static tools and dynamic registry + const tool = this.tools[currentAction] || this.dynamicToolRegistry.get(currentAction); + + if (tool) { // Prepare the next action based on the current tool const nextPrompt = [ { type: 'text', - text: `<stage number="${i + 1}" role="user">` + builder.build({ action_rules: this.tools[currentAction].getActionRule() }) + `</stage>`, + text: `<stage number="${i + 1}" role="user">` + builder.build({ action_rules: tool.getActionRule() }) + `</stage>`, } as Observation, ]; this.interMessages.push({ role: 'user', content: nextPrompt }); break; } else { // Handle error in case of an invalid action - console.log('Error: No valid action'); + console.log(`Error: Action "${currentAction}" is not a valid tool`); this.interMessages.push({ role: 'user', - content: `<stage number="${i + 1}" role="system-error-reporter">No valid action, try again.</stage>`, + content: `<stage number="${i + 1}" role="system-error-reporter">Action "${currentAction}" is not a valid tool, try again.</stage>`, }); break; } @@ -376,8 +526,8 @@ export class Agent { throw new Error('Action must be a non-empty string'); } - // Optional: Check if the action is among allowed actions - const allowedActions = Object.keys(this.tools); + // Optional: Check if the action is among allowed actions (including dynamic tools) + const allowedActions = [...Object.keys(this.tools), ...Array.from(this.dynamicToolRegistry.keys())]; if (!allowedActions.includes(stage.action)) { throw new Error(`Action "${stage.action}" is not a valid tool`); } @@ -482,12 +632,15 @@ export class Agent { * @throws An error if the action is unknown, if required parameters are missing, or if input types don't match the expected parameter types. */ private async processAction(action: string, actionInput: ParametersType<ReadonlyArray<Parameter>>): Promise<Observation[]> { - // Check if the action exists in the tools list - if (!(action in this.tools)) { + // Check if the action exists in the tools list or dynamic registry + if (!(action in this.tools) && !this.dynamicToolRegistry.has(action)) { throw new Error(`Unknown action: ${action}`); } console.log(actionInput); + // Determine which tool to use - either from static tools or dynamic registry + const tool = this.tools[action] || this.dynamicToolRegistry.get(action); + // Special handling for documentMetadata tool with numeric or boolean fieldValue if (action === 'documentMetadata') { // Handle single field edit @@ -520,9 +673,49 @@ export class Agent { } } - for (const param of this.tools[action].parameterRules) { + // Special handling for createNewTool with parsed XML toolCode + if (action === 'createNewTool') { + if ('toolCode' in actionInput && typeof actionInput.toolCode === 'object' && actionInput.toolCode !== null) { + try { + // Convert the parsed XML object back to a string + const extractText = (obj: any): string => { + if (typeof obj === 'string') { + return obj; + } else if (obj && typeof obj === 'object') { + if (obj._text) { + return obj._text; + } + // Recursively extract text from all properties + let text = ''; + for (const key in obj) { + if (key !== '_text') { + const value = obj[key]; + if (typeof value === 'string') { + text += value + '\n'; + } else if (value && typeof value === 'object') { + text += extractText(value) + '\n'; + } + } + } + return text; + } + return ''; + }; + + const reconstructedCode = extractText(actionInput.toolCode); + actionInput.toolCode = reconstructedCode; + } catch (error) { + console.error('Error processing toolCode:', error); + // Convert to string as fallback + actionInput.toolCode = String(actionInput.toolCode); + } + } + } + + // Check parameter requirements and types for the tool + for (const param of tool.parameterRules) { // Check if the parameter is required and missing in the input - if (param.required && !(param.name in actionInput) && !this.tools[action].inputValidator(actionInput)) { + if (param.required && !(param.name in actionInput) && !tool.inputValidator(actionInput)) { throw new Error(`Missing required parameter: ${param.name}`); } @@ -540,12 +733,31 @@ export class Agent { } } - const tool = this.tools[action]; - + // Execute the tool with the validated inputs return await tool.execute(actionInput); } /** + * Gets a combined list of all tools, both static and dynamic + * @returns An array of all available tool instances + */ + private getAllTools(): BaseTool<ReadonlyArray<Parameter>>[] { + // Combine static and dynamic tools + return [...Object.values(this.tools), ...Array.from(this.dynamicToolRegistry.values())]; + } + + /** + * Overridden method to get the React prompt with all tools (static + dynamic) + */ + private getSystemPromptWithAllTools(): string { + const allTools = this.getAllTools(); + const docSummaries = () => JSON.stringify(this._docManager.listDocs); + const chatHistory = this._history(); + + return getReactPrompt(allTools, docSummaries, chatHistory); + } + + /** * Reinitializes the DocumentMetadataTool with a direct reference to the ChatBox instance. * This ensures that the tool can properly access the ChatBox document and find related documents. * @@ -560,3 +772,9 @@ export class Agent { } } } + +// Forward declaration to avoid circular import +interface AgentLike { + registerDynamicTool(toolName: string, toolInstance: BaseTool<ReadonlyArray<Parameter>>): void; + notifyToolCreated(toolName: string, completeToolCode: string): void; +} diff --git a/src/client/views/nodes/chatbot/chatboxcomponents/ChatBox.scss b/src/client/views/nodes/chatbot/chatboxcomponents/ChatBox.scss index 31f7be4c4..8e00cbdb7 100644 --- a/src/client/views/nodes/chatbot/chatboxcomponents/ChatBox.scss +++ b/src/client/views/nodes/chatbot/chatboxcomponents/ChatBox.scss @@ -950,3 +950,123 @@ $font-size-xlarge: 18px; } } } + +/* Tool Reload Modal Styles */ +.tool-reload-modal-overlay { + position: fixed; + top: 0; + left: 0; + right: 0; + bottom: 0; + background-color: rgba(0, 0, 0, 0.5); + display: flex; + align-items: center; + justify-content: center; + z-index: 10000; + backdrop-filter: blur(4px); +} + +.tool-reload-modal { + background: white; + border-radius: 12px; + padding: 0; + min-width: 400px; + max-width: 500px; + box-shadow: + 0 20px 25px -5px rgba(0, 0, 0, 0.1), + 0 10px 10px -5px rgba(0, 0, 0, 0.04); + border: 1px solid #e2e8f0; + animation: modalSlideIn 0.3s ease-out; +} + +@keyframes modalSlideIn { + from { + opacity: 0; + transform: scale(0.95) translateY(-20px); + } + to { + opacity: 1; + transform: scale(1) translateY(0); + } +} + +.tool-reload-modal-header { + padding: 24px 24px 16px 24px; + border-bottom: 1px solid #e2e8f0; + + h3 { + margin: 0; + font-size: 18px; + font-weight: 600; + color: #1a202c; + display: flex; + align-items: center; + + &::before { + content: '🛠️'; + margin-right: 8px; + font-size: 20px; + } + } +} + +.tool-reload-modal-content { + padding: 20px 24px; + + p { + margin: 0 0 12px 0; + line-height: 1.5; + color: #4a5568; + + &:last-child { + margin-bottom: 0; + } + + strong { + color: #2d3748; + font-weight: 600; + } + } +} + +.tool-reload-modal-actions { + padding: 16px 24px 24px 24px; + display: flex; + gap: 12px; + justify-content: flex-end; + + button { + padding: 10px 20px; + border-radius: 6px; + font-weight: 500; + font-size: 14px; + cursor: pointer; + transition: all 0.2s ease; + border: none; + + &.primary { + background: #3182ce; + color: white; + + &:hover { + background: #2c5aa0; + transform: translateY(-1px); + } + + &:active { + transform: translateY(0); + } + } + + &.secondary { + background: #f7fafc; + color: #4a5568; + border: 1px solid #e2e8f0; + + &:hover { + background: #edf2f7; + border-color: #cbd5e0; + } + } + } +} diff --git a/src/client/views/nodes/chatbot/chatboxcomponents/ChatBox.tsx b/src/client/views/nodes/chatbot/chatboxcomponents/ChatBox.tsx index 470f94a8d..df6c5627c 100644 --- a/src/client/views/nodes/chatbot/chatboxcomponents/ChatBox.tsx +++ b/src/client/views/nodes/chatbot/chatboxcomponents/ChatBox.tsx @@ -79,6 +79,7 @@ export class ChatBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { @observable private _citationPopup: { text: string; visible: boolean } = { text: '', visible: false }; @observable private _isFontSizeModalOpen: boolean = false; @observable private _fontSize: 'small' | 'normal' | 'large' | 'xlarge' = 'normal'; + @observable private _toolReloadModal: { visible: boolean; toolName: string } = { visible: false, toolName: '' }; // Private properties for managing OpenAI API, vector store, agent, and UI elements private openai!: OpenAI; // Using definite assignment assertion @@ -125,6 +126,9 @@ export class ChatBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { // Create an agent with the vectorstore this.agent = new Agent(this.vectorstore, this.retrieveFormattedHistory.bind(this), this.retrieveCSVData.bind(this), this.createImageInDash.bind(this), this.createCSVInDash.bind(this), this.docManager); + // Set up the tool created callback + this.agent.setToolCreatedCallback(this.handleToolCreated); + // Add event listeners this.addScrollListener(); @@ -1159,6 +1163,56 @@ export class ChatBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { this._inputValue = question; }; + /** + * Handles tool creation notification and shows the reload modal + * @param toolName The name of the tool that was created + */ + @action + handleToolCreated = (toolName: string) => { + this._toolReloadModal = { + visible: true, + toolName: toolName, + }; + }; + + /** + * Closes the tool reload modal + */ + @action + closeToolReloadModal = () => { + this._toolReloadModal = { + visible: false, + toolName: '', + }; + }; + + /** + * Handles the reload confirmation and triggers page reload + */ + @action + handleReloadConfirmation = async () => { + // Close the modal first + this.closeToolReloadModal(); + + try { + // Perform the deferred tool save operation + const saveSuccess = await this.agent.performDeferredToolSave(); + + if (saveSuccess) { + console.log('Tool saved successfully, proceeding with reload...'); + } else { + console.warn('Tool save failed, but proceeding with reload anyway...'); + } + } catch (error) { + console.error('Error during deferred tool save:', error); + } + + // Trigger page reload to rebuild webpack and load the new tool + setTimeout(() => { + window.location.reload(); + }, 100); + }; + _dictation: DictationButton | null = null; /** @@ -1434,6 +1488,32 @@ export class ChatBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { <div className="citation-content">{this._citationPopup.text}</div> </div> )} + + {/* Tool Reload Modal */} + {this._toolReloadModal.visible && ( + <div className="tool-reload-modal-overlay"> + <div className="tool-reload-modal"> + <div className="tool-reload-modal-header"> + <h3>Tool Created Successfully!</h3> + </div> + <div className="tool-reload-modal-content"> + <p> + The tool <strong>{this._toolReloadModal.toolName}</strong> has been created and saved successfully. + </p> + <p>To make the tool available for future use, the page needs to be reloaded to rebuild the application bundle.</p> + <p>Click "Reload Page" to complete the tool installation.</p> + </div> + <div className="tool-reload-modal-actions"> + <button className="reload-button primary" onClick={this.handleReloadConfirmation}> + Reload Page + </button> + <button className="close-button secondary" onClick={this.closeToolReloadModal}> + Later + </button> + </div> + </div> + </div> + )} </div> ); } diff --git a/src/client/views/nodes/chatbot/tools/CreateNewTool.ts b/src/client/views/nodes/chatbot/tools/CreateNewTool.ts new file mode 100644 index 000000000..1cc50a803 --- /dev/null +++ b/src/client/views/nodes/chatbot/tools/CreateNewTool.ts @@ -0,0 +1,599 @@ +import { Observation } from '../types/types'; +import { Parameter, ParametersType, ToolInfo } from '../types/tool_types'; +import { BaseTool } from './BaseTool'; +import * as ts from 'typescript'; +import { v4 as uuidv4 } from 'uuid'; +import { Networking } from '../../../../Network'; + +// Forward declaration to avoid circular import +interface AgentLike { + registerDynamicTool(toolName: string, toolInstance: BaseTool<ReadonlyArray<Parameter>>): void; + notifyToolCreated(toolName: string, completeToolCode: string): void; +} + +const createNewToolParams = [ + { + name: 'toolName', + type: 'string', + description: 'The name of the new tool class (PascalCase) and filename. This will also be converted to lowercase for the action name.', + required: true, + }, + { + name: 'toolCode', + type: 'string', + description: + 'The complete TypeScript code for the new tool class. IMPORTANT: Provide this as a single string without any XML formatting. Do not break it into multiple lines or add any XML tags. The tool must extend BaseTool, implement an async execute method, and have proper parameter definitions. Use CDATA format if needed: <![CDATA[your code here]]>', + required: true, + }, + { + name: 'description', + type: 'string', + description: 'A brief description of what the tool does.', + required: true, + }, +] as const; + +type CreateNewToolParamsType = typeof createNewToolParams; + +const createNewToolInfo: ToolInfo<CreateNewToolParamsType> = { + name: 'createNewTool', + description: `Creates a new tool for the agent to use based on research done with the codebase search, file content, and filenames tools. The new tool will be instantly available for use in the current session and saved as a proper TypeScript file. + +IMPORTANT TOOL CREATION RULES: +1. Your tool will be created with proper imports adjusted for the dynamic subfolder location +2. Your tool MUST extend BaseTool with proper parameter type definition +3. Your tool MUST implement an async execute method that returns Promise<Observation[]> +4. Your tool MUST call super() with the proper tool info configuration object +5. CRITICAL: The toolInfo.name property MUST be lowercase and should match the action name you want to use +6. Follow this EXACT pattern (imports will be added automatically): + +\`\`\`typescript +const yourToolParams = [ + { + name: 'inputParam', + type: 'string', + description: 'Your parameter description', + required: true + } +] as const; + +type YourToolParamsType = typeof yourToolParams; + +const yourToolInfo: ToolInfo<YourToolParamsType> = { + name: 'yourtoolname', + description: 'Your tool description', + citationRules: 'No citation needed.', + parameterRules: yourToolParams +}; + +export class YourToolName extends BaseTool<YourToolParamsType> { + constructor() { + super(yourToolInfo); + } + + async execute(args: ParametersType<YourToolParamsType>): Promise<Observation[]> { + const { inputParam } = args; + // Your implementation here + return [{ type: 'text', text: 'Your result' }]; + } +} +\`\`\` + +EXAMPLE - Character Count Tool: + +\`\`\`typescript +const characterCountParams = [ + { + name: 'text', + type: 'string', + description: 'The text to count characters in', + required: true + } +] as const; + +type CharacterCountParamsType = typeof characterCountParams; + +const characterCountInfo: ToolInfo<CharacterCountParamsType> = { + name: 'charactercount', + description: 'Counts characters in text, excluding spaces', + citationRules: 'No citation needed.', + parameterRules: characterCountParams +}; + +export class CharacterCountTool extends BaseTool<CharacterCountParamsType> { + constructor() { + super(characterCountInfo); + } + + async execute(args: ParametersType<CharacterCountParamsType>): Promise<Observation[]> { + const { text } = args; + const count = text ? text.replace(/\\s/g, '').length : 0; + return [{ type: 'text', text: \`Character count (excluding spaces): \${count}\` }]; + } +} +\`\`\``, + citationRules: `No citation needed.`, + parameterRules: createNewToolParams, +}; + +/** + * This tool allows the agent to create new custom tools after researching the codebase. + * It validates the provided code, dynamically compiles it, and registers it with the + * Agent for immediate use. + */ +export class CreateNewTool extends BaseTool<CreateNewToolParamsType> { + // Reference to the dynamic tool registry in the Agent class + private dynamicToolRegistry: Map<string, BaseTool<ReadonlyArray<Parameter>>>; + private existingTools: Record<string, BaseTool<ReadonlyArray<Parameter>>>; + private agent?: AgentLike; + + constructor(toolRegistry: Map<string, BaseTool<ReadonlyArray<Parameter>>>, existingTools: Record<string, BaseTool<ReadonlyArray<Parameter>>> = {}, agent?: AgentLike) { + super(createNewToolInfo); + this.dynamicToolRegistry = toolRegistry; + this.existingTools = existingTools; + this.agent = agent; + } + + /** + * Validates TypeScript code for basic safety and correctness + * @param code The TypeScript code to validate + * @returns An object with validation result and any error messages + */ + private validateToolCode(code: string, toolName: string): { valid: boolean; errors: string[] } { + const errors: string[] = []; + + // Check for fundamental structure + if (!code.includes('extends BaseTool')) { + errors.push('Tool must extend BaseTool class'); + } + + if (!code.includes(`class ${toolName} extends`)) { + errors.push(`Tool class name must match the provided toolName: ${toolName}`); + } + + if (!code.includes('async execute(')) { + errors.push('Tool must implement an async execute method'); + } + + if (!code.includes('super(')) { + errors.push('Tool must call super() in constructor'); + } + + // Check if the tool exports the class correctly (should use export class) + if (!code.includes(`export class ${toolName}`)) { + errors.push(`Tools must export the class using: export class ${toolName}`); + } + + // Check if tool info has name property in lowercase + const nameMatch = code.match(/name\s*:\s*['"]([^'"]+)['"]/); + if (nameMatch && nameMatch[1]) { + const toolInfoName = nameMatch[1]; + if (toolInfoName !== toolInfoName.toLowerCase()) { + errors.push(`Tool info name property must be lowercase. Found: "${toolInfoName}", should be "${toolInfoName.toLowerCase()}"`); + } + } else { + errors.push('Tool info must have a name property'); + } + + // Check for type definition - make this more flexible + const hasTypeDefinition = code.includes(`type ${toolName}ParamsType`) || code.includes(`type ${toolName.toLowerCase()}ParamsType`) || code.includes('ParamsType = typeof'); + if (!hasTypeDefinition) { + errors.push(`Tool must define a type for parameters like: type ${toolName}ParamsType = typeof ${toolName.toLowerCase()}Params`); + } + + // Check for ToolInfo type annotation - make this more flexible + const hasToolInfoType = code.includes(`ToolInfo<${toolName}ParamsType>`) || code.includes(`ToolInfo<${toolName.toLowerCase()}ParamsType>`) || code.includes('ToolInfo<'); + if (!hasToolInfoType) { + errors.push(`Tool info must be typed as ToolInfo<YourParamsType>`); + } + + // Check for proper execute method typing - make this more flexible + if (!code.includes(`ParametersType<${toolName}ParamsType>`) && !code.includes('args: ParametersType<')) { + errors.push(`Execute method must have typed parameters: args: ParametersType<${toolName}ParamsType>`); + } + + // Check for unsafe code patterns + const unsafePatterns = [ + { pattern: /eval\s*\(/, message: 'eval() is not allowed' }, + { pattern: /Function\s*\(/, message: 'Function constructor is not allowed' }, + { pattern: /require\s*\(\s*['"]child_process['"]/, message: 'child_process module is not allowed' }, + { pattern: /require\s*\(\s*['"]fs['"]/, message: 'Direct fs module import is not allowed' }, + { pattern: /require\s*\(\s*['"]path['"]/, message: 'Direct path module import is not allowed' }, + { pattern: /process\.env/, message: 'Accessing process.env is not allowed' }, + { pattern: /import\s+.*['"]child_process['"]/, message: 'child_process module is not allowed' }, + { pattern: /import\s+.*['"]fs['"]/, message: 'Direct fs module import is not allowed' }, + { pattern: /import\s+.*['"]path['"]/, message: 'Direct path module import is not allowed' }, + { pattern: /\bnew\s+Function\b/, message: 'Function constructor is not allowed' }, + { pattern: /\bwindow\b/, message: 'Direct window access is not allowed' }, + { pattern: /\bdocument\b/, message: 'Direct document access is not allowed' }, + { pattern: /\blocation\b/, message: 'Direct location access is not allowed' }, + { pattern: /\bsessionStorage\b/, message: 'Direct sessionStorage access is not allowed' }, + { pattern: /\blocalStorage\b/, message: 'Direct localStorage access is not allowed' }, + { pattern: /fetch\s*\(/, message: 'Direct fetch calls are not allowed' }, + { pattern: /XMLHttpRequest/, message: 'Direct XMLHttpRequest use is not allowed' }, + ]; + + for (const { pattern, message } of unsafePatterns) { + if (pattern.test(code)) { + errors.push(message); + } + } + + // Check if the tool name is already used by an existing tool + const toolNameLower = toolName.toLowerCase(); + if (Object.keys(this.existingTools).some(key => key.toLowerCase() === toolNameLower) || Array.from(this.dynamicToolRegistry.keys()).some(key => key.toLowerCase() === toolNameLower)) { + errors.push(`A tool with the name "${toolNameLower}" already exists. Please choose a different name.`); + } + + // Use TypeScript compiler API to check for syntax errors + try { + const sourceFile = ts.createSourceFile(`${toolName}.ts`, code, ts.ScriptTarget.Latest, true); + + // Create a TypeScript program to check for type errors + const options: ts.CompilerOptions = { + target: ts.ScriptTarget.ES2020, + module: ts.ModuleKind.ESNext, + strict: true, + esModuleInterop: true, + skipLibCheck: true, + forceConsistentCasingInFileNames: true, + }; + + // Perform additional static analysis on the AST + const visitor = (node: ts.Node) => { + // Check for potentially unsafe constructs + if (ts.isCallExpression(node)) { + const expression = node.expression; + if (ts.isIdentifier(expression)) { + const name = expression.text; + if (name === 'eval' || name === 'Function') { + errors.push(`Use of ${name} is not allowed`); + } + } + } + + // Recursively visit all child nodes + ts.forEachChild(node, visitor); + }; + + visitor(sourceFile); + } catch (error) { + errors.push(`TypeScript syntax error: ${error}`); + } + + return { + valid: errors.length === 0, + errors, + }; + } + + /** + * Extracts tool info name from the tool code + * @param code The tool TypeScript code + * @returns The tool info name or null if not found + */ + private extractToolInfoName(code: string): string | null { + const nameMatch = code.match(/name\s*:\s*['"]([^'"]+)['"]/); + return nameMatch && nameMatch[1] ? nameMatch[1] : null; + } + + /** + * Extracts and parses parameter info from the tool code + * @param code The tool TypeScript code + * @returns An array of parameter objects + */ + private extractToolParameters(code: string): Array<{ name: string; type: string; description: string; required: boolean }> { + // Basic regex-based extraction - in a production environment, this should use the TypeScript AST + const paramsMatch = code.match(/const\s+\w+Params\s*=\s*\[([\s\S]*?)\]\s*as\s*const/); + if (!paramsMatch || !paramsMatch[1]) { + return []; + } + + const paramsText = paramsMatch[1]; + + // Parse individual parameters + const paramRegex = /{\s*name\s*:\s*['"]([^'"]+)['"]\s*,\s*type\s*:\s*['"]([^'"]+)['"]\s*,\s*description\s*:\s*['"]([^'"]+)['"]\s*,\s*required\s*:\s*(true|false)/g; + const params = []; + let match; + + while ((match = paramRegex.exec(paramsText)) !== null) { + params.push({ + name: match[1], + type: match[2], + description: match[3], + required: match[4] === 'true', + }); + } + + return params; + } + + /** + * Generates the complete tool file content with proper imports for the dynamic subfolder + * @param toolCode The user-provided tool code + * @param toolName The name of the tool class + * @returns The complete TypeScript file content + */ + private generateCompleteToolFile(toolCode: string, toolName: string): string { + // Add proper imports for the dynamic subfolder (one level deeper than regular tools) + const imports = `import { Observation } from '../../types/types'; +import { ParametersType, ToolInfo } from '../../types/tool_types'; +import { BaseTool } from '../BaseTool'; + +`; + + // Clean the user code - remove any existing imports they might have added + const cleanedCode = toolCode + .replace(/import\s+[^;]+;?\s*/g, '') // Remove any import statements + .trim(); + + return imports + cleanedCode; + } + + /** + * Transpiles TypeScript code to JavaScript + * @param code The TypeScript code to compile + * @param filename The name of the file (for error reporting) + * @returns The compiled JavaScript code + */ + private transpileTypeScript(code: string, filename: string): { jsCode: string; errors: string[] } { + try { + const transpileOptions: ts.TranspileOptions = { + compilerOptions: { + module: ts.ModuleKind.CommonJS, // Use CommonJS for dynamic imports + target: ts.ScriptTarget.ES2020, + moduleResolution: ts.ModuleResolutionKind.NodeJs, + esModuleInterop: true, + sourceMap: false, + strict: false, // Relax strict mode for dynamic compilation + noImplicitAny: false, // Allow implicit any types + }, + reportDiagnostics: true, + fileName: `${filename}.ts`, + }; + + const output = ts.transpileModule(code, transpileOptions); + + // Check for compilation errors + const errors: string[] = []; + if (output.diagnostics && output.diagnostics.length > 0) { + for (const diagnostic of output.diagnostics) { + if (diagnostic.file && diagnostic.start !== undefined) { + const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start); + const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'); + errors.push(`Line ${line + 1}, Column ${character + 1}: ${message}`); + } else { + errors.push(ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n')); + } + } + + if (errors.length > 0) { + return { jsCode: '', errors }; + } + } + + return { jsCode: output.outputText, errors: [] }; + } catch (error) { + return { + jsCode: '', + errors: [`Transpilation failed: ${error instanceof Error ? error.message : String(error)}`], + }; + } + } + + /** + * Dynamically evaluates and instantiates a tool from JavaScript code + * @param jsCode The JavaScript code + * @param toolName The name of the tool class + * @returns An instance of the tool or null if instantiation failed + */ + private async createDynamicTool(jsCode: string, toolName: string): Promise<BaseTool<ReadonlyArray<Parameter>> | null> { + try { + // Create a safe evaluation context with necessary globals + const globalContext = { + BaseTool: BaseTool, // Actual class reference + exports: {}, + module: { exports: {} }, + require: (id: string) => { + // Mock require for the imports we know about + if (id.includes('types/types')) { + return { Observation: null }; + } + if (id.includes('tool_types')) { + return { ParametersType: null, ToolInfo: null }; + } + if (id.includes('BaseTool')) { + return { BaseTool: BaseTool }; + } + return {}; + }, + console: console, + // Add any other commonly needed globals + JSON: JSON, + Array: Array, + Object: Object, + String: String, + Number: Number, + Boolean: Boolean, + Math: Math, + Date: Date, + }; + + // Create function to evaluate in the proper context + const evaluationFunction = new Function( + ...Object.keys(globalContext), + `"use strict"; + try { + ${jsCode} + // Get the exported class from the module + const ToolClass = exports.${toolName} || module.exports.${toolName} || module.exports; + if (ToolClass && typeof ToolClass === 'function') { + return new ToolClass(); + } else { + console.error('Tool class not found in exports:', Object.keys(exports), Object.keys(module.exports)); + return null; + } + } catch (error) { + console.error('Error during tool evaluation:', error); + return null; + }` + ); + + // Execute with our controlled globals + const toolInstance = evaluationFunction(...Object.values(globalContext)); + + if (!toolInstance) { + console.error(`Failed to instantiate ${toolName} - no instance returned`); + return null; + } + + // Verify it's a proper BaseTool instance + if (!(toolInstance instanceof BaseTool)) { + console.error(`${toolName} is not a proper instance of BaseTool`); + return null; + } + + console.log(`Successfully created dynamic tool instance: ${toolName}`); + return toolInstance; + } catch (error) { + console.error('Error creating dynamic tool:', error); + return null; + } + } + + /** + * Save the tool code to the server so it's available for future sessions + * @param toolName The name of the tool + * @param completeToolCode The complete TypeScript code for the tool with imports + */ + private async saveToolToServer(toolName: string, completeToolCode: string): Promise<boolean> { + try { + // Create a server endpoint to save the tool + const response = await Networking.PostToServer('/saveDynamicTool', { + toolName: toolName, + toolCode: completeToolCode, + }); + + // Type check the response to avoid property access errors + return typeof response === 'object' && response !== null && 'success' in response && (response as { success: boolean }).success === true; + } catch (error) { + console.error('Failed to save tool to server:', error); + return false; + } + } + + async execute(args: ParametersType<CreateNewToolParamsType>): Promise<Observation[]> { + const { toolName, toolCode, description } = args; + + console.log(`Creating new tool: ${toolName}`); + + // Remove any markdown backticks that might be in the code + const cleanedCode = (toolCode as string).replace(/```typescript|```/g, '').trim(); + + if (!cleanedCode) { + return [ + { + type: 'text', + text: 'Failed to extract tool code from the provided input. Please ensure the tool code is provided as valid TypeScript code.', + }, + ]; + } + + // Validate the provided code + const validation = this.validateToolCode(cleanedCode, toolName); + if (!validation.valid) { + return [ + { + type: 'text', + text: `Failed to create tool: Code validation failed with the following errors:\n- ${validation.errors.join('\n- ')}`, + }, + ]; + } + + try { + // Generate the complete tool file with proper imports + const completeToolCode = this.generateCompleteToolFile(cleanedCode, toolName); + + // Extract tool info name from the code + const toolInfoName = this.extractToolInfoName(cleanedCode); + if (!toolInfoName) { + return [ + { + type: 'text', + text: 'Failed to extract tool info name from the code. Make sure the tool has a name property.', + }, + ]; + } + + // Extract parameters from the tool code + const parameters = this.extractToolParameters(cleanedCode); + + // Transpile the TypeScript to JavaScript + const { jsCode, errors } = this.transpileTypeScript(completeToolCode, toolName); + if (errors.length > 0) { + return [ + { + type: 'text', + text: `Failed to transpile tool code with the following errors:\n- ${errors.join('\n- ')}`, + }, + ]; + } + + // Create a dynamic tool instance + const toolInstance = await this.createDynamicTool(jsCode, toolName); + if (!toolInstance) { + return [ + { + type: 'text', + text: 'Failed to instantiate the tool. Make sure it follows all the required patterns and properly extends BaseTool.', + }, + ]; + } + + // Register the tool in the dynamic registry + // Use the name property from the tool info as the registry key + this.dynamicToolRegistry.set(toolInfoName, toolInstance); + + // If we have a reference to the agent, tell it to register dynamic tool + // This ensures the tool is properly loaded from the filesystem for the prompt system + if (this.agent) { + this.agent.registerDynamicTool(toolInfoName, toolInstance); + } + + // Create the success message + const successMessage = `Successfully created and registered new tool: ${toolName}\n\nThe tool is now available for use in the current session. You can call it using the action "${toolInfoName}".\n\nDescription: ${description}\n\nParameters: ${ + parameters.length > 0 ? parameters.map(p => `\n- ${p.name} (${p.type}${p.required ? ', required' : ''}): ${p.description}`).join('') : '\nNo parameters' + }\n\nThe tool will be saved permanently after you confirm the page reload.`; + + // Notify the agent that a tool was created with the complete code for deferred saving + // This will trigger the modal but NOT save to disk yet + if (this.agent) { + this.agent.notifyToolCreated(toolName, completeToolCode); + } + + return [ + { + type: 'text', + text: successMessage, + }, + ]; + } catch (error) { + console.error(`Error creating new tool:`, error); + return [ + { + type: 'text', + text: `Failed to create tool: ${(error as Error).message || 'Unknown error'}`, + }, + ]; + } + } + + /** + * Public method to save tool to server (called by agent after user confirmation) + * @param toolName The name of the tool + * @param completeToolCode The complete TypeScript code for the tool with imports + */ + public async saveToolToServerDeferred(toolName: string, completeToolCode: string): Promise<boolean> { + return this.saveToolToServer(toolName, completeToolCode); + } +} diff --git a/src/client/views/nodes/chatbot/tools/dynamic/CharacterCountTool.ts b/src/client/views/nodes/chatbot/tools/dynamic/CharacterCountTool.ts new file mode 100644 index 000000000..38fed231c --- /dev/null +++ b/src/client/views/nodes/chatbot/tools/dynamic/CharacterCountTool.ts @@ -0,0 +1,33 @@ +import { Observation } from '../../types/types'; +import { ParametersType, ToolInfo } from '../../types/tool_types'; +import { BaseTool } from '../BaseTool'; + +const characterCountParams = [ + { + name: 'text', + type: 'string', + description: 'The text to count characters in', + required: true + } + ] as const; + + type CharacterCountParamsType = typeof characterCountParams; + + const characterCountInfo: ToolInfo<CharacterCountParamsType> = { + name: 'charactercount', + description: 'Counts characters in text, excluding spaces', + citationRules: 'No citation needed.', + parameterRules: characterCountParams + }; + + export class CharacterCountTool extends BaseTool<CharacterCountParamsType> { + constructor() { + super(characterCountInfo); + } + + async execute(args: ParametersType<CharacterCountParamsType>): Promise<Observation[]> { + const { text } = args; + const count = text ? text.replace(/\s/g, '').length : 0; + return [{ type: 'text', text: `Character count (excluding spaces): ${count}` }]; + } + }
\ No newline at end of file diff --git a/src/server/api/dynamicTools.ts b/src/server/api/dynamicTools.ts new file mode 100644 index 000000000..a7b7e1478 --- /dev/null +++ b/src/server/api/dynamicTools.ts @@ -0,0 +1,130 @@ +import * as express from 'express'; +import * as fs from 'fs'; +import * as path from 'path'; + +// Define handler types to match project patterns +type RouteHandler = (req: express.Request, res: express.Response) => any; + +/** + * Handles API endpoints for dynamic tools created by the agent + */ +export function setupDynamicToolsAPI(app: express.Express): void { + // Directory where dynamic tools will be stored + const dynamicToolsDir = path.join(process.cwd(), 'src', 'client', 'views', 'nodes', 'chatbot', 'tools', 'dynamic'); + + console.log(`Dynamic tools directory path: ${dynamicToolsDir}`); + + // Ensure directory exists + if (!fs.existsSync(dynamicToolsDir)) { + try { + fs.mkdirSync(dynamicToolsDir, { recursive: true }); + console.log(`Created dynamic tools directory at ${dynamicToolsDir}`); + } catch (error) { + console.error(`Failed to create dynamic tools directory: ${error}`); + } + } + + /** + * Save a dynamic tool to the server + */ + const saveDynamicTool: RouteHandler = (req, res) => { + try { + const { toolName, toolCode } = req.body; + + if (!toolName || !toolCode) { + return res.status(400).json({ + success: false, + error: 'Missing toolName or toolCode in request body', + }); + } + + // Validate the tool name (should be PascalCase) + if (!/^[A-Z][a-zA-Z0-9]*$/.test(toolName)) { + return res.status(400).json({ + success: false, + error: 'Tool name must be in PascalCase format', + }); + } + + // Create the file path + const filePath = path.join(dynamicToolsDir, `${toolName}.ts`); + + // Check if file already exists and is different + let existingCode = ''; + if (fs.existsSync(filePath)) { + existingCode = fs.readFileSync(filePath, 'utf8'); + } + + // Only write if the file doesn't exist or the content is different + if (existingCode !== toolCode) { + fs.writeFileSync(filePath, toolCode, 'utf8'); + console.log(`Saved dynamic tool: ${toolName}`); + } else { + console.log(`Dynamic tool ${toolName} already exists with the same content`); + } + + return res.json({ success: true, toolName }); + } catch (error) { + console.error('Error saving dynamic tool:', error); + return res.status(500).json({ + success: false, + error: error instanceof Error ? error.message : 'Unknown error', + }); + } + }; + + /** + * Get a list of all available dynamic tools + */ + const getDynamicTools: RouteHandler = (req, res) => { + try { + // Get all TypeScript files in the dynamic tools directory + const files = fs + .readdirSync(dynamicToolsDir) + .filter(file => file.endsWith('.ts')) + .map(file => ({ + name: path.basename(file, '.ts'), + path: path.join('dynamic', file), + })); + + return res.json({ success: true, tools: files }); + } catch (error) { + console.error('Error getting dynamic tools:', error); + return res.status(500).json({ + success: false, + error: error instanceof Error ? error.message : 'Unknown error', + }); + } + }; + + /** + * Get the code for a specific dynamic tool + */ + const getDynamicTool: RouteHandler = (req, res) => { + try { + const { toolName } = req.params; + const filePath = path.join(dynamicToolsDir, `${toolName}.ts`); + + if (!fs.existsSync(filePath)) { + return res.status(404).json({ + success: false, + error: `Tool ${toolName} not found`, + }); + } + + const toolCode = fs.readFileSync(filePath, 'utf8'); + return res.json({ success: true, toolName, toolCode }); + } catch (error) { + console.error('Error getting dynamic tool:', error); + return res.status(500).json({ + success: false, + error: error instanceof Error ? error.message : 'Unknown error', + }); + } + }; + + // Register routes + app.post('/saveDynamicTool', saveDynamicTool); + app.get('/getDynamicTools', getDynamicTools); + app.get('/getDynamicTool/:toolName', getDynamicTool); +} diff --git a/src/server/index.ts b/src/server/index.ts index 3b77359ec..887974ed8 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -2,6 +2,7 @@ import { yellow } from 'colors'; import * as dotenv from 'dotenv'; import * as mobileDetect from 'mobile-detect'; import * as path from 'path'; +import * as express from 'express'; import { logExecution } from './ActionUtilities'; import AssistantManager from './ApiManagers/AssistantManager'; import FlashcardManager from './ApiManagers/FlashcardManager'; diff --git a/src/server/server_Initialization.ts b/src/server/server_Initialization.ts index 514e2ce1e..80cf977ee 100644 --- a/src/server/server_Initialization.ts +++ b/src/server/server_Initialization.ts @@ -21,6 +21,7 @@ import { Database } from './database'; import { WebSocket } from './websocket'; import axios from 'axios'; import { JSDOM } from 'jsdom'; +import { setupDynamicToolsAPI } from './api/dynamicTools'; /* RouteSetter is a wrapper around the server that prevents the server from being exposed. */ @@ -210,6 +211,10 @@ export default async function InitializeServer(routeSetter: RouteSetter) { // app.use(cors({ origin: (_origin: any, callback: any) => callback(null, true) })); registerAuthenticationRoutes(app); // this adds routes to authenticate a user (login, etc) registerCorsProxy(app); // this adds a /corsproxy/ route to allow clients to get to urls that would otherwise be blocked by cors policies + + // Set up the dynamic tools API + setupDynamicToolsAPI(app); + isRelease && !SSL.Loaded && SSL.exit(); routeSetter(new RouteManager(app, isRelease)); // this sets up all the regular supervised routes (things like /home, download/upload api's, pdf, search, session, etc) isRelease && process.env.serverPort && (resolvedPorts.server = Number(process.env.serverPort)); diff --git a/test_dynamic_tools.js b/test_dynamic_tools.js new file mode 100644 index 000000000..b0d6844f3 --- /dev/null +++ b/test_dynamic_tools.js @@ -0,0 +1,44 @@ +// Quick test script to verify dynamic tool loading +const fs = require('fs'); +const path = require('path'); + +console.log('=== Testing Dynamic Tool Loading ==='); + +// Check if the dynamic tools directory exists +const dynamicToolsPath = path.join(__dirname, 'src/client/views/nodes/chatbot/tools/dynamic'); +console.log('Dynamic tools directory:', dynamicToolsPath); +console.log('Directory exists:', fs.existsSync(dynamicToolsPath)); + +if (fs.existsSync(dynamicToolsPath)) { + const files = fs.readdirSync(dynamicToolsPath); + const toolFiles = files.filter(file => file.endsWith('.ts') && !file.startsWith('.')); + + console.log('Found tool files:', toolFiles); + + for (const toolFile of toolFiles) { + const toolPath = path.join(dynamicToolsPath, toolFile); + const toolName = path.basename(toolFile, '.ts'); + + console.log(`\nTesting ${toolFile}:`); + console.log(' - Tool name:', toolName); + console.log(' - File size:', fs.statSync(toolPath).size, 'bytes'); + + // Try to read and check the file content + try { + const content = fs.readFileSync(toolPath, 'utf8'); + + // Check for required patterns + const hasExport = content.includes(`export class ${toolName}`); + const toolInfoMatch = content.match(/const\s+\w+Info.*?=\s*{[^}]*name\s*:\s*['"]([^'"]+)['"]/s); + const hasExtends = content.includes('extends BaseTool'); + + console.log(' - Has export class:', hasExport); + console.log(' - Extends BaseTool:', hasExtends); + console.log(' - Tool info name:', toolInfoMatch ? toolInfoMatch[1] : 'NOT FOUND'); + } catch (error) { + console.log(' - Error reading file:', error.message); + } + } +} + +console.log('\n=== Test Complete ==='); |