evoltagent 1.1.1 → 1.1.2

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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/utils/connections.ts","../src/schemas/toolCall.ts","../src/utils/toolUtil.ts","../src/utils/logger.ts","../src/utils/index.ts","../src/configs/configLoader.ts","../src/configs/constants.ts","../src/configs/paths.ts","../src/configs/settings.ts","../src/configs/mcpConfig.ts","../src/tools/toolStore.ts","../src/tools/toolRegister.ts","../src/tools/think.ts","../src/tools/cmdTool.ts","../src/types.ts","../src/tools/context.ts","../src/tools/fileTool.ts","../src/tools/esmTool.ts","../src/tools/apiTool.ts","../src/tools/reply2human.ts","../src/tools/todoList.ts","../src/tools/designUI.ts","../src/tools/reflect.ts","../src/tools/skills.ts","../src/tools/gitTool.ts","../src/model.ts","../src/schemas/message.ts","../src/memory/messageHistory.ts","../src/tools/toolcallManager.ts","../src/prompts/tools.ts","../src/agent.ts","../src/environment/base.ts","../src/environment/coding.ts"],"sourcesContent":["/**\n * Connection utilities for MCP servers\n *\n * Converts Python's connections.py to TypeScript\n */\n\nimport { Client } from '@modelcontextprotocol/sdk/client/index.js';\nimport { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';\nimport { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';\nimport { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';\nimport { logger } from './index';\n\n/**\n * AsyncExitStack for managing multiple async context managers\n */\nexport class AsyncExitStack {\n private stack: Array<{\n exit: (exc_type: any, exc_val: any, exc_tb: any) => Promise<void>;\n }> = [];\n\n /**\n * Enter a context manager and add it to the stack\n */\n async enterContext<T>(context: AsyncContextManager<T>): Promise<T> {\n const result = await context.enter();\n this.stack.push(context);\n return result;\n }\n\n /**\n * Close all context managers in reverse order\n */\n async close(): Promise<void> {\n while (this.stack.length > 0) {\n const context = this.stack.pop();\n if (context) {\n try {\n await context.exit(null, null, null);\n } catch (error) {\n logger.error('Error closing context:', error);\n }\n }\n }\n }\n\n /**\n * Alias for close to match Python's close method if needed,\n * though Python uses __aexit__ usually.\n */\n async aclose(): Promise<void> {\n await this.close();\n }\n\n /**\n * Push a callback to be called when closing\n */\n push(callback: () => Promise<void>): void {\n // Convert callback to context manager interface\n const contextManager = {\n enter: async () => {},\n exit: async (exc_type: any, exc_val: any, exc_tb: any): Promise<void> => {\n await callback();\n },\n };\n this.stack.push(contextManager);\n }\n}\n\n/**\n * Interface for async context managers\n */\nexport interface AsyncContextManager<T> {\n enter(): Promise<T>;\n exit(exc_type: any, exc_val: any, exc_tb: any): Promise<void>;\n}\n\n/**\n * Base class for MCP server connections\n */\nexport abstract class MCPConnection implements AsyncContextManager<MCPConnection> {\n session: Client | null = null;\n private transport: Transport | null = null;\n\n abstract createTransport(): Promise<Transport>;\n\n async enter(): Promise<MCPConnection> {\n this.transport = await this.createTransport();\n this.session = new Client(\n {\n name: 'evoltagent-client',\n version: '1.0.0',\n },\n {\n capabilities: {\n // Client capabilities\n },\n }\n );\n\n // Connect transport\n await this.session.connect(this.transport);\n\n return this;\n }\n\n async exit(exc_type: any, exc_val: any, exc_tb: any): Promise<void> {\n try {\n if (this.session) {\n await this.session.close();\n }\n } catch (e) {\n logger.error(`Error during cleanup: ${e}`);\n } finally {\n this.session = null;\n this.transport = null;\n }\n }\n\n async listTools(): Promise<any[]> {\n if (!this.session) throw new Error('Session not initialized');\n const result = await this.session.listTools();\n return result.tools;\n }\n\n async callTool(toolName: string, argumentsDict: any): Promise<any> {\n if (!this.session) throw new Error('Session not initialized');\n return await this.session.callTool({\n name: toolName,\n arguments: argumentsDict,\n });\n }\n}\n\n/**\n * MCP connection using standard input/output\n */\nexport class MCPConnectionStdio extends MCPConnection {\n private command: string;\n private args: string[];\n private env: Record<string, string> | undefined;\n\n constructor(command: string, args: string[] = [], env?: Record<string, string>) {\n super();\n this.command = command;\n this.args = args;\n this.env = env;\n }\n\n async createTransport(): Promise<Transport> {\n return new StdioClientTransport({\n command: this.command,\n args: this.args,\n env: this.env,\n });\n }\n}\n\n/**\n * MCP connection using Server-Sent Events\n */\nexport class MCPConnectionSSE extends MCPConnection {\n private url: string;\n private headers: Record<string, string> | undefined;\n\n constructor(url: string, headers?: Record<string, string>) {\n super();\n this.url = url;\n this.headers = headers;\n }\n\n async createTransport(): Promise<Transport> {\n return new SSEClientTransport(new URL(this.url), {\n eventSourceInit: {\n // headers: this.headers, // TypeScript doesn't like headers in EventSourceInit\n },\n });\n }\n}\n\n/**\n * Factory function to create the appropriate MCP connection\n */\nexport function createMcpConnection(config: any): MCPConnection {\n const connType = (config.type || 'stdio').toLowerCase();\n\n if (connType === 'stdio') {\n if (!config.command) {\n throw new Error('Command is required for STDIO connections');\n }\n return new MCPConnectionStdio(config.command, config.args || [], config.env);\n } else if (connType === 'sse') {\n if (!config.url) {\n throw new Error('URL is required for SSE connections');\n }\n return new MCPConnectionSSE(config.url, config.headers);\n } else {\n throw new Error(`Unsupported connection type: ${connType}`);\n }\n}\n","/**\n * Toolcall class and types\n *\n * Extracted from src/utils/toolUtil.ts to mirror Python evolt/schemas/toolcall.py\n */\n\nimport { randomUUID } from 'crypto';\nimport { logger } from '../utils';\n\n/**\n * Toolcall execution state\n */\nexport type ToolcallState = 'pending' | 'running' | 'success' | 'failed';\n\n/**\n * Toolcall type\n */\nexport type ToolcallType = 'system' | 'user' | 'TaskCompletion';\n\n/**\n * Toolcall class representing a single tool call\n */\nexport class Toolcall {\n name: string;\n input: Record<string, any>;\n isExtractedSuccess: boolean;\n failedExtractedReason?: string;\n executedState: ToolcallState;\n executedContent?: string;\n toolCallId: string;\n type: ToolcallType;\n rawContentFromLlm?: string;\n\n constructor(config: {\n name: string;\n input?: Record<string, any>;\n isExtractedSuccess?: boolean;\n failedExtractedReason?: string;\n executedState?: ToolcallState;\n executedContent?: string;\n toolCallId?: string;\n type?: ToolcallType;\n rawContentFromLlm?: string;\n }) {\n this.name = config.name;\n this.input = config.input || {};\n this.isExtractedSuccess = config.isExtractedSuccess ?? true;\n this.failedExtractedReason = config.failedExtractedReason;\n this.executedState = config.executedState || 'pending';\n this.executedContent = config.executedContent;\n this.toolCallId = config.toolCallId || randomUUID();\n this.type = config.type || 'system';\n this.rawContentFromLlm = config.rawContentFromLlm;\n }\n\n /**\n * Toolcall extraction result description\n */\n extractedResult(): string | Record<string, any> | Record<string, any>[] {\n // TaskCompletion\n if (this.type === 'TaskCompletion') {\n return this.rawContentFromLlm || '';\n }\n\n // User Toolcall\n if (this.type === 'user') {\n if (!this.isExtractedSuccess) {\n return [\n {\n role: 'assistant',\n tool_calls: [\n {\n id: `user_tool_${this.toolCallId}`,\n type: 'function',\n function: {\n name: this.name,\n arguments: this.rawContentFromLlm,\n },\n },\n ],\n },\n {\n role: 'tool',\n tool_call_id: `user_tool_${this.toolCallId}`,\n name: this.name,\n content: this.failedExtractedReason || 'Unknown reason',\n },\n ];\n }\n logger.debug(`User Toolcall: ${this.name}(${JSON.stringify(this.input)})`);\n\n return {\n role: 'assistant',\n tool_calls: [\n {\n id: `user_tool_${this.toolCallId}`,\n type: 'function',\n function: {\n name: this.name,\n arguments: JSON.stringify(this.input),\n },\n },\n ],\n };\n }\n\n // System Toolcall\n // Failed extraction\n if (!this.isExtractedSuccess) {\n return `Toolcall ${this.name} failed to extract: ${this.failedExtractedReason || 'Unknown reason'}`;\n }\n\n // Successful extraction, return XML format\n if (this.name) {\n const inputStr = Object.entries(this.input)\n .map(([k, v]) => `<${k}>${v}</${k}>`)\n .join('');\n return `<${this.name}>${inputStr}</${this.name}>`;\n }\n\n return `Invalid Toolcall: name ${this.name}, arguments ${JSON.stringify(this.input)}.`;\n }\n\n /**\n * Toolcall execution result: Feedback to LLM\n */\n executedResult(): string | Record<string, any> {\n // TaskCompletion\n if (this.type === 'TaskCompletion') {\n return 'The task has been completed.';\n }\n\n // User Toolcall execution result\n if (this.type === 'user') {\n if (!this.isExtractedSuccess) {\n return '';\n }\n\n return {\n role: 'tool',\n tool_call_id: this.toolCallId, // Use the original tool_call_id without prefix\n name: this.name,\n content: (this.executedContent || 'No execution result found.').trim(),\n };\n }\n\n // Special tools that don't use observation format\n if (this.name.startsWith('ThinkTool.execute') || this.name.startsWith('TodoListTool.write')) {\n return (this.executedContent || 'No thinking result found.').trim();\n }\n\n // Other tools: use observation format\n let toolcallDescription = '';\n let observation = '';\n\n if (this.name.startsWith('FileEditor.write')) {\n toolcallDescription = `FileEditor.write(${this.input.path})`;\n } else {\n toolcallDescription = `${this.name}(${JSON.stringify(this.input)})`;\n }\n\n observation += `Executed content: ${(this.executedContent || 'None').trim()}\\n`;\n\n // Simplified observation format - you might want to import actual prompt templates\n return `Toolcall: ${toolcallDescription}\\nObservation: ${observation}`;\n }\n}\n","/**\n * Tool utility functions and Toolcall class\n *\n * Converts Python's tool_util.py to TypeScript\n */\n\nimport { logger } from './index';\nimport { Toolcall, ToolcallState, ToolcallType } from '../schemas/toolCall';\n\n// Re-export for convenience\nexport { Toolcall, ToolcallState, ToolcallType };\n\n/**\n * Check if message contains tool calls\n */\nexport function hasToolcall(msg: string | Toolcall[], toolStore?: Record<string, any>): boolean {\n if (typeof msg === 'string') {\n if (!toolStore) return false;\n\n for (const toolName of Object.keys(toolStore)) {\n if (msg.includes(`<${toolName}>`) && msg.includes(`</${toolName}>`)) {\n return true;\n }\n }\n return false;\n } else if (Array.isArray(msg)) {\n for (const t of msg) {\n if (t instanceof Toolcall && t.name) {\n return true;\n }\n }\n return false;\n }\n\n logger.error(`msg: ${msg} is not a valid list.`);\n return false;\n}\n\n/**\n * Check if writing JSON file\n * 检查是否正在写入JSON文件\n *\n * 支持以下路径参数名:\n * - path\n * - filePath\n * - apiFilePath\n *\n * @param argumentsTxt 工具参数的XML文本\n * @param toolName 工具名称\n * @returns 如果是写入JSON文件则返回true\n */\nexport function isWriteJsonFile(argumentsTxt: string, toolName: string): boolean {\n if (!toolName.startsWith('FileEditor.') && !toolName.startsWith('ApiTool.')) {\n return false;\n }\n\n // 匹配 .json </path> 或 .json</filePath> 或 .json </apiFilePath> 等\n const pattern = /\\.json\\s*<\\/(path|filePath|apiFilePath)>/;\n return pattern.test(argumentsTxt);\n}\n\n/**\n * Unescape HTML/XML entities in a string.\n *\n * LLMs often output XML-escaped content that needs unescaping before processing.\n *\n * Supported entities:\n * - Named: &quot; &amp; &lt; &gt; &apos;\n * - Numeric decimal: &#34; &#38;\n * - Numeric hex: &#x22; &#x26;\n *\n * @param str - String potentially containing HTML entities\n * @returns String with entities unescaped to their character equivalents\n *\n * @example\n * unescapeHtmlEntities('&quot;Hello&quot;') // Returns: \"Hello\"\n * unescapeHtmlEntities('&#60;tag&#62;') // Returns: \"<tag>\"\n */\nfunction unescapeHtmlEntities(str: string): string {\n // Replace numeric entities first (decimal and hex)\n // This prevents issues with double-unescaping\n let result = str;\n result = result.replace(/&#(\\d+);/g, (_, dec) => String.fromCharCode(parseInt(dec, 10)));\n result = result.replace(/&#x([0-9a-fA-F]+);/g, (_, hex) => String.fromCharCode(parseInt(hex, 16)));\n\n // Replace named entities using a single-pass approach\n result = result.replace(/&(?:quot|amp|lt|gt|apos);/g, match => {\n const entities: Record<string, string> = {\n '&quot;': '\"',\n '&amp;': '&',\n '&lt;': '<',\n '&gt;': '>',\n '&apos;': \"'\",\n };\n return entities[match] || match;\n });\n\n return result;\n}\n\n/**\n * Convert string to object from XML format\n */\nexport function convertStrToObject(txt: string, toolName: string, argNames: string[]): Record<string, any> {\n const result: Record<string, any> = {};\n\n // Build complete start and end tags\n const startTag = `<${toolName}>`;\n const endTag = `</${toolName}>`;\n\n // Extract content inside tool tags\n const toolPattern = new RegExp(`${escapeRegExp(startTag)}(.*?)${escapeRegExp(endTag)}`, 's');\n const toolMatch = toolPattern.exec(txt);\n\n if (!toolMatch) {\n return result;\n }\n\n const innerContent = toolMatch[1];\n\n // Extract each parameter value\n for (const argName of argNames) {\n const argStartTag = `<${argName}>`;\n const argEndTag = `</${argName}>`;\n\n const argPattern = new RegExp(`${escapeRegExp(argStartTag)}(.*?)${escapeRegExp(argEndTag)}`, 's');\n const argMatch = argPattern.exec(innerContent);\n\n if (argMatch) {\n let value = argMatch[1].trim();\n\n // Unescape HTML/XML entities (e.g., &quot; -> \", &#34; -> \")\n // LLMs may output XML-escaped content that needs unescaping before JSON parsing\n // This must happen BEFORE the JSON.parse() attempt below\n value = unescapeHtmlEntities(value);\n\n // If writing JSON file, return content directly\n if (isWriteJsonFile(txt, toolName)) {\n result[argName] = value;\n continue;\n }\n\n // Try to parse as JSON\n try {\n const parsedValue = JSON.parse(value);\n result[argName] = parsedValue;\n } catch {\n // If JSON parsing fails, keep as string\n result[argName] = value;\n }\n }\n }\n\n return result;\n}\n\n/**\n * Extract tool calls from string\n */\nexport function extractToolcallsFromStr(txt: string, toolStore: Record<string, any>): Toolcall[] {\n const matches: Array<[number, Toolcall]> = [];\n\n for (const toolName of Object.keys(toolStore)) {\n const pattern = new RegExp(`<${escapeRegExp(toolName)}>(.*?)</${escapeRegExp(toolName)}>`, 'gs');\n let match: RegExpExecArray | null;\n\n while ((match = pattern.exec(txt)) !== null) {\n const argumentsTxt = match[1].trim();\n\n if (!isWriteJsonFile(argumentsTxt, toolName) && argumentsTxt.startsWith('{') && argumentsTxt.endsWith('}')) {\n matches.push([\n match.index,\n new Toolcall({\n name: toolName,\n input: {},\n isExtractedSuccess: false,\n type: 'system',\n rawContentFromLlm: txt,\n }),\n ]);\n continue;\n }\n\n const rawInput = `<${toolName}>${argumentsTxt}</${toolName}>`;\n let pythonObjectInput: Record<string, any> = {};\n\n if (rawInput) {\n const argNames = toolStore[toolName].argNames || [];\n pythonObjectInput = convertStrToObject(rawInput, toolName, argNames);\n }\n\n matches.push([\n match.index,\n new Toolcall({\n name: toolName,\n input: pythonObjectInput,\n type: 'system',\n }),\n ]);\n }\n }\n\n // Sort by occurrence order and return\n matches.sort((a, b) => a[0] - b[0]);\n return matches.map(([, tc]) => tc);\n}\n\n/**\n * Execute a single tool\n */\nexport async function executeSingleTool(toolcall: Toolcall, toolStore: Record<string, any>[]): Promise<Toolcall> {\n if (!Array.isArray(toolStore)) {\n toolStore = [toolStore];\n }\n\n // Return failed toolcall\n if (!toolcall.isExtractedSuccess) {\n return toolcall;\n }\n\n try {\n // Execute the tool directly\n if (toolcall.name && !toolcall.name.startsWith('FileEditor.') && !toolcall.name.startsWith('ThinkTool.')) {\n logger.info(`Executing Tool ${toolcall.name} with arguments: ${JSON.stringify(toolcall.input)}`);\n }\n\n for (const ts of toolStore) {\n let toolCall: any;\n let argNames: string[] = [];\n\n // Check if tool store has the tool\n // Support both class-based ToolStore (with hasTool/getTool) and object-based store\n if (typeof ts.hasTool === 'function' && ts.hasTool(toolcall.name)) {\n const toolDesc = ts.getTool(toolcall.name);\n toolCall = toolDesc ? toolDesc.execute : undefined;\n argNames = toolDesc ? toolDesc.argNames : [];\n } else if (toolcall.name in ts) {\n toolCall = ts[toolcall.name].execute;\n argNames = ts[toolcall.name].argNames || [];\n }\n\n if (toolCall) {\n let result: any;\n\n if (typeof toolCall === 'function') {\n // Map arguments based on argNames if available\n if (argNames && argNames.length > 0) {\n // Map input object to argument list based on docstring parameter order\n const args = argNames.map(name => toolcall.input[name]);\n result = await toolCall(...args);\n } else {\n // Fallback: pass the input object directly\n // This handles cases where tool takes a single object argument or no arguments\n result = await toolCall(toolcall.input);\n }\n } else {\n logger.error(`Tool ${toolcall.name} is not callable`);\n toolcall.executedContent = `Tool '${toolcall.name}' is not callable`;\n toolcall.executedState = 'failed';\n return toolcall;\n }\n\n toolcall.executedContent = String(result);\n toolcall.executedState = 'success';\n return toolcall;\n }\n }\n\n // Tool not found\n toolcall.executedContent = `Tool '${toolcall.name}' not found in tool_store. Please check the tool name.`;\n toolcall.executedState = 'failed';\n return toolcall;\n } catch (error) {\n const errorMsg = `Error executing tool: ${error}`;\n toolcall.executedContent = errorMsg;\n toolcall.executedState = 'failed';\n return toolcall;\n }\n}\n\n/**\n * Execute multiple tools\n */\nexport async function executeTools(\n toolCalls: Toolcall[],\n toolStore: Record<string, any>[],\n parallel: boolean = false\n): Promise<Toolcall[]> {\n if (parallel) {\n return Promise.all(toolCalls.map(call => executeSingleTool(call, toolStore)));\n } else {\n const results: Toolcall[] = [];\n for (const call of toolCalls) {\n results.push(await executeSingleTool(call, toolStore));\n }\n return results;\n }\n}\n\n/**\n * Helper function to escape regex special characters\n */\nfunction escapeRegExp(string: string): string {\n return string.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n","/**\n * Winston logger configuration\n *\n * Provides a centralized logging solution to replace console calls\n * Format inspired by loguru for better readability\n */\n\nimport * as winston from 'winston';\nimport * as fs from 'fs';\nimport * as dotenv from 'dotenv';\n\ndotenv.config();\n\nconst getDisableLog = (): boolean => {\n return process.env.DISABLE_LOG == 'true' || !('DISABLE_LOG' in process.env);\n};\n\n// Winston log levels (npm standard)\n// winston levels: error: 0, warn: 1, info: 2, http: 3, verbose: 4, debug: 5, silly: 6\nconst winstonLevels = {\n error: 0,\n warn: 1,\n info: 2,\n http: 3,\n verbose: 4,\n debug: 5,\n silly: 6,\n};\n\n// Get log level from environment variable\nconst getLogLevel = (): string => {\n const envLevel = process.env.LOG_LEVEL?.toLowerCase() || 'error';\n // Map some common level names to winston levels\n const levelMapping: Record<string, string> = {\n fatal: 'error',\n trace: 'debug',\n };\n return levelMapping[envLevel] || envLevel;\n};\n\n// No longer need addCallerInfo format since we're capturing it in the wrapper\n\n/**\n * Custom winston format for loguru-style output\n * Format: YYYY-MM-DD HH:MM:SS | LEVEL | file:line | MESSAGE\n */\nconst loguruFormat = winston.format.combine(\n winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),\n winston.format.errors({ stack: true }),\n winston.format.printf(({ timestamp, level, message, stack, ...meta }: any) => {\n const formattedLevel = level.toUpperCase().padEnd(7);\n const caller = meta.caller || meta[0]?.caller;\n const location = caller ? `${String(caller).padEnd(35)} | ` : '';\n const msg = stack || message;\n return `${timestamp} | ${formattedLevel} | ${location}${msg}`;\n })\n);\n\n/**\n * Custom winston format with colors for console output\n */\nconst loguruFormatColored = winston.format.combine(\n winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),\n winston.format.errors({ stack: true }),\n winston.format.printf(({ timestamp, level, message, stack, ...meta }: any) => {\n // Convert level to uppercase and pad it\n const levelUpper = level.toUpperCase().padEnd(7);\n\n // Apply colors manually\n let coloredLevel = levelUpper;\n if (level === 'error') {\n coloredLevel = `\\u001b[31m${levelUpper}\\u001b[39m`; // red\n } else if (level === 'warn') {\n coloredLevel = `\\u001b[33m${levelUpper}\\u001b[39m`; // yellow\n } else if (level === 'info') {\n coloredLevel = `\\u001b[36m${levelUpper}\\u001b[39m`; // cyan\n } else if (level === 'debug') {\n coloredLevel = `\\u001b[34m${levelUpper}\\u001b[39m`; // blue\n }\n\n // Add caller info (file:line) with color\n const caller = meta.caller || meta[0]?.caller;\n const location = caller ? `\\u001b[90m${String(caller).padEnd(35)}\\u001b[39m | ` : '';\n\n const msg = stack || message;\n return `${timestamp} | ${coloredLevel} | ${location}${msg}`;\n })\n);\n\n/**\n * Create winston transports based on LOG_OUTPUT environment variable\n * LOG_OUTPUT can be:\n * - undefined/empty: use console (default, error->stderr, others->stdout)\n * - 'console': use console (same as default)\n * - 'stdout': use process.stdout (all logs)\n * - 'stderr': use process.stderr (all logs)\n * - file path: write to both console and file\n *\n * When ENABLE_LOG is 'false', no transports will be created (logging disabled)\n */\nconst createLoggerTransports = (): winston.transport[] => {\n // Check if logging is disabled\n if (getDisableLog()) {\n return [];\n }\n\n const output = process.env.LOG_OUTPUT;\n\n if (!output || output === 'console') {\n // Default: use separate transports for error and other levels\n return [\n new winston.transports.Console({\n level: getLogLevel(),\n format: loguruFormatColored,\n stderrLevels: ['error'], // Only error goes to stderr\n }),\n ];\n } else if (output === 'stdout') {\n return [\n new winston.transports.Stream({\n stream: process.stdout,\n format: loguruFormat,\n }),\n ];\n } else if (output === 'stderr') {\n return [\n new winston.transports.Stream({\n stream: process.stderr,\n format: loguruFormat,\n }),\n ];\n } else {\n // File output: output to both console and file\n return [\n new winston.transports.Console({\n level: getLogLevel(),\n format: loguruFormatColored,\n stderrLevels: ['error'], // Only error goes to stderr\n }),\n new winston.transports.File({\n filename: output,\n format: loguruFormat,\n }),\n ];\n }\n};\n\n// Create winston logger\nconst logger = winston.createLogger({\n levels: winstonLevels,\n level: getLogLevel(),\n transports: createLoggerTransports(),\n});\n\n// Add custom colors for winston\nwinston.addColors({\n error: 'red',\n warn: 'yellow',\n info: 'cyan',\n http: 'green',\n verbose: 'blue',\n debug: 'blue',\n silly: 'magenta',\n});\n\n/**\n * Capture caller info immediately and pass to logger\n */\nfunction captureCallerInfo(): string {\n const stack = new Error().stack;\n if (!stack) return '';\n\n const lines = stack.split('\\n');\n // Skip first 3 lines: Error, captureCallerInfo, and the logger method wrapper\n for (let i = 3; i < lines.length; i++) {\n const line = lines[i];\n const match = line.match(/\\(([^)]+):(\\d+):\\d+\\)/) || line.match(/at\\s+([^()\\s]+):(\\d+):\\d+/);\n\n if (match && match[1]) {\n const fullPath = match[1];\n const lineNum = match[2];\n\n // Skip internal files\n if (fullPath.includes('node_modules') || fullPath.endsWith('logger.ts') || fullPath.endsWith('logger.js')) {\n continue;\n }\n\n const workspaceRoot = process.cwd();\n let displayPath = fullPath;\n\n if (fullPath.startsWith(workspaceRoot)) {\n displayPath = fullPath.substring(workspaceRoot.length + 1);\n } else {\n const parts = fullPath.split(/[/\\\\]/);\n displayPath = parts[parts.length - 1];\n }\n\n return `${displayPath}:${lineNum}`;\n }\n }\n\n return '';\n}\n\n// dummy logger\nconst dummyLogger = {\n error: () => {},\n warn: () => {},\n info: () => {},\n debug: () => {},\n http: () => {},\n verbose: () => {},\n silly: () => {},\n};\n\n/**\n * Enhanced logger with caller info\n */\nconst enhancedLogger = {\n error: (message?: any, ...meta: any[]) => {\n const caller = captureCallerInfo();\n logger.error(message, { ...meta, caller });\n },\n warn: (message?: any, ...meta: any[]) => {\n const caller = captureCallerInfo();\n logger.warn(message, { ...meta, caller });\n },\n info: (message?: any, ...meta: any[]) => {\n const caller = captureCallerInfo();\n logger.info(message, { ...meta, caller });\n },\n debug: (message?: any, ...meta: any[]) => {\n const caller = captureCallerInfo();\n logger.debug(message, { ...meta, caller });\n },\n http: (message?: any, ...meta: any[]) => {\n const caller = captureCallerInfo();\n logger.http(message, { ...meta, caller });\n },\n verbose: (message?: any, ...meta: any[]) => {\n const caller = captureCallerInfo();\n logger.verbose(message, { ...meta, caller });\n },\n silly: (message?: any, ...meta: any[]) => {\n const caller = captureCallerInfo();\n logger.silly(message, { ...meta, caller });\n },\n};\n\n/**\n * Stream logger for streaming output\n * Provides direct write access to stdout without formatting\n * Suitable for streaming scenarios where content should be output as-is\n */\nconst streamLogger = {\n /**\n * Write content directly to stdout without formatting\n * Used for streaming output where content comes in chunks\n */\n info: (message: string) => {\n if (!getDisableLog()) {\n process.stdout.write(message);\n if (process.env.LOG_OUTPUT) {\n fs.appendFileSync(process.env.LOG_OUTPUT, message);\n }\n }\n },\n /**\n * Write error content to stderr\n */\n error: (message: string) => {\n if (!getDisableLog()) {\n process.stderr.write(message);\n if (process.env.LOG_OUTPUT) {\n fs.appendFileSync(process.env.LOG_OUTPUT, message);\n }\n }\n },\n /**\n * Write content with newline\n */\n log: (message: string) => {\n if (!getDisableLog()) {\n process.stdout.write(message + '\\n');\n if (process.env.LOG_OUTPUT) {\n fs.appendFileSync(process.env.LOG_OUTPUT, message + '\\n');\n }\n }\n },\n debug: (message: string) => {\n if (!getDisableLog()) {\n process.stdout.write(message);\n if (process.env.LOG_OUTPUT) {\n fs.appendFileSync(process.env.LOG_OUTPUT, message);\n }\n }\n },\n};\n\nexport default { enhancedLogger, dummyLogger, streamLogger, getDisableLog };\n","/**\n * Utils module exports\n */\n\nexport { AsyncExitStack } from './connections';\nexport { hasToolcall, isWriteJsonFile, convertStrToObject, extractToolcallsFromStr, executeSingleTool, executeTools } from './toolUtil';\nexport { MessageCost } from './cost';\nimport loggers from './logger';\n\nexport const logger = loggers.getDisableLog() ? loggers.dummyLogger : loggers.enhancedLogger;\n// streamLogger already handles getDisableLog() internally in createStreamLogger\nexport const streamLogger = loggers.getDisableLog() ? loggers.dummyLogger : loggers.streamLogger;\n\nif (process.env.LOG_LEVEL) {\n logger.info(`LOG_LEVEL: ${process.env.LOG_LEVEL}`);\n} else {\n logger.info('LOG_LEVEL is not set');\n}\n\nif (process.env.LOG_OUTPUT) {\n logger.info(`LOG_OUTPUT: ${process.env.LOG_OUTPUT}`);\n}\n\nif (process.env.ENABLE_LOG === 'true') {\n logger.info('ENABLE_LOG is set to true');\n} else {\n logger.info('ENABLE_LOG is not set');\n}\n","/**\n * Model configuration loader\n *\n * Converts Python's config_loader.py to TypeScript\n */\n\nimport { ModelConfig } from '../types';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as yaml from 'yaml';\nimport { logger } from '../utils';\n\n/**\n * Get config path (same as Python version)\n */\nexport function getConfigPath(): string {\n return path.join(process.env.HOME || '~', '.evolt', 'config.yaml');\n}\n\n/**\n * Load model configuration from YAML file\n */\nexport function loadModelConfig(modelName?: string): ModelConfig {\n // Use the same config path as Python version: ~/.evolt/config.yaml\n const configPath = process.env.EVOLT_CONFIG_PATH || getConfigPath();\n\n let configData: any = {};\n\n try {\n if (fs.existsSync(configPath)) {\n const fileContent = fs.readFileSync(configPath, 'utf8');\n configData = yaml.parse(fileContent);\n } else {\n logger.warn(`Config file not found at ${configPath}, using defaults`);\n // Fallback to default configuration\n configData = getDefaultConfig();\n }\n } catch (error) {\n logger.warn(`Failed to load config from ${configPath}, using defaults:`, error);\n configData = getDefaultConfig();\n }\n\n // Get model-specific configuration\n const models = configData.models || {};\n const defaultModel = modelName || configData.defaultModel || 'deepseek';\n\n const modelConfig = models[defaultModel] || models.deepseek || getDefaultModelConfig();\n\n // Extract params if exists (to match Python version)\n const params = modelConfig.params || {};\n\n return {\n provider: modelConfig.provider || 'openai',\n model: modelConfig.model || 'gpt-3.5-turbo',\n contextWindowTokens: modelConfig.contextWindowTokens || 4096,\n maxOutputTokens: params.maxCompletionTokens || params.maxTokens || modelConfig.maxOutputTokens || 1024,\n temperature: params.temperature || modelConfig.temperature || 0.7,\n topP: modelConfig.topP || 0.9,\n apiKey: modelConfig.apiKey,\n baseUrl: modelConfig.baseUrl,\n ...modelConfig,\n };\n}\n\n/**\n * Get default configuration when no config file is found\n */\nfunction getDefaultConfig(): any {\n return {\n defaultModel: 'deepseek',\n models: {\n deepseek: getDefaultModelConfig(),\n openai: {\n provider: 'openai',\n model: 'gpt-3.5-turbo',\n contextWindowTokens: 4096,\n maxOutputTokens: 1024,\n temperature: 0.7,\n topP: 0.9,\n },\n anthropic: {\n provider: 'anthropic',\n model: 'claude-3-sonnet-20240229',\n contextWindowTokens: 200000,\n maxOutputTokens: 4096,\n temperature: 0.7,\n topP: 0.9,\n },\n },\n };\n}\n\n/**\n * Get default model configuration for DeepSeek\n */\nfunction getDefaultModelConfig(): any {\n return {\n provider: 'deepseek',\n model: 'deepseek-chat',\n contextWindowTokens: 32768,\n maxOutputTokens: 4096,\n temperature: 0.7,\n topP: 0.9,\n apiKey: process.env.DEEPSEEK_API_KEY,\n baseUrl: process.env.DEEPSEEK_BASE_URL || 'https://api.deepseek.com/v1',\n };\n}\n\n/**\n * Convert type names to OpenAI format for function calling\n */\nexport function convertTypeNameToOpenai(typeName: string): string {\n const typeMap: { [key: string]: string } = {\n str: 'string',\n string: 'string',\n int: 'integer',\n integer: 'integer',\n float: 'number',\n number: 'number',\n bool: 'boolean',\n boolean: 'boolean',\n list: 'array',\n array: 'array',\n dict: 'object',\n object: 'object',\n };\n\n return typeMap[typeName.toLowerCase()] || 'string';\n}\n","/**\n * Application constants\n *\n * Converts Python's constants.py to TypeScript\n */\n\n/**\n * Default configuration values\n */\nexport const DEFAULT_CONFIG = {\n MODEL: 'deepseek',\n PROVIDER: 'deepseek',\n CONTEXT_WINDOW: 32768,\n MAX_OUTPUT_TOKENS: 4096,\n TEMPERATURE: 0.7,\n TOP_P: 0.9,\n};\n\n/**\n * Tool-related constants\n */\nexport const TOOL_CONSTANTS = {\n SYSTEM_TOOL_PREFIX: 'SystemTool.',\n USER_TOOL_PREFIX: 'UserTool.',\n AGENT_TOOL_PREFIX: 'Agent.',\n MCP_TOOL_PREFIX: 'MCP.',\n};\n\n/**\n * Message role constants\n */\nexport const MESSAGE_ROLES = {\n SYSTEM: 'system',\n USER: 'user',\n ASSISTANT: 'assistant',\n} as const;\n\n/**\n * Tool call types\n */\nexport const TOOL_CALL_TYPES = {\n SYSTEM: 'system',\n USER: 'user',\n} as const;\n\n/**\n * Environment variables\n */\nexport const ENV_VARS = {\n EVOLT_CONFIG_PATH: 'EVOLT_CONFIG_PATH',\n DEEPSEEK_API_KEY: 'DEEPSEEK_API_KEY',\n DEEPSEEK_BASE_URL: 'DEEPSEEK_BASE_URL',\n OPENAI_API_KEY: 'OPENAI_API_KEY',\n ANTHROPIC_API_KEY: 'ANTHROPIC_API_KEY',\n};\n\n/**\n * Error messages\n */\nexport const ERROR_MESSAGES = {\n CONFIG_LOAD_FAILED: 'Failed to load configuration',\n MODEL_NOT_FOUND: 'Model configuration not found',\n TOOL_NOT_REGISTERED: 'Tool not registered in tool store',\n INVALID_MESSAGE_FORMAT: 'Invalid message format',\n TOOL_EXECUTION_FAILED: 'Tool execution failed',\n};\n\n/**\n * Logging levels\n */\nexport const LOG_LEVELS = {\n DEBUG: 0,\n INFO: 1,\n WARNING: 2,\n ERROR: 3,\n} as const;\n","/**\n * Path configuration and utilities\n *\n * Converts Python's paths.py to TypeScript\n */\n\nimport * as path from 'path';\nimport * as fs from 'fs';\n\n/**\n * Get workspace directory\n */\nexport function getWorkspaceDir(): string {\n return process.env.EVOLT_WORKSPACE || path.join(process.cwd(), 'workspace');\n}\n\n/**\n * Get configuration directory\n */\nexport function getConfigDir(): string {\n return process.env.EVOLT_CONFIG_DIR || path.join(process.cwd(), 'config');\n}\n\n/**\n * Get logs directory\n */\nexport function getLogsDir(): string {\n return process.env.EVOLT_LOGS_DIR || path.join(getWorkspaceDir(), 'logs');\n}\n\n/**\n * Get cache directory\n */\nexport function getCacheDir(): string {\n return process.env.EVOLT_CACHE_DIR || path.join(getWorkspaceDir(), 'cache');\n}\n\n/**\n * Get skills directory\n */\nexport function getSkillsDir(): string {\n return process.env.EVOLT_SKILLS_DIR || path.join(getWorkspaceDir(), 'skills');\n}\n\n/**\n * Ensure directory exists\n */\nexport function ensureDir(dirPath: string): void {\n if (!fs.existsSync(dirPath)) {\n fs.mkdirSync(dirPath, { recursive: true });\n }\n}\n\n/**\n * Get absolute path relative to workspace\n */\nexport function getWorkspacePath(relativePath: string): string {\n const workspaceDir = getWorkspaceDir();\n ensureDir(workspaceDir);\n return path.join(workspaceDir, relativePath);\n}\n\n/**\n * Get absolute path relative to config directory\n */\nexport function getConfigPath(relativePath: string): string {\n const configDir = getConfigDir();\n ensureDir(configDir);\n return path.join(configDir, relativePath);\n}\n\n/**\n * Check if path is within workspace\n */\nexport function isInWorkspace(filePath: string): boolean {\n const workspaceDir = getWorkspaceDir();\n const absolutePath = path.resolve(filePath);\n return absolutePath.startsWith(path.resolve(workspaceDir));\n}\n\n/**\n * Normalize path for cross-platform compatibility\n */\nexport function normalizePath(filePath: string): string {\n return path.normalize(filePath).replace(/\\\\/g, '/');\n}\n\n/**\n * Get file extension\n */\nexport function getFileExtension(filePath: string): string {\n return path.extname(filePath).toLowerCase();\n}\n\n/**\n * Check if file exists\n */\nexport function fileExists(filePath: string): boolean {\n try {\n return fs.existsSync(filePath);\n } catch {\n return false;\n }\n}\n\n/**\n * Create temporary file path\n */\nexport function getTempFilePath(prefix: string = 'evolt'): string {\n const tempDir = path.join(getCacheDir(), 'temp');\n ensureDir(tempDir);\n const timestamp = Date.now();\n const random = Math.random().toString(36).substring(2, 8);\n return path.join(tempDir, `${prefix}_${timestamp}_${random}.tmp`);\n}\n\n// Constants for backward compatibility\nexport const WORKSPACE_DIR = getWorkspaceDir();\nexport const SKILLS_DIR = getSkillsDir();\n","/**\n * Application settings and runtime configuration\n *\n * Converts Python's settings.py to TypeScript\n */\n\nimport { LOG_LEVELS } from './constants';\n\n/**\n * Application settings interface\n */\nexport interface AppSettings {\n logLevel: number;\n verbose: boolean;\n debug: boolean;\n workspace: string;\n maxRetries: number;\n timeout: number;\n enableCache: boolean;\n enableTelemetry: boolean;\n}\n\n/**\n * Default application settings\n */\nexport const DEFAULT_SETTINGS: AppSettings = {\n logLevel: LOG_LEVELS.INFO,\n verbose: false,\n debug: false,\n workspace: process.env.EVOLT_WORKSPACE || './workspace',\n maxRetries: 3,\n timeout: 30000, // 30 seconds\n enableCache: true,\n enableTelemetry: false,\n};\n\n/**\n * Global settings instance\n */\nclass SettingsManager {\n private settings: AppSettings = { ...DEFAULT_SETTINGS };\n\n /**\n * Update settings\n */\n update(newSettings: Partial<AppSettings>): void {\n this.settings = { ...this.settings, ...newSettings };\n }\n\n /**\n * Get current settings\n */\n get(): AppSettings {\n return { ...this.settings };\n }\n\n /**\n * Reset to default settings\n */\n reset(): void {\n this.settings = { ...DEFAULT_SETTINGS };\n }\n\n /**\n * Get specific setting value\n */\n getValue<K extends keyof AppSettings>(key: K): AppSettings[K] {\n return this.settings[key];\n }\n\n /**\n * Set specific setting value\n */\n setValue<K extends keyof AppSettings>(key: K, value: AppSettings[K]): void {\n this.settings[key] = value;\n }\n}\n\n// Global settings instance\nexport const settings = new SettingsManager();\n\n/**\n * Initialize settings from environment variables\n */\nexport function initializeSettings(): void {\n const envSettings: Partial<AppSettings> = {};\n\n // Log level from environment\n const logLevelEnv = process.env.EVOLT_LOG_LEVEL;\n if (logLevelEnv) {\n const levelMap: { [key: string]: number } = {\n debug: LOG_LEVELS.DEBUG,\n info: LOG_LEVELS.INFO,\n warning: LOG_LEVELS.WARNING,\n error: LOG_LEVELS.ERROR,\n };\n const normalizedLevel = logLevelEnv.toLowerCase();\n envSettings.logLevel = levelMap[normalizedLevel] ?? LOG_LEVELS.INFO;\n }\n\n // Verbose mode from environment\n if (process.env.EVOLT_VERBOSE === 'true' || process.env.EVOLT_VERBOSE === '1') {\n envSettings.verbose = true;\n }\n\n // Debug mode from environment\n if (process.env.EVOLT_DEBUG === 'true' || process.env.EVOLT_DEBUG === '1') {\n envSettings.debug = true;\n envSettings.logLevel = LOG_LEVELS.DEBUG;\n }\n\n // Workspace from environment\n if (process.env.EVOLT_WORKSPACE) {\n envSettings.workspace = process.env.EVOLT_WORKSPACE;\n }\n\n // Max retries from environment\n if (process.env.EVOLT_MAX_RETRIES) {\n const maxRetries = parseInt(process.env.EVOLT_MAX_RETRIES, 10);\n if (!isNaN(maxRetries)) {\n envSettings.maxRetries = maxRetries;\n }\n }\n\n // Timeout from environment\n if (process.env.EVOLT_TIMEOUT) {\n const timeout = parseInt(process.env.EVOLT_TIMEOUT, 10);\n if (!isNaN(timeout)) {\n envSettings.timeout = timeout;\n }\n }\n\n // Cache from environment\n if (process.env.EVOLT_ENABLE_CACHE === 'false' || process.env.EVOLT_ENABLE_CACHE === '0') {\n envSettings.enableCache = false;\n }\n\n // Telemetry from environment\n if (process.env.EVOLT_ENABLE_TELEMETRY === 'true' || process.env.EVOLT_ENABLE_TELEMETRY === '1') {\n envSettings.enableTelemetry = true;\n }\n\n settings.update(envSettings);\n}\n\n/**\n * Get current settings (convenience function)\n */\nexport function getSettings(): AppSettings {\n return settings.get();\n}\n\n/**\n * Update settings (convenience function)\n */\nexport function updateSettings(newSettings: Partial<AppSettings>): void {\n settings.update(newSettings);\n}\n\n// Auto-initialize settings on module load\ninitializeSettings();\n","/**\n * MCP Server Configurations\n */\n\nexport const MCP_SERVERS_CONFIG: Record<string, any> = {\n playwright: {\n type: 'stdio',\n command: 'npx',\n args: ['-y', '@playwright/mcp@latest'],\n },\n filesystem: {\n type: 'stdio',\n command: 'npx',\n args: ['-y', '@modelcontextprotocol/server-filesystem', '.'],\n },\n};\n","/**\n * Tool storage and management\n *\n * Python Evolt v0.1.5 Parity - Unified ToolStore implementation\n */\n\nimport { ToolDescription, ToolStore as IToolStore } from '../types';\nimport { AsyncExitStack, createMcpConnection, MCPConnection } from '../utils/connections';\nimport { MCP_SERVERS_CONFIG } from '../configs';\nimport { logger } from '../utils';\n\n/**\n * Helper function to execute MCP tool\n */\nasync function mcpTool(connection: MCPConnection, toolName: string, args: any): Promise<string> {\n try {\n // Ensure args is an object\n const argumentsDict = typeof args === 'object' ? args : {};\n\n const result = await connection.callTool(toolName, argumentsDict);\n\n if (result && result.content) {\n for (const item of result.content) {\n if (item.type === 'text') {\n return item.text;\n }\n }\n }\n\n return 'No text content in tool response';\n } catch (e) {\n return `Error executing ${toolName}: ${e}`;\n }\n}\n\n/**\n * Unified ToolStore class (Python v0.1.5 parity)\n *\n * Replaces separate SystemToolStore and UserToolStore classes.\n * Both SYSTEM_TOOLSTORE and FUNCTION_CALLING_STORE are instances of this class.\n */\nclass ToolStore implements IToolStore {\n private tools: { [key: string]: ToolDescription } = {};\n\n /**\n * Add a tool to the store\n */\n addTool(\n name: string,\n desc: string,\n execute: (...args: any[]) => Promise<any>,\n argNames: string[],\n serverName?: string,\n inputSchema?: Record<string, any>\n ): void {\n if (name in this.tools) {\n logger.warn(`Tool ${name} already exists in store.`);\n return;\n }\n\n this.tools[name] = {\n desc,\n execute,\n argNames,\n serverName,\n inputSchema,\n };\n }\n\n /**\n * Add MCP tools to the store\n */\n async addMcpTools(agentName: string, serverName: string, stack: any): Promise<void> {\n const config = MCP_SERVERS_CONFIG[serverName];\n\n if (!config) {\n logger.warn(`No MCP server config found for ${serverName}, agent: ${agentName}.`);\n return;\n }\n\n let numMcpTools = 0;\n try {\n const connection = createMcpConnection(config);\n\n // Add to stack if provided\n if (stack && typeof stack.enterContext === 'function') {\n await stack.enterContext(connection);\n } else {\n // If no stack provided, just enter context\n // WARNING: This might leak connections if not closed manually\n logger.warn('No AsyncExitStack provided for MCP connection, connection might leak.');\n await connection.enter();\n }\n\n const toolDefinitions = await connection.listTools();\n\n for (const toolInfo of toolDefinitions) {\n if (toolInfo && toolInfo.name && toolInfo.inputSchema) {\n const toolDesc = toolInfo.description || `tool: ${toolInfo.name}`;\n\n // Helper to execute tool using the connection\n const executeFn = async (args: any) => {\n return await mcpTool(connection, toolInfo.name, args);\n };\n\n // Check if tool already exists and belongs to a different agent\n const existingTool = this.getTool(toolInfo.name);\n if (existingTool && (existingTool as any).agentName !== agentName) {\n // Tool exists but belongs to different agent, skip\n logger.warn(`Tool ${toolInfo.name} already exists in store for different agent.`);\n continue;\n }\n\n this.addTool(\n toolInfo.name,\n toolDesc,\n executeFn,\n [], // Empty argNames implies expecting a single object argument (the dict)\n serverName,\n toolInfo.inputSchema\n );\n\n // Store agent name for MCP tools\n const tool = this.getTool(toolInfo.name);\n if (tool) {\n (tool as any).agentName = agentName;\n }\n\n numMcpTools++;\n }\n }\n\n logger.info(`Loaded ${numMcpTools} MCP tools from ${serverName}, config: ${JSON.stringify(config)}.`);\n } catch (e) {\n logger.error(`Error setting up MCP server ${serverName}, config: ${JSON.stringify(config)}: ${e}`);\n }\n }\n\n /**\n * Get MCP tools schemas for a specific agent and server\n */\n getMcpToolsSchemas(agentName: string, serverName: string, provider: string): any[] {\n const toolcallSchemas: any[] = [];\n\n for (const name of this.listTools()) {\n const tool = this.getTool(name);\n if (!tool) continue;\n\n // Filter by server name if provided\n if (serverName && tool.serverName !== serverName) {\n continue;\n }\n\n // Filter by agent name for MCP tools\n if ((tool as any).agentName && (tool as any).agentName !== agentName) {\n continue;\n }\n\n if (tool.inputSchema) {\n toolcallSchemas.push(this.toToolSchema(name, tool, provider));\n }\n }\n\n return toolcallSchemas;\n }\n\n /**\n * Convert tool to schema format for specific provider\n */\n toToolSchema(name: string, tool: ToolDescription, provider: string = 'openai'): any {\n if (provider === 'openai') {\n return {\n type: 'function',\n function: {\n name,\n description: tool.desc,\n parameters: tool.inputSchema,\n },\n };\n } else if (provider === 'anthropic') {\n return {\n name,\n description: tool.desc,\n input_schema: tool.inputSchema,\n };\n }\n return {};\n }\n\n /**\n * Get tool schema by name (Python: get_toolcall_schema)\n */\n getToolcallSchema(toolName: string, provider: string = 'openai'): any {\n const tool = this.getTool(toolName);\n if (!tool) {\n return {};\n }\n return this.toToolSchema(toolName, tool, provider);\n }\n\n /**\n * Get tool by name\n */\n getTool(name: string): ToolDescription | undefined {\n return this.tools[name];\n }\n\n /**\n * Check if tool exists\n */\n hasTool(name: string): boolean {\n return name in this.tools;\n }\n\n /**\n * Get all tool names (Python: list_tools)\n */\n listTools(): string[] {\n return Object.keys(this.tools);\n }\n\n /**\n * Convert all tools to schema format\n */\n toDict(provider: string = 'openai'): any[] {\n const toolSchemas: any[] = [];\n\n for (const [name, tool] of Object.entries(this.tools)) {\n if (tool.inputSchema) {\n toolSchemas.push(this.toToolSchema(name, tool, provider));\n }\n }\n\n return toolSchemas;\n }\n\n /**\n * Get number of tools in store\n */\n get length(): number {\n return Object.keys(this.tools).length;\n }\n\n /**\n * Check if tool exists (Python __contains__ equivalent)\n */\n contains(name: string): boolean {\n return this.hasTool(name);\n }\n\n /**\n * Get tool by index operator (Python __getitem__ equivalent)\n */\n getItem(name: string): ToolDescription {\n const tool = this.getTool(name);\n if (!tool) {\n throw new Error(`Tool ${name} not found in store.`);\n }\n return tool;\n }\n\n /**\n * Get all tool entries\n */\n items(): [string, ToolDescription][] {\n return Object.entries(this.tools);\n }\n\n /**\n * Get all tool names (alias for listTools)\n */\n keys(): string[] {\n return this.listTools();\n }\n}\n\n// Global tool store instances (Python v0.1.5 parity)\n// Phase 6: Renamed from UPPER_CASE to PascalCase for TypeScript convention\nexport const SystemToolStore: IToolStore = new ToolStore();\nexport const FunctionCallingStore: IToolStore = new ToolStore();\n\n/**\n * @deprecated Use FunctionCallingStore instead. This alias will be removed in v2.0.0\n */\nexport const UserToolStore: IToolStore = FunctionCallingStore;\n","/**\n * TypeScript-native tool registration system\n * Uses configuration objects instead of docstring parsing\n */\n\nimport { SystemToolStore, FunctionCallingStore } from './toolStore';\nimport { convertTypeNameToOpenai } from '../configs/configLoader';\nimport { ToolConfig } from './toolConfig';\nimport { logger } from '../utils';\n\n/**\n * Build tool description XML from configuration\n */\nfunction buildToolDescription(fullToolName: string, config: ToolConfig[string]): string {\n let toolDesc = `\\n<${fullToolName}>\\n<${fullToolName}.description> ${config.description}\\n`;\n\n // Add parameters\n if (config.params) {\n for (const param of config.params) {\n toolDesc += `<argument name=\"${param.name}\" type=\"${param.type}\"> ${param.description} </argument>\\n`;\n }\n }\n\n // Add return type\n if (config.returns) {\n toolDesc += `<returns type=\"${config.returns.type}\"> ${config.returns.description} </returns>\\n`;\n }\n\n toolDesc += `</${fullToolName}.description>\\n`;\n\n // Add examples\n if (config.examples && config.examples.length > 0) {\n for (const example of config.examples) {\n toolDesc += `<${fullToolName}.example>\\n${example}\\n</${fullToolName}.example>\\n`;\n }\n }\n\n toolDesc += `</${fullToolName}>`;\n return toolDesc;\n}\n\n/**\n * Build OpenAI input schema from configuration\n */\nfunction buildInputSchema(config: ToolConfig[string]): Record<string, any> {\n const inputSchema = {\n type: 'object',\n properties: {} as Record<string, any>,\n required: [] as string[],\n };\n\n if (config.params) {\n for (const param of config.params) {\n inputSchema.properties[param.name] = {\n type: convertTypeNameToOpenai(param.type),\n description: param.description,\n };\n\n if (!param.optional) {\n inputSchema.required.push(param.name);\n }\n }\n }\n\n return inputSchema;\n}\n\n/**\n * Unified tool registration decorator (Python parity)\n * Registers methods to BOTH SystemToolStore and FunctionCallingStore\n *\n * This simplifies tool registration compared to using separate decorators.\n * The decorator automatically handles both XML (system) and OpenAI (user) formats.\n *\n * @param config - Tool configuration with method definitions\n * @returns Class decorator\n *\n * @example\n * ```typescript\n * @tools({\n * execute: {\n * description: \"Tool description\",\n * params: [{ name: \"param1\", type: \"string\", description: \"...\" }],\n * returns: { type: \"string\", description: \"...\" }\n * }\n * })\n * export class MyTool {\n * async execute(param1: string): Promise<string> { ... }\n * }\n * ```\n */\nexport function tools(config: ToolConfig): ClassDecorator {\n return function (target: any) {\n const instance = new target();\n\n for (const [methodName, methodConfig] of Object.entries(config)) {\n const method = (instance as any)[methodName];\n if (!method || typeof method !== 'function') {\n throw new Error(`Tool ${target.name}.${methodName} not found`);\n }\n const execute = method.bind(instance);\n\n const argNames = methodConfig.params?.map(p => p.name) || [];\n\n // Register to SystemToolStore (XML format: ClassName.methodName)\n const systemToolName = `${target.name}.${methodName}`;\n const systemToolDesc = buildToolDescription(systemToolName, methodConfig);\n SystemToolStore.addTool(systemToolName, systemToolDesc, execute, argNames, target.name);\n\n // Register to FunctionCallingStore (OpenAI format: ClassName-methodName)\n const userToolName = `${target.name}-${methodName}`;\n const userToolDesc = `\\nTool \\`${userToolName}\\` function is: ${methodConfig.description}\\n`;\n const inputSchema = buildInputSchema(methodConfig);\n FunctionCallingStore.addTool(userToolName, userToolDesc, execute, argNames, target.name, inputSchema);\n\n logger.debug(`Registered unified tool: ${systemToolName} / ${userToolName}`);\n }\n\n return target;\n };\n}\n\n/**\n * Register Agent as tool to SystemToolStore\n */\nexport function registerAgentAsTool(agents: any, verbose: boolean = false): string[] {\n if (!agents) {\n return [];\n }\n\n const agentList = Array.isArray(agents) ? agents : [agents];\n const registeredAgentNames: string[] = [];\n\n for (const agent of agentList) {\n if (!agent || typeof agent !== 'object') {\n logger.warn(`Invalid agent: ${agent}, skipping`);\n continue;\n }\n\n const agentName = `Agent.${agent.name}`;\n\n if (SystemToolStore.hasTool(agentName)) {\n logger.debug(`Agent ${agent.name} already registered as ${agentName}, change agent name`);\n registeredAgentNames.push(agentName);\n continue;\n }\n\n const toolDesc = `Delegate tasks to sub-agent ${agent.name}.\n \n Profile: ${agent.profile}\n \n Args:\n instruction (str): Detailed task description or instruction for the agent. \n Be specific about what you want the agent to accomplish.\n \n Returns:\n str: The agent's execution result, including analysis, outputs, or conclusions.\n \n Examples:\n <${agentName}>\n <instruction>\n Please analyze this data and provide insights on trends and patterns.\n </instruction>\n </${agentName}>\n `;\n\n const agentExecute = async (instruction: string): Promise<string> => {\n try {\n // Agent.run now returns string | any (with post_processor support)\n const response = await (agent as any).run(instruction);\n\n // Handle string responses (default)\n if (typeof response === 'string') {\n return response;\n }\n\n // Handle array responses (legacy ModelResponse[])\n if (Array.isArray(response)) {\n return response.map(r => String(r)).join('\\n');\n }\n\n // Handle object responses (from post_processor)\n return JSON.stringify(response);\n } catch (error) {\n logger.error(`Error executing agent ${agent.name}:`, error);\n return `Error: ${error instanceof Error ? error.message : String(error)}`;\n }\n };\n\n SystemToolStore.addTool(agentName, toolDesc, agentExecute, ['instruction'], agent.name);\n\n registeredAgentNames.push(agentName);\n if (verbose) {\n logger.info(`Registered agent as tool: ${agentName}`);\n }\n }\n\n if (registeredAgentNames.length > 0) {\n logger.debug(`Successfully registered ${registeredAgentNames.length} Agent tool(s): ${registeredAgentNames.join(', ')}`);\n }\n\n return registeredAgentNames;\n}\n","/**\n * ThinkTool - Tool for internal reasoning without executing external actions\n *\n * TypeScript-native version using configuration objects\n */\n\nimport { tools } from './toolRegister';\n\n/**\n * ThinkTool class for internal reasoning\n */\n@tools({\n execute: {\n description: 'Use the tool to think about something when complex reasoning.',\n params: [\n {\n name: 'thought',\n type: 'str',\n description: 'The thought to think about.',\n },\n ],\n returns: {\n type: 'str',\n description: 'The complete thought result.',\n },\n examples: [\n 'Good example:\\n<ThinkTool.execute><thought> your thought here </thought></ThinkTool.execute>',\n 'Bad example:\\n<ThinkTool.execute>{\"thought\":\"your thought here\"}</ThinkTool.execute>',\n ],\n },\n})\nexport class ThinkTool {\n async execute(thought: string): Promise<string> {\n return 'Thinking complete!';\n }\n}\n","/**\n * CommandTool - Command line tool for executing bash commands in background\n *\n * Converts Python's cmd_tool.py to TypeScript\n */\n\nimport { spawn, ChildProcess } from 'child_process';\nimport { tools } from './toolRegister';\nimport { ToolExecutionError } from '../types';\nimport { getCurrentManager } from './context';\nimport { logger } from '../utils';\n\n/**\n * CommandTool class for executing commands in background\n */\n@tools({\n execute: {\n description: 'Execute bash command in background (non-blocking, returns result).',\n params: [\n { name: 'command', type: 'str', description: 'The bash command to execute' },\n {\n name: 'cwd',\n type: 'Optional[str]',\n description: 'Working directory, uses current directory if None',\n optional: true,\n },\n {\n name: 'env',\n type: 'Optional[Dict[str, str]]',\n description: 'Environment variables dictionary, uses current environment if None',\n optional: true,\n },\n ],\n returns: { type: 'str', description: 'Background process startup information, including process ID and PID' },\n },\n list: {\n description: 'List all background processes.',\n returns: { type: 'str', description: 'Information about all background processes' },\n },\n stop: {\n description: 'Stop the specified background process.',\n params: [\n { name: 'processId', type: 'str', description: 'The process ID to stop' },\n {\n name: 'force',\n type: 'bool',\n description: 'Whether to force kill the process (using SIGKILL)',\n optional: true,\n },\n ],\n returns: { type: 'str', description: 'Result information of stopping the process' },\n },\n cleanup: {\n description: 'Clean up all background processes.',\n returns: { type: 'str', description: 'Cleanup result information' },\n },\n})\nexport class CommandLineTool {\n async execute(command: string, cwd?: string, env?: Record<string, string>): Promise<string> {\n try {\n // Set working directory\n const workDir: string = cwd || process.cwd();\n\n // Check if directory exists\n try {\n const fs = await import('fs');\n if (!fs.existsSync(workDir)) {\n return `Working directory does not exist: ${workDir}`;\n }\n } catch (error) {\n return `Cannot access working directory: ${workDir}`;\n }\n\n // Set environment variables\n const execEnv: NodeJS.ProcessEnv = { ...process.env, ...env };\n\n // Start process (avoid naming conflict with global process)\n const childProcess: ChildProcess = spawn(command, {\n shell: true,\n cwd: workDir,\n env: execEnv,\n stdio: ['pipe', 'pipe', 'pipe'],\n });\n\n // Get current ToolcallManager and register process\n const manager = getCurrentManager();\n if (!manager) {\n throw new ToolExecutionError('Cannot get ToolcallManager, please execute this tool through ToolcallManager');\n }\n\n const processId = manager.registerBackgroundProcess(childProcess, command, workDir);\n logger.debug(`Register background process: Command: ${command}\\n Process ID: ${processId}`);\n\n // Wait up to 5 seconds to get execution result\n return new Promise(resolve => {\n const timeout = setTimeout(async () => {\n // Process is still running after 5 seconds\n resolve(\n `COMMAND: ${command}\\n` +\n `PROCESS ID: ${processId}\\n` +\n `STATUS: The process may still be executing (waited 5 seconds, not completed)\\n` +\n `TIP: Please use the list command later to check the process status, or wait for the process to complete and then check the result`\n );\n }, 5000);\n\n // Collect output\n let stdout = '';\n let stderr = '';\n\n childProcess.stdout?.on('data', (data: Buffer) => {\n stdout += data.toString();\n });\n\n childProcess.stderr?.on('data', (data: Buffer) => {\n stderr += data.toString();\n });\n\n childProcess.on('close', (code: number | null) => {\n clearTimeout(timeout);\n\n const stdoutText = stdout.trim();\n const stderrText = stderr.trim();\n\n const resultParts = [`COMMAND: ${command}`];\n if (stdoutText) {\n resultParts.push(`STDOUT:\\n${stdoutText}`);\n }\n if (stderrText) {\n resultParts.push(`STDERR:\\n${stderrText}`);\n }\n resultParts.push(`EXIT CODE: ${code}`);\n\n resolve(resultParts.join('\\n\\n'));\n });\n\n childProcess.on('error', (error: Error) => {\n clearTimeout(timeout);\n resolve(`COMMAND: ${command}\\nERROR: ${error.message}`);\n });\n });\n } catch (error: any) {\n throw new ToolExecutionError(`Error executing background process '${command}': ${error.message}`);\n }\n }\n\n /**\n * List all background processes.\n *\n * Returns:\n * str: The natural language description of the background process list\n */\n async list(): Promise<string> {\n const manager = getCurrentManager();\n if (!manager) {\n throw new ToolExecutionError('Cannot get ToolcallManager, please execute this tool through ToolcallManager');\n }\n\n const [status, result] = manager.listBackgroundProcesses();\n return result;\n }\n\n /**\n * Stop the specified background process.\n *\n * Args:\n * process_id (str): The process ID to stop\n * force (bool): Whether to force kill the process (using SIGKILL)\n *\n * Returns:\n * str: Natural language description of the operation result\n */\n async stop(processId: string, force: boolean = false): Promise<string> {\n const manager = getCurrentManager();\n if (!manager) {\n throw new ToolExecutionError('Cannot get ToolcallManager, please execute this tool through ToolcallManager');\n }\n\n return await manager.stopBackgroundProcess(processId, force);\n }\n\n /**\n * Clean up all background processes.\n *\n * Returns:\n * str: The natural language description of the cleanup result\n */\n async cleanup(): Promise<string> {\n const manager = getCurrentManager();\n if (!manager) {\n throw new ToolExecutionError('Cannot get ToolcallManager, please execute this tool through ToolcallManager');\n }\n\n return await manager.cleanupBackgroundProcesses();\n }\n}\n","/**\n * Core type definitions for evoltagent\n */\n\nimport { PostProcessor } from './hooks';\n\n// Message types\nexport interface Message {\n role: 'system' | 'user' | 'assistant';\n content: string;\n images?: string | string[];\n type?: string;\n}\n\nexport interface ToolCall {\n type: 'system' | 'user';\n extractedResult: () => string;\n}\n\nexport interface ModelResponse {\n type: 'system' | 'user' | 'TaskCompletion';\n extractedResult: () => string | any[] | Record<string, any>;\n rawContentFromLlm?: string;\n}\n\n// Tool types\nexport interface ToolDescription {\n desc: string;\n execute: (...args: any[]) => Promise<any>;\n argNames: string[];\n serverName?: string;\n inputSchema?: Record<string, any>;\n}\n\nexport interface ToolStore {\n addTool: (\n name: string,\n desc: string,\n execute: (...args: any[]) => Promise<any>,\n argNames: string[],\n serverName?: string,\n inputSchema?: Record<string, any>\n ) => void;\n addMcpTools: (agentName: string, serverName: string, stack: any) => Promise<void>;\n getMcpToolsSchemas: (agentName: string, serverName: string, provider: string) => any[];\n getTool: (name: string) => ToolDescription | undefined;\n hasTool: (name: string) => boolean;\n listTools: () => string[];\n toDict?: (provider?: string) => any[];\n contains: (name: string) => boolean;\n getItem: (name: string) => ToolDescription;\n items: () => [string, ToolDescription][];\n keys: () => string[];\n readonly length: number;\n toToolSchema: (name: string, tool: ToolDescription, provider?: string) => any;\n getToolcallSchema: (toolName: string, provider?: string) => any;\n}\n\n// Model configuration types\nexport interface ModelConfig {\n provider: string;\n model: string;\n apiKey: string;\n baseUrl: string;\n contextWindowTokens: number;\n maxOutputTokens?: number;\n temperature?: number;\n topP?: number;\n stream?: boolean;\n [key: string]: any;\n}\n\n// Agent configuration types\nexport interface AgentConfig {\n name: string;\n profile: string;\n system?: string;\n tools?: string[];\n subAgents?: any[];\n mcpServerNames?: string[];\n modelConfig?: string | ModelConfig;\n verbose?: boolean | number;\n useFunctionCalling?: boolean;\n postProcessor?: PostProcessor;\n toolcallManagerPoolSize?: number;\n}\n\n// Environment types\nexport interface EnvironmentConfig {\n workspace?: string;\n [key: string]: any;\n}\n\n// Exception types\nexport class EvoltError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'EvoltError';\n }\n}\n\nexport class ToolExecutionError extends EvoltError {\n constructor(message: string) {\n super(message);\n this.name = 'ToolExecutionError';\n }\n}\n\nexport class ModelError extends EvoltError {\n constructor(message: string) {\n super(message);\n this.name = 'ModelError';\n }\n}\n\n// Re-export hooks types\nexport { PostProcessor };\n","/**\n * Context management for ToolcallManager\n * Separated to avoid circular dependencies\n */\n\nimport { AsyncLocalStorage } from 'async_hooks';\n\n// Use generic type to avoid circular dependency with ToolcallManager\nexport const toolcallManagerContext = new AsyncLocalStorage<any>();\n\n/**\n * Get current ToolcallManager instance\n */\nexport function getCurrentManager(): any | null {\n return toolcallManagerContext.getStore() || null;\n}\n\n/**\n * Run function within ToolcallManager context\n */\nexport function runWithManager<T>(manager: any, fn: () => Promise<T>): Promise<T> {\n return toolcallManagerContext.run(manager, fn);\n}\n","/**\n * FileEditor - Async file reader and editor\n *\n * Converts Python's file_tool.py to TypeScript\n */\n\nimport * as fs from 'fs/promises';\nimport * as pathModule from 'path';\nimport { tools } from './toolRegister';\nimport { ToolExecutionError } from '../types';\n\n/**\n * FileEditor class for async file operations\n */\n@tools({\n read: {\n description: 'Read the content of only one file. **Read one file at a time**.',\n params: [\n { name: 'path', type: 'string', description: 'The path of only one file, must include workspace directory' },\n {\n name: 'lineRange',\n type: 'string',\n description: \"Line range, format 'start-end' or 'start'. If 'all', reads entire file.\",\n optional: true,\n },\n ],\n returns: { type: 'string', description: 'The content of the file' },\n },\n write: {\n description: 'Write content to a file.',\n params: [\n { name: 'path', type: 'string', description: 'File path, must include workspace directory' },\n { name: 'content', type: 'string', description: 'Content to write' },\n ],\n returns: { type: 'string', description: 'Natural language description of operation result' },\n },\n find: {\n description: 'Find content matching specified pattern in file. **Folder searching is not supported.**',\n params: [\n { name: 'path', type: 'string', description: 'File path, must include workspace directory' },\n { name: 'pattern', type: 'string', description: 'Regex pattern to search for' },\n ],\n returns: { type: 'string', description: 'Natural language description of search results' },\n },\n findAndReplace: {\n description: 'Find and replace content matching specified pattern in file. **Folder searching is not supported.**',\n params: [\n { name: 'path', type: 'string', description: 'File path, must include workspace directory' },\n {\n name: 'pattern',\n type: 'string',\n description:\n 'Regex pattern to search for. Escape special chars [ ] ( ) . * + ? $ ^ | \\\\ with backslash. Example: CSS class \"pt-[30]\" → use pattern \"pt-\\\\[30\\\\]\"',\n },\n { name: 'replacement', type: 'string', description: 'Replacement text' },\n ],\n returns: { type: 'string', description: 'Natural language description of operation result' },\n },\n insert: {\n description: 'Insert content at specified line in file. **Folder searching is not supported.**',\n params: [\n { name: 'path', type: 'string', description: 'File path, must include workspace directory' },\n { name: 'content', type: 'string', description: 'Content to insert' },\n { name: 'line', type: 'integer', description: 'Line number to insert at. If None, appends to end of file.', optional: true },\n ],\n returns: { type: 'string', description: 'Natural language description of operation result' },\n },\n})\nexport class FileEditor {\n async read(path: string, lineRange: string = 'all'): Promise<string> {\n // Check if file exists\n try {\n await fs.access(path);\n } catch {\n throw new ToolExecutionError(`File does not exist: ${path}`);\n }\n\n try {\n // Read file with UTF-8 encoding first\n let content: string;\n try {\n content = await fs.readFile(path, 'utf-8');\n } catch (error: any) {\n // If UTF-8 fails, try other encodings\n if (error.code === 'ENCODING_NOT_SUPPORTED' || error.message.includes('encoding')) {\n // In Node.js, we'll try with latin1 which can handle binary data\n const buffer = await fs.readFile(path);\n content = buffer.toString('latin1');\n } else {\n throw error;\n }\n }\n\n const lines = content.split('\\n');\n\n if (lineRange === 'all') {\n return content;\n }\n\n // Parse line range\n if (lineRange.includes('-')) {\n try {\n const [startStr, endStr] = lineRange.split('-', 2);\n const start = parseInt(startStr) - 1; // Convert to 0-index\n const end = parseInt(endStr);\n if (start < 0 || end <= start) {\n throw new ToolExecutionError(`Line range is invalid: ${lineRange}`);\n }\n const selectedLines = lines.slice(start, end);\n return `Lines ${start + 1} to ${end} of file ${path}:\\n` + selectedLines.join('\\n');\n } catch (error: any) {\n throw new ToolExecutionError(\n `Invalid line range format when reading file ${path}: ${lineRange}, error: ${error.message}`\n );\n }\n } else {\n try {\n const lineNum = parseInt(lineRange) - 1; // Convert to 0-index\n if (lineNum < 0) {\n throw new ToolExecutionError(`Line number is less than 0: ${lineRange}`);\n }\n if (lineNum >= lines.length) {\n throw new ToolExecutionError(`Line number ${lineNum + 1} exceeds file length ${lines.length}`);\n }\n return `Line ${lineNum + 1} of file ${path}:\\n` + lines[lineNum];\n } catch (error: any) {\n throw new ToolExecutionError(\n `Invalid line number format when reading file ${path}: ${lineRange}, error: ${error.message}`\n );\n }\n }\n } catch (error: any) {\n if (error instanceof ToolExecutionError) {\n throw error;\n }\n throw new ToolExecutionError(`Error reading file ${path}: ${error.message}`);\n }\n }\n\n async write(path: string, content: string): Promise<string> {\n try {\n // Ensure directory exists\n const dirPath = pathModule.dirname(path);\n if (dirPath) {\n await fs.mkdir(dirPath, { recursive: true });\n }\n\n // Write file\n await fs.writeFile(path, content, 'utf-8');\n\n const bytesWritten = Buffer.from(content, 'utf-8').length;\n return `Successfully wrote content to file ${path}, wrote ${bytesWritten} bytes`;\n } catch (error: any) {\n if (error.code === 'EACCES') {\n throw new ToolExecutionError(`No write permission: ${path}`);\n }\n throw new ToolExecutionError(`Error writing to file ${path}: ${error.message}`);\n }\n }\n\n async find(path: string, pattern: string): Promise<string> {\n // Check if file exists\n try {\n await fs.access(path);\n } catch {\n throw new ToolExecutionError(`File does not exist: ${path}`);\n }\n\n let compiledPattern: RegExp;\n try {\n compiledPattern = new RegExp(pattern, 'g');\n } catch (error: any) {\n throw new ToolExecutionError(`Invalid regex pattern: ${pattern}, error: ${error.message}`);\n }\n\n const matches: Array<{\n lineNumber: number;\n lineContent: string;\n match: string;\n startPos: number;\n endPos: number;\n }> = [];\n\n try {\n let content: string;\n try {\n content = await fs.readFile(path, 'utf-8');\n } catch (error: any) {\n // If UTF-8 fails, try other encodings\n if (error.code === 'ENCODING_NOT_SUPPORTED' || error.message.includes('encoding')) {\n const buffer = await fs.readFile(path);\n content = buffer.toString('latin1');\n } else {\n throw error;\n }\n }\n\n const lines = content.split('\\n');\n\n for (let lineNumber = 0; lineNumber < lines.length; lineNumber++) {\n const line = lines[lineNumber];\n let match: RegExpExecArray | null;\n // Reset regex lastIndex for each line\n compiledPattern.lastIndex = 0;\n\n while ((match = compiledPattern.exec(line)) !== null) {\n matches.push({\n lineNumber: lineNumber + 1,\n lineContent: line,\n match: match[0],\n startPos: match.index,\n endPos: match.index + match[0].length,\n });\n }\n }\n } catch (error: any) {\n throw new ToolExecutionError(`Error reading file ${path}: ${error.message}`);\n }\n\n if (matches.length === 0) {\n return `No content matching pattern '${pattern}' found in file ${path}`;\n }\n\n const resultLines = [`Found ${matches.length} matches in file ${path}:`];\n for (const match of matches) {\n resultLines.push(`Line ${match.lineNumber}: ${match.match} (position ${match.startPos}-${match.endPos})`);\n resultLines.push(` Full line content: ${match.lineContent}`);\n }\n\n return resultLines.join('\\n');\n }\n\n async findAndReplace(path: string, pattern: string, replacement: string): Promise<string> {\n // Check if file exists\n try {\n await fs.access(path);\n } catch {\n throw new ToolExecutionError(`File does not exist: ${path}`);\n }\n\n let compiledPattern: RegExp;\n try {\n compiledPattern = new RegExp(pattern, 'g');\n } catch (error: any) {\n throw new ToolExecutionError(`Invalid regex pattern ${pattern}, error: ${error.message}`);\n }\n\n let content: string;\n try {\n try {\n content = await fs.readFile(path, 'utf-8');\n } catch (error: any) {\n // If UTF-8 fails, try other encodings\n if (error.code === 'ENCODING_NOT_SUPPORTED' || error.message.includes('encoding')) {\n const buffer = await fs.readFile(path);\n content = buffer.toString('latin1');\n } else {\n throw error;\n }\n }\n } catch (error: any) {\n throw new ToolExecutionError(`Error reading file ${path}: ${error.message}`);\n }\n\n // Execute replacement\n const newContent = content.replace(compiledPattern, replacement);\n const replacementCount = (content.match(compiledPattern) || []).length;\n\n // Calculate modified lines\n let modifiedLines = 0;\n if (replacementCount > 0) {\n const originalLines = content.split('\\n');\n const newLines = newContent.split('\\n');\n modifiedLines = originalLines.filter((line, index) => line !== newLines[index]).length;\n\n // Write back to file\n try {\n await fs.writeFile(path, newContent, 'utf-8');\n } catch (error: any) {\n if (error.code === 'EACCES') {\n throw new ToolExecutionError(`No write permission: ${path}`);\n }\n throw new ToolExecutionError(`Error writing to file ${path}: ${error.message}`);\n }\n }\n\n return `In file ${path}, found and replaced pattern '${pattern}' with '${replacement}', successfully replaced ${replacementCount} occurrences, modified ${modifiedLines} lines`;\n }\n\n async insert(path: string, content: string, line?: number): Promise<string> {\n try {\n await fs.access(path);\n } catch {\n throw new ToolExecutionError(`File does not exist: ${path}`);\n }\n\n let lines: string[];\n try {\n let fileContent: string;\n try {\n fileContent = await fs.readFile(path, 'utf-8');\n } catch (error: any) {\n // If UTF-8 fails, try other encodings\n if (error.code === 'ENCODING_NOT_SUPPORTED' || error.message.includes('encoding')) {\n const buffer = await fs.readFile(path);\n fileContent = buffer.toString('latin1');\n } else {\n throw error;\n }\n }\n lines = fileContent.split('\\n');\n } catch (error: any) {\n throw new ToolExecutionError(`Error reading file ${path}: ${error.message}`);\n }\n\n let actionDesc: string;\n if (line === undefined) {\n lines.push(content);\n actionDesc = `Appended content to end of file ${path}`;\n } else {\n if (!(0 < line && line <= lines.length + 1)) {\n throw new ToolExecutionError(`Line number ${line} exceeds file ${path} bounds (1 to ${lines.length + 1})`);\n }\n lines.splice(line - 1, 0, content);\n actionDesc = `Inserted content at line ${line} of file ${path}`;\n }\n\n try {\n await fs.writeFile(path, lines.join('\\n'), 'utf-8');\n return actionDesc;\n } catch (error: any) {\n if (error.code === 'EACCES') {\n throw new ToolExecutionError(`No write permission: ${path}`);\n }\n throw new ToolExecutionError(`Error writing to file ${path}: ${error.message}`);\n }\n }\n}\n","/**\n * ExtendStateMachineTool - Tool for writing ESM content to YAML files\n *\n * Converts Python's esm_tool.py to TypeScript\n */\n\nimport { tools } from './toolRegister';\nimport { ToolExecutionError } from '../types';\nimport { FileEditor } from './fileTool';\n\n/**\n * ExtendStateMachineTool class for writing ESM content\n */\n@tools({\n writeEsm: {\n description: 'Write the yaml format ExtendStateMachine(ESM) content to the yaml file',\n params: [\n {\n name: 'esmContent',\n type: 'str',\n description: 'The yaml format ESM content to write. follow the format of the ESM content.',\n },\n {\n name: 'filepath',\n type: 'str',\n description: 'The path to write the yaml format ESM content to.',\n },\n ],\n returns: {\n type: 'str',\n description: 'Successfully wrote the ESM content to the yaml file {filepath}',\n },\n },\n})\nexport class ExtendStateMachineTool {\n async writeEsm(esmContent: string, filepath: string): Promise<string> {\n try {\n // For now, we'll just write the YAML content directly\n // In a full implementation, we would validate and parse the YAML\n const fileEditor = new FileEditor();\n await fileEditor.write(filepath, esmContent);\n return `Successfully wrote the ESM content to the yaml file ${filepath}`;\n } catch (error: any) {\n throw new ToolExecutionError(`Failed to write the ESM content to the yaml file ${filepath}: ${error.message}`);\n }\n }\n}\n","/**\n * ApiTool - Tool for writing API files and generating Golang files\n *\n * Converts Python's api_tool.py to TypeScript\n */\n\nimport { tools } from './toolRegister';\nimport { FileEditor } from './fileTool';\nimport { CommandLineTool } from './cmdTool';\n\n/**\n * ApiTool class for API file operations\n */\n@tools({\n write: {\n description: 'Use the tool to write api file based on goctl.',\n params: [\n {\n name: 'apiFilePath',\n type: 'str',\n description: 'The api file path to write.',\n },\n {\n name: 'apiContent',\n type: 'str',\n description: 'The api content to write.',\n },\n ],\n returns: { type: 'str', description: 'The complete api file result.' },\n examples: [\n 'Good example:\\n<ApiTool.write><apiFilePath>to/your/workspace/your_api_file_name.api</apiFilePath><apiContent>type ( Request { Name string `path:\"name,options=[you,me]\"` } Response { Message string `json:\"message\"` } ) service greet-api { @handler GreetHandler get /greet/from/:name (Request) returns (Response) }</apiContent></ApiTool.write>',\n ],\n },\n generateGolangFilesFromApi: {\n description: 'Use the tool to generate golang files from api file.',\n params: [\n {\n name: 'apiFilePath',\n type: 'str',\n description: 'The api file path to generate golang files.',\n },\n {\n name: 'dir',\n type: 'str',\n description: 'The directory to generate golang files.',\n },\n ],\n returns: { type: 'str', description: 'The complete golang files result.' },\n },\n})\nexport class ApiTool {\n async write(apiFilePath: string, apiContent: string): Promise<string> {\n const fileEditor = new FileEditor();\n await fileEditor.write(apiFilePath, apiContent);\n return `Write api file ${apiFilePath} complete!`;\n }\n\n async generateGolangFilesFromApi(apiFilePath: string, dir: string): Promise<string> {\n const cmdTool = new CommandLineTool();\n await cmdTool.execute(`goctl api go -api ${apiFilePath} -dir ${dir}`);\n return `Generate golang files from ${apiFilePath} complete! The files are in ${dir}`;\n }\n}\n","/**\n * Reply2HumanTool - Tool for sending final human-facing replies\n *\n * Converts Python's reply2human.py to TypeScript\n */\n\nimport { tools } from './toolRegister';\n\n/**\n * Reply2HumanTool class for sending human-facing replies\n */\n@tools({\n reply: {\n description: 'Emit the reply text in a unified and formatted manner.',\n params: [{ name: 'reply', type: 'str', description: 'Raw reply text to be sent to the user.' }],\n returns: { type: 'str', description: 'The complete, formatted reply.' },\n },\n})\nexport class Reply2HumanTool {\n async reply(reply: string): Promise<string> {\n return 'Reply complete!';\n }\n}\n","/**\n * TodoListTool - Tool for editing todo list file for project\n *\n * Converts Python's todo_list.py to TypeScript\n */\n\nimport { tools } from './toolRegister';\nimport { FileEditor } from './fileTool';\n\n/**\n * TodoListTool class for managing todo lists\n */\n@tools({\n write: {\n description: 'Use the tool to write todo list file for project.',\n params: [\n { name: 'projectName', type: 'str', description: 'The project name to write todo list file.' },\n { name: 'todoList', type: 'str', description: 'The todo list to write.' },\n { name: 'projectDir', type: 'str', description: 'The project directory to write todo list file.' },\n ],\n returns: { type: 'str', description: 'The complete todo list file result.' },\n examples: [\n 'Good example:\\n<TodoListTool.write><projectName>your project name here</projectName><todoList>- [ ] Write todo list file for project\\n- [ ] Write todo list file for project</todoList><projectDir>your project directory here</projectDir></TodoListTool.write>',\n ],\n },\n})\nexport class TodoListTool {\n async write(projectName: string, todoList: string, projectDir: string): Promise<string> {\n const content = `# ${projectName}\\n## Todo List\\n${todoList}`;\n const fileEditor = new FileEditor();\n await fileEditor.write(`${projectDir}/todo.md`, content);\n return `Write todo list file for project ${projectName} complete! The file is in ${projectDir}/todo.md`;\n }\n}\n","/**\n * WriteUIDesignDocument - Tool for writing UI Design Document files\n *\n * Converts Python's design_ui.py to TypeScript\n */\n\nimport { tools } from './toolRegister';\nimport { FileEditor } from './fileTool';\n\n/**\n * WriteUIDesignDocument class for UI design document operations\n */\n@tools({\n write: {\n description: 'Use the tool to write UI Design Document files.',\n params: [\n {\n name: 'uiDesignDocumentFileDir',\n type: 'str',\n description: 'The UI Design Document file directory to write.',\n },\n {\n name: 'elements',\n type: 'List[Dict]',\n description: 'The elements to write.',\n },\n {\n name: 'composites',\n type: 'List[Dict]',\n description: 'The composites to write.',\n },\n { name: 'pages', type: 'List[Dict]', description: 'The pages to write.' },\n {\n name: 'functions',\n type: 'List[Dict]',\n description: 'The functions to write.',\n },\n {\n name: 'styles',\n type: 'List[Dict]',\n description: 'The styles to write.',\n },\n ],\n returns: {\n type: 'str',\n description: 'The complete UI Design Document files result.',\n },\n },\n})\nexport class WriteUIDesignDocument {\n async write(\n uiDesignDocumentFileDir: string,\n elements: Record<string, any>[],\n composites: Record<string, any>[],\n pages: Record<string, any>[],\n functions: Record<string, any>[],\n styles: Record<string, any>[]\n ): Promise<string> {\n const fileEditor = new FileEditor();\n\n await fileEditor.write(`${uiDesignDocumentFileDir}/AtomicElements.json`, JSON.stringify(elements, null, 2));\n await fileEditor.write(`${uiDesignDocumentFileDir}/Composites.json`, JSON.stringify(composites, null, 2));\n await fileEditor.write(`${uiDesignDocumentFileDir}/Pages.json`, JSON.stringify(pages, null, 2));\n await fileEditor.write(`${uiDesignDocumentFileDir}/Functions.json`, JSON.stringify(functions, null, 2));\n await fileEditor.write(`${uiDesignDocumentFileDir}/Styles.json`, JSON.stringify(styles, null, 2));\n\n return `Write UI Design Document files ${uiDesignDocumentFileDir} complete!`;\n }\n}\n","/**\n * ReflectTool - Tool for reflecting on the state\n *\n * Converts Python's reflect.py to TypeScript\n */\n\nimport { tools } from './toolRegister';\n\n/**\n * ReflectTool class for state reflection\n */\n@tools({\n reflect: {\n description: 'Use the tool to reflect on the state.',\n params: [{ name: 'state', type: 'str', description: 'The state to reflect on.' }],\n returns: { type: 'str', description: 'The reflected result.' },\n },\n})\nexport class ReflectTool {\n async reflect(state: string): Promise<string> {\n return 'Reflected complete!';\n }\n\n /**\n * Set the reflection for agent to see.\n */\n setReflection(reflection: string): string {\n return `<ReflectTool.setReflection><reflection>${reflection}</reflection></ReflectTool.setReflection>`;\n }\n}\n","/**\n * SkillsTool - Tool for managing skills\n *\n * Converts Python's tools/skills.py to TypeScript\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { tools } from './toolRegister';\nimport { ToolExecutionError } from '../types';\nimport { FileEditor } from './fileTool';\nimport { SKILLS_DIR } from '../configs/paths';\nimport { logger } from '../utils';\n\n/**\n * SkillsTool class for managing skills\n */\n@tools({\n readSkillDescription: {\n description: 'Read the content of the skill description file.',\n params: [{ name: 'name', type: 'str', description: 'The name of the skill' }],\n returns: { type: 'str', description: 'The content of the skill description file' },\n },\n listSkills: {\n description: 'List the skills in the skills root directory',\n returns: { type: 'str', description: 'The list of skills with their descriptions' },\n },\n})\nexport class SkillsTool {\n /**\n * Skills directory\n */\n skillsDir: string;\n\n constructor(skillsDir: string = SKILLS_DIR) {\n this.skillsDir = skillsDir;\n }\n\n /**\n * Read the content of the skill description file.\n *\n * Args:\n * name (str): The name of the skill\n *\n * Returns:\n * str: The content of the skill description file\n */\n async readSkillDescription(name: string): Promise<string> {\n const skillsPath = path.join(this.skillsDir, name, 'SKILL.md');\n\n if (!fs.existsSync(skillsPath)) {\n throw new ToolExecutionError(`Skill description file not found: ${skillsPath}`);\n }\n\n const fileEditor = new FileEditor();\n const skillDescription = await fileEditor.read(skillsPath);\n const formattedDescription = `<${name}.SkillDescription>${skillDescription}</${name}.SkillDescription>`;\n\n logger.debug(formattedDescription);\n return formattedDescription;\n }\n\n /**\n * List the skills in the skills root directory\n */\n async listSkills(): Promise<string> {\n if (!fs.existsSync(this.skillsDir)) {\n throw new ToolExecutionError(`Skills path not found: ${this.skillsDir}`);\n }\n\n // Read all SKILL.md files\n const skillsDict: Record<string, string> = {};\n const items = fs.readdirSync(this.skillsDir);\n\n for (const skillName of items) {\n const skillPath = path.join(this.skillsDir, skillName, 'SKILL.md');\n if (!fs.existsSync(skillPath)) {\n continue;\n }\n\n const fileEditor = new FileEditor();\n try {\n const skillContent = await fileEditor.read(skillPath, '1-3');\n skillsDict[skillName] = skillContent;\n } catch (error) {\n logger.warn(`Failed to read skill ${skillName}:`, error);\n }\n }\n\n const skillsInfo =\n '<SkillsInformation>' +\n Object.entries(skillsDict)\n .map(([skillName, content]) => `<${skillName}> ${content} </${skillName}>`)\n .join('\\n') +\n '</SkillsInformation>';\n\n logger.debug(skillsInfo);\n return skillsInfo;\n }\n}\n","import { exec } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { tools } from './toolRegister';\nimport { ToolExecutionError } from '../types';\n\n// Helper function to safely quote shell arguments\nfunction quote(str: string): string {\n if (/^[a-zA-Z0-9_\\-.\\/]+$/.test(str)) {\n return str;\n }\n // Replace single quotes with '\"'\"' (close quote, literal single quote, open quote)\n // This is the standard way to escape single quotes inside single-quoted strings in bash\n return `'${str.replace(/'/g, \"'\\\\''\")}'`;\n}\n\nconst gitToolConfig = {\n init: {\n description: 'Initialize a git repository.',\n params: [\n {\n name: 'cwd',\n type: 'string',\n description: 'Working directory, defaults to current directory if None',\n optional: true,\n },\n {\n name: 'bare',\n type: 'boolean',\n description: 'Create a bare repository',\n optional: true,\n },\n {\n name: 'initialBranch',\n type: 'string',\n description: 'Initial branch name',\n optional: true,\n },\n {\n name: 'config',\n type: 'object',\n description: 'Git config options {key: value}',\n optional: true,\n },\n ],\n returns: { type: 'string', description: 'Initialization result' },\n },\n status: {\n description: 'View git repository status, showing changes in working directory and staging area.',\n params: [\n {\n name: 'cwd',\n type: 'string',\n description: 'Working directory, defaults to current directory if None',\n optional: true,\n },\n {\n name: 'config',\n type: 'object',\n description: 'Git config options {key: value}',\n optional: true,\n },\n ],\n returns: { type: 'string', description: 'Output of git status' },\n },\n add: {\n description: 'Add files to staging area.',\n params: [\n {\n name: 'files',\n type: 'string',\n description: 'File paths to add, can be single file, multiple files (space separated), \".\" (all files) or path patterns',\n },\n {\n name: 'cwd',\n type: 'string',\n description: 'Working directory, defaults to current directory if None',\n optional: true,\n },\n {\n name: 'config',\n type: 'object',\n description: 'Git config options {key: value}',\n optional: true,\n },\n ],\n returns: { type: 'string', description: 'Operation result description' },\n },\n commit: {\n description: 'Commit changes in staging area.',\n params: [\n { name: 'message', type: 'string', description: 'Commit message' },\n {\n name: 'cwd',\n type: 'string',\n description: 'Working directory, defaults to current directory if None',\n optional: true,\n },\n {\n name: 'allowEmpty',\n type: 'boolean',\n description: 'Whether to allow empty commits, default False',\n optional: true,\n },\n {\n name: 'config',\n type: 'object',\n description: 'Git config options {key: value}',\n optional: true,\n },\n ],\n returns: {\n type: 'string',\n description: 'Commit result, including commit hash and change statistics',\n },\n },\n push: {\n description: 'Push local commits to remote repository.',\n params: [\n {\n name: 'remote',\n type: 'string',\n description: 'Remote repository name, defaults to origin',\n optional: true,\n },\n {\n name: 'branch',\n type: 'string',\n description: 'Branch name to push, defaults to current branch',\n optional: true,\n },\n {\n name: 'cwd',\n type: 'string',\n description: 'Working directory, defaults to current directory if None',\n optional: true,\n },\n {\n name: 'force',\n type: 'boolean',\n description: 'Whether to force push, default False',\n optional: true,\n },\n {\n name: 'config',\n type: 'object',\n description: 'Git config options {key: value}',\n optional: true,\n },\n ],\n returns: { type: 'string', description: 'Push result description' },\n },\n pull: {\n description: 'Pull latest changes from remote repository.',\n params: [\n {\n name: 'remote',\n type: 'string',\n description: 'Remote repository name, defaults to origin',\n optional: true,\n },\n {\n name: 'branch',\n type: 'string',\n description: 'Branch name to pull, defaults to current branch',\n optional: true,\n },\n {\n name: 'cwd',\n type: 'string',\n description: 'Working directory, defaults to current directory if None',\n optional: true,\n },\n {\n name: 'config',\n type: 'object',\n description: 'Git config options {key: value}',\n optional: true,\n },\n ],\n returns: { type: 'string', description: 'Pull result description' },\n },\n checkout: {\n description: 'Switch branch or checkout files.',\n params: [\n {\n name: 'target',\n type: 'string',\n description: 'Target branch name or file path',\n },\n {\n name: 'cwd',\n type: 'string',\n description: 'Working directory, defaults to current directory if None',\n optional: true,\n },\n {\n name: 'createBranch',\n type: 'boolean',\n description: \"Whether to create new branch if target doesn't exist, default True\",\n optional: true,\n },\n {\n name: 'config',\n type: 'object',\n description: 'Git config options {key: value}',\n optional: true,\n },\n ],\n returns: { type: 'string', description: 'Checkout result description' },\n },\n branch: {\n description: 'List all branches or create/delete branch.',\n params: [\n {\n name: 'name',\n type: 'string',\n description: 'Branch name, lists all branches if None',\n optional: true,\n },\n {\n name: 'cwd',\n type: 'string',\n description: 'Working directory, defaults to current directory if None',\n optional: true,\n },\n {\n name: 'delete',\n type: 'boolean',\n description: 'Whether to delete branch, default False',\n optional: true,\n },\n {\n name: 'config',\n type: 'object',\n description: 'Git config options {key: value}',\n optional: true,\n },\n ],\n returns: { type: 'string', description: 'Branch operation result' },\n },\n log: {\n description: 'View commit history.',\n params: [\n {\n name: 'cwd',\n type: 'string',\n description: 'Working directory, defaults to current directory if None',\n optional: true,\n },\n {\n name: 'maxCount',\n type: 'integer',\n description: 'Maximum number of commits to show',\n optional: true,\n },\n {\n name: 'oneline',\n type: 'boolean',\n description: 'Whether to show in oneline format, default False',\n optional: true,\n },\n {\n name: 'filePath',\n type: 'string',\n description: 'View commit history for specific file',\n optional: true,\n },\n {\n name: 'config',\n type: 'object',\n description: 'Git config options {key: value}',\n optional: true,\n },\n ],\n returns: { type: 'string', description: 'Commit history' },\n },\n diff: {\n description: 'View file differences.',\n params: [\n {\n name: 'cwd',\n type: 'string',\n description: 'Working directory, defaults to current directory if None',\n optional: true,\n },\n {\n name: 'staged',\n type: 'boolean',\n description: 'Whether to view staged changes, default False',\n optional: true,\n },\n {\n name: 'filePath',\n type: 'string',\n description: 'View diff for specific file',\n optional: true,\n },\n {\n name: 'commit1',\n type: 'string',\n description: 'First commit hash or branch name',\n optional: true,\n },\n {\n name: 'commit2',\n type: 'string',\n description: 'Second commit hash or branch name',\n optional: true,\n },\n {\n name: 'config',\n type: 'object',\n description: 'Git config options {key: value}',\n optional: true,\n },\n ],\n returns: { type: 'string', description: 'Diff content' },\n },\n remote: {\n description: 'Manage remote repositories.',\n params: [\n {\n name: 'action',\n type: 'string',\n description: 'Action type: \"list\", \"add\", \"remove\", \"set-url\", default \"list\"',\n optional: true,\n },\n {\n name: 'name',\n type: 'string',\n description: 'Remote repository name, usually \"origin\"',\n optional: true,\n },\n {\n name: 'url',\n type: 'string',\n description: 'Remote repository URL (for add or set-url)',\n optional: true,\n },\n {\n name: 'cwd',\n type: 'string',\n description: 'Working directory, defaults to current directory if None',\n optional: true,\n },\n {\n name: 'config',\n type: 'object',\n description: 'Git config options {key: value}',\n optional: true,\n },\n ],\n returns: { type: 'string', description: 'Operation result' },\n },\n clone: {\n description: 'Clone remote repository to local.',\n params: [\n { name: 'url', type: 'string', description: 'Remote repository URL' },\n {\n name: 'directory',\n type: 'string',\n description: 'Local directory name, defaults to repository name if None',\n optional: true,\n },\n {\n name: 'cwd',\n type: 'string',\n description: 'Working directory, defaults to current directory if None',\n optional: true,\n },\n {\n name: 'config',\n type: 'object',\n description: 'Git config options {key: value}',\n optional: true,\n },\n ],\n returns: { type: 'string', description: 'Clone result description' },\n },\n fetch: {\n description: 'Fetch latest changes from remote without merging.',\n params: [\n {\n name: 'remote',\n type: 'string',\n description: 'Remote repository name, defaults to origin',\n optional: true,\n },\n {\n name: 'cwd',\n type: 'string',\n description: 'Working directory, defaults to current directory if None',\n optional: true,\n },\n {\n name: 'config',\n type: 'object',\n description: 'Git config options {key: value}',\n optional: true,\n },\n ],\n returns: { type: 'string', description: 'Fetch result description' },\n },\n merge: {\n description: 'Merge specified branch into current branch.',\n params: [\n { name: 'branch', type: 'string', description: 'Branch name to merge' },\n {\n name: 'cwd',\n type: 'string',\n description: 'Working directory, defaults to current directory if None',\n optional: true,\n },\n {\n name: 'config',\n type: 'object',\n description: 'Git config options {key: value}',\n optional: true,\n },\n ],\n returns: { type: 'string', description: 'Merge result description' },\n },\n show: {\n description: 'Show detailed information about git objects (commits, tags, trees, etc).',\n params: [\n {\n name: 'object',\n type: 'string',\n description: 'Object to show (commit hash, tag, branch, etc.), defaults to HEAD',\n optional: true,\n },\n {\n name: 'cwd',\n type: 'string',\n description: 'Working directory',\n optional: true,\n },\n {\n name: 'stat',\n type: 'boolean',\n description: 'Show status info',\n optional: true,\n },\n {\n name: 'nameOnly',\n type: 'boolean',\n description: 'Show only filenames',\n optional: true,\n },\n {\n name: 'format',\n type: 'string',\n description: 'Custom format string',\n optional: true,\n },\n {\n name: 'config',\n type: 'object',\n description: 'Git config options {key: value}',\n optional: true,\n },\n ],\n returns: { type: 'string', description: 'Object details' },\n },\n tag: {\n description: 'Create, list or delete tags.',\n params: [\n {\n name: 'name',\n type: 'string',\n description: 'Tag name, lists all tags if None',\n optional: true,\n },\n {\n name: 'cwd',\n type: 'string',\n description: 'Working directory',\n optional: true,\n },\n {\n name: 'message',\n type: 'string',\n description: 'Tag message',\n optional: true,\n },\n {\n name: 'delete',\n type: 'boolean',\n description: 'Delete tag',\n optional: true,\n },\n {\n name: 'listAll',\n type: 'boolean',\n description: 'List all tags',\n optional: true,\n },\n {\n name: 'annotate',\n type: 'boolean',\n description: 'Create annotated tag',\n optional: true,\n },\n {\n name: 'config',\n type: 'object',\n description: 'Git config options {key: value}',\n optional: true,\n },\n ],\n returns: { type: 'string', description: 'Tag operation result' },\n },\n revert: {\n description: 'Revert existing commits.',\n params: [\n {\n name: 'commit',\n type: 'string',\n description: 'Commit hash to revert',\n },\n {\n name: 'cwd',\n type: 'string',\n description: 'Working directory',\n optional: true,\n },\n {\n name: 'noCommit',\n type: 'boolean',\n description: 'Revert changes but do not commit',\n optional: true,\n },\n {\n name: 'noEdit',\n type: 'boolean',\n description: 'Do not edit commit message, default True',\n optional: true,\n },\n {\n name: 'mainline',\n type: 'integer',\n description: 'Mainline parent number for merge commits',\n optional: true,\n },\n {\n name: 'config',\n type: 'object',\n description: 'Git config options {key: value}',\n optional: true,\n },\n ],\n returns: { type: 'string', description: 'Revert result' },\n },\n};\n\n@tools(gitToolConfig)\nexport class GitTool {\n /**\n * Helper method to execute git commands.\n */\n private async _executeGitCommand(\n command: string,\n cwd?: string,\n timeout: number = 30000,\n config?: Record<string, string>\n ): Promise<string> {\n const workDir = cwd || process.cwd();\n if (!fs.existsSync(workDir)) {\n throw new ToolExecutionError(`工作目录不存在: ${workDir}`);\n }\n\n // Check if it's a git repository (init and clone methods do not require check)\n const gitDir = path.join(workDir, '.git');\n const isInitOrClone = command.includes('clone') || command.includes('init');\n\n if (!fs.existsSync(gitDir) && !isInitOrClone) {\n throw new ToolExecutionError(`当前目录不是 git 仓库: ${workDir}`);\n }\n\n // Build git command with config options\n let gitCmd = 'git';\n if (config) {\n for (const [key, value] of Object.entries(config)) {\n gitCmd += ` -c ${key}=${quote(value)}`;\n }\n }\n gitCmd += ` ${command}`;\n\n return new Promise((resolve, reject) => {\n exec(gitCmd, { cwd: workDir, timeout, encoding: 'utf-8' }, (error, stdout, stderr) => {\n const stdoutText = stdout ? stdout.trim() : '';\n const stderrText = stderr ? stderr.trim() : '';\n\n if (error) {\n // Check for timeout explicitly\n if ((error as any).signal === 'SIGTERM') {\n reject(new ToolExecutionError(`Git 命令执行超时(超过 ${timeout / 1000} 秒)`));\n return;\n }\n\n const errorMsg = stderrText || stdoutText || error.message;\n reject(new ToolExecutionError(`Git 命令执行失败: ${errorMsg}`));\n return;\n }\n\n resolve(stdoutText || '命令执行成功,无输出');\n });\n });\n }\n\n /**\n * Get current branch name.\n */\n private async _getCurrentBranch(cwd?: string, config?: Record<string, string>): Promise<string> {\n const result = await this._executeGitCommand('rev-parse --abbrev-ref HEAD', cwd, 30000, config);\n return result.trim();\n }\n\n async init(cwd?: string, bare: boolean = false, initialBranch?: string, config?: Record<string, string>): Promise<string> {\n let command = 'init';\n if (bare) command += ' --bare';\n if (initialBranch) command += ` --initial-branch=${initialBranch}`;\n\n const result = await this._executeGitCommand(command, cwd, 30000, config);\n return `Git 仓库初始化完成\\n${result}`;\n }\n\n async status(cwd?: string, config?: Record<string, string>): Promise<string> {\n return await this._executeGitCommand('status', cwd, 30000, config);\n }\n\n async add(files: string, cwd?: string, config?: Record<string, string>): Promise<string> {\n // files can be \".\" multiple files etc.\n const result = await this._executeGitCommand(`add ${files}`, cwd, 30000, config);\n return `成功将文件添加到暂存区: ${files}\\n${result}`;\n }\n\n async commit(message: string, cwd?: string, allowEmpty: boolean = false, config?: Record<string, string>): Promise<string> {\n const allowEmptyFlag = allowEmpty ? ' --allow-empty' : '';\n // Use quote() helper for proper shell escaping\n const result = await this._executeGitCommand(`commit -m ${quote(message)}${allowEmptyFlag}`, cwd, 30000, config);\n return `提交成功\\n${result}`;\n }\n\n async push(\n remote: string = 'origin',\n branch?: string,\n cwd?: string,\n force: boolean = false,\n config?: Record<string, string>\n ): Promise<string> {\n const targetBranch = branch || (await this._getCurrentBranch(cwd, config));\n const forceFlag = force ? ' --force' : '';\n const result = await this._executeGitCommand(`push${forceFlag} ${remote} ${targetBranch}`, cwd, 60000, config);\n return `成功推送到 ${remote}/${targetBranch}\\n${result}`;\n }\n\n async pull(remote: string = 'origin', branch?: string, cwd?: string, config?: Record<string, string>): Promise<string> {\n const targetBranch = branch || (await this._getCurrentBranch(cwd, config));\n const result = await this._executeGitCommand(`pull ${remote} ${targetBranch}`, cwd, 60000, config);\n return `成功从 ${remote}/${targetBranch} 拉取更改\\n${result}`;\n }\n\n async checkout(target: string, cwd?: string, createBranch: boolean = true, config?: Record<string, string>): Promise<string> {\n const createFlag = createBranch ? ' -b' : '';\n const result = await this._executeGitCommand(`checkout${createFlag} ${target}`, cwd, 30000, config);\n return `成功切换到 ${target}\\n${result}`;\n }\n\n async branch(name?: string, cwd?: string, deleteBranch: boolean = false, config?: Record<string, string>): Promise<string> {\n if (!name) {\n const result = await this._executeGitCommand('branch -a', cwd, 30000, config);\n return `所有分支列表:\\n${result}`;\n } else if (deleteBranch) {\n const result = await this._executeGitCommand(`branch -d ${name}`, cwd, 30000, config);\n return `成功删除分支 ${name}\\n${result}`;\n } else {\n const result = await this._executeGitCommand(`branch ${name}`, cwd, 30000, config);\n return `成功创建分支 ${name}\\n${result}`;\n }\n }\n\n async log(\n cwd?: string,\n maxCount?: number,\n oneline: boolean = false,\n filePath?: string,\n config?: Record<string, string>\n ): Promise<string> {\n let command = 'log';\n if (oneline) command += ' --oneline';\n if (maxCount) command += ` -${maxCount}`;\n if (filePath) command += ` -- ${filePath}`;\n\n const result = await this._executeGitCommand(command, cwd, 30000, config);\n return `提交历史:\\n${result}`;\n }\n\n async diff(\n cwd?: string,\n staged: boolean = false,\n filePath?: string,\n commit1?: string,\n commit2?: string,\n config?: Record<string, string>\n ): Promise<string> {\n let command = 'diff';\n if (staged) command += ' --staged';\n if (commit1 && commit2) {\n command += ` ${commit1} ${commit2}`;\n } else if (commit1) {\n command += ` ${commit1}`;\n }\n if (filePath) command += ` -- ${filePath}`;\n\n const result = await this._executeGitCommand(command, cwd, 30000, config);\n return `差异内容:\\n${result}`;\n }\n\n async remote(action: string = 'list', name?: string, url?: string, cwd?: string, config?: Record<string, string>): Promise<string> {\n if (action === 'list') {\n const result = await this._executeGitCommand('remote -v', cwd, 30000, config);\n return `远程仓库列表:\\n${result}`;\n } else if (action === 'add') {\n if (!name || !url) throw new ToolExecutionError('添加远程仓库需要提供 name 和 url 参数');\n const result = await this._executeGitCommand(`remote add ${name} ${url}`, cwd, 30000, config);\n return `成功添加远程仓库 ${name}: ${url}\\n${result}`;\n } else if (action === 'remove') {\n if (!name) throw new ToolExecutionError('删除远程仓库需要提供 name 参数');\n const result = await this._executeGitCommand(`remote remove ${name}`, cwd, 30000, config);\n return `成功删除远程仓库 ${name}\\n${result}`;\n } else if (action === 'set-url') {\n if (!name || !url) throw new ToolExecutionError('设置远程仓库 URL 需要提供 name 和 url 参数');\n const result = await this._executeGitCommand(`remote set-url ${name} ${url}`, cwd, 30000, config);\n return `成功设置远程仓库 ${name} 的 URL 为 {url}\\n${result}`;\n } else {\n throw new ToolExecutionError(`不支持的操作类型: ${action},支持的操作: list, add, remove, set-url`);\n }\n }\n\n async clone(url: string, directory?: string, cwd?: string, config?: Record<string, string>): Promise<string> {\n const workDir = cwd || process.cwd();\n let command = `clone ${url}`;\n if (directory) command += ` ${directory}`;\n\n // clone takes time, set timeout to 120s\n const result = await this._executeGitCommand(command, workDir, 120000, config);\n return `成功克隆仓库 ${url}\\n${result}`;\n }\n\n async fetch(remote: string = 'origin', cwd?: string, config?: Record<string, string>): Promise<string> {\n const result = await this._executeGitCommand(`fetch ${remote}`, cwd, 60000, config);\n return `成功从 ${remote} 获取更新\\n${result}`;\n }\n\n async merge(branch: string, cwd?: string, config?: Record<string, string>): Promise<string> {\n const noFfFlag = '';\n const result = await this._executeGitCommand(`merge${noFfFlag} ${branch}`, cwd, 30000, config);\n return `成功合并分支 ${branch}\\n${result}`;\n }\n\n async show(\n object?: string,\n cwd?: string,\n stat: boolean = false,\n nameOnly: boolean = false,\n format?: string,\n config?: Record<string, string>\n ): Promise<string> {\n let command = 'show';\n if (object) command += ` ${object}`;\n if (stat) command += ' --stat';\n if (nameOnly) command += ' --name-only';\n if (format) command += ` --format=${format}`;\n\n const result = await this._executeGitCommand(command, cwd, 30000, config);\n return `显示对象信息:\\n${result}`;\n }\n\n async tag(\n name?: string,\n cwd?: string,\n message?: string,\n deleteTag: boolean = false,\n listAll: boolean = false,\n annotate: boolean = false,\n config?: Record<string, string>\n ): Promise<string> {\n if (!name) {\n let command = 'tag';\n if (listAll) command += ' -l';\n const result = await this._executeGitCommand(command, cwd, 30000, config);\n return `标签列表:\\n${result}`;\n } else if (deleteTag) {\n const result = await this._executeGitCommand(`tag -d ${name}`, cwd, 30000, config);\n return `成功删除标签 ${name}\\n${result}`;\n } else {\n let command = 'tag';\n if (annotate || message) command += ' -a';\n if (message) command += ` -m ${quote(message)}`;\n command += ` ${name}`;\n const result = await this._executeGitCommand(command, cwd, 30000, config);\n return `成功创建标签 ${name}\\n${result}`;\n }\n }\n\n async revert(\n commit: string,\n cwd?: string,\n noCommit: boolean = false,\n noEdit: boolean = true,\n mainline?: number,\n config?: Record<string, string>\n ): Promise<string> {\n let command = 'revert';\n if (noCommit) command += ' --no-commit';\n if (noEdit) command += ' --no-edit';\n if (mainline) command += ` -m ${mainline}`;\n command += ` ${commit}`;\n\n const result = await this._executeGitCommand(command, cwd, 30000, config);\n return `成功撤销提交 ${commit}\\n${result}`;\n }\n}\n","/**\n * Model abstraction layer using official SDKs\n *\n * Provides a unified interface for multiple LLM providers:\n * - OpenAI (and compatible APIs like DeepSeek)\n * - Anthropic Claude\n * - Google Gemini\n */\n\nimport { ModelConfig, ModelError } from './types';\nimport { loadModelConfig } from './configs/configLoader';\nimport OpenAI from 'openai';\nimport Anthropic from '@anthropic-ai/sdk';\nimport { GoogleGenerativeAI } from '@google/generative-ai';\nimport { logger, streamLogger } from './utils';\n\n/**\n * Model response interface\n */\nexport interface ModelResponse {\n type: 'system' | 'user' | 'TaskCompletion';\n extractedResult: () => string | any[] | Record<string, any>;\n rawContentFromLlm?: string;\n}\n\n/**\n * Model class for interacting with LLM providers\n * Uses official SDKs for better reliability and type safety\n */\nexport class Model {\n private modelName: string;\n private config: ModelConfig;\n private openaiClient?: OpenAI;\n private anthropicClient?: Anthropic;\n private geminiClient?: GoogleGenerativeAI;\n\n constructor(model?: string | ModelConfig) {\n if (typeof model === 'string' || model === undefined) {\n this.modelName = model || 'deepseek';\n this.config = loadModelConfig(this.modelName);\n } else {\n // model is ModelConfig object\n this.config = model;\n this.modelName = model.model || 'deepseek';\n }\n\n // Initialize the appropriate client based on provider\n this._initializeClient();\n }\n\n /**\n * Initialize the appropriate SDK client based on provider\n */\n private _initializeClient(): void {\n const provider = this.config.provider.toLowerCase();\n\n switch (provider) {\n case 'openai':\n this.openaiClient = new OpenAI({\n apiKey: this.config.apiKey || process.env.OPENAI_API_KEY,\n baseURL: this.config.baseUrl,\n timeout: 60000,\n });\n break;\n\n case 'deepseek':\n // DeepSeek uses OpenAI-compatible API\n this.openaiClient = new OpenAI({\n apiKey: this.config.apiKey || process.env.DEEPSEEK_API_KEY,\n baseURL: this.config.baseUrl || 'https://api.deepseek.com',\n timeout: 60000,\n });\n break;\n\n case 'anthropic':\n if (this.config.baseUrl.endsWith('/v1') || this.config.baseUrl.endsWith('v1/')) {\n this.config.baseUrl = this.config.baseUrl.slice(0, -3);\n }\n this.anthropicClient = new Anthropic({\n apiKey: this.config.apiKey || process.env.ANTHROPIC_API_KEY,\n baseURL: this.config.baseUrl,\n timeout: 60000,\n });\n break;\n\n case 'gemini':\n const apiKey = this.config.apiKey || process.env.GEMINI_API_KEY || '';\n this.geminiClient = new GoogleGenerativeAI(apiKey);\n break;\n\n default:\n throw new ModelError(`Unsupported provider: ${provider}`);\n }\n }\n\n /**\n * Asynchronous chat completion\n */\n async achat(messages: any[], tools?: any[], stream: boolean = true): Promise<ModelResponse[]> {\n const provider = this.config.provider.toLowerCase();\n const useStream = stream !== undefined ? stream : !!this.config.stream;\n\n try {\n switch (provider) {\n case 'openai':\n case 'deepseek':\n return await this._callOpenAICompatible(messages, tools, useStream);\n case 'anthropic':\n return await this._callAnthropic(messages, tools, useStream);\n case 'gemini':\n return await this._callGemini(messages, tools, useStream);\n default:\n throw new ModelError(`Unsupported provider: ${provider}`);\n }\n } catch (error) {\n logger.error(`Model call failed: ${error}`);\n throw error;\n }\n }\n\n /**\n * Call OpenAI-compatible API (OpenAI, DeepSeek, etc.)\n */\n private async _callOpenAICompatible(messages: any[], tools?: any[], stream: boolean = false): Promise<ModelResponse[]> {\n if (!this.openaiClient) {\n throw new ModelError('OpenAI client not initialized');\n }\n\n try {\n const params: any = {\n model: this.config.model || 'gpt-3.5-turbo',\n messages: messages,\n temperature: this.config.temperature || 0.7,\n max_tokens: this.config.maxOutputTokens || 1024,\n top_p: this.config.topP || 0.9,\n stream: stream,\n };\n\n // Add tools if provided\n if (tools && tools.length > 0) {\n params.tools = tools;\n params.tool_choice = 'auto';\n }\n\n if (stream) {\n const streamResponse = (await this.openaiClient.chat.completions.create({\n ...params,\n stream: true,\n })) as any; // AsyncIterable type\n\n let fullContent = '';\n let toolCallsMap: Record<number, any> = {};\n\n for await (const chunk of streamResponse) {\n const delta = chunk.choices[0]?.delta;\n if (!delta) continue;\n\n // Handle content\n if (delta.content) {\n streamLogger.info(delta.content);\n fullContent += delta.content;\n }\n\n // Handle tool calls\n if (delta.tool_calls) {\n for (const tc of delta.tool_calls) {\n const index = tc.index;\n\n if (!toolCallsMap[index]) {\n toolCallsMap[index] = {\n id: tc.id || '',\n type: 'function',\n function: {\n name: tc.function?.name || '',\n arguments: tc.function?.arguments || '',\n },\n };\n if (tc.function?.name) {\n streamLogger.info(`\\nTool Call: ${tc.function.name}\\nArguments: `);\n }\n } else {\n if (tc.function?.arguments) {\n toolCallsMap[index].function.arguments += tc.function.arguments;\n streamLogger.info(tc.function.arguments);\n }\n }\n }\n }\n }\n streamLogger.info('\\n');\n\n const toolCalls = Object.values(toolCallsMap);\n const hasContent = fullContent.trim().length > 0;\n const hasToolCalls = toolCalls.length > 0;\n\n if (hasToolCalls) {\n return [\n {\n type: 'user',\n extractedResult: () => ({\n role: 'assistant',\n content: fullContent,\n tool_calls: toolCalls,\n }),\n },\n ];\n }\n\n // Return as system response (may contain XML tool calls or TaskCompletion)\n // Agent loop will extract tools and exit when no more tools remain\n return [\n {\n type: 'system',\n extractedResult: () => fullContent,\n rawContentFromLlm: fullContent,\n },\n ];\n } else {\n // Non-streaming\n const response = await this.openaiClient.chat.completions.create(params);\n\n if (!response.choices || response.choices.length === 0) {\n throw new ModelError('No choices returned from OpenAI API');\n }\n\n const message = response.choices[0].message;\n const messageContent = message.content || '';\n const hasToolCalls = message.tool_calls && message.tool_calls.length > 0;\n\n // Handle tool calls\n if (hasToolCalls) {\n return [\n {\n type: 'user',\n extractedResult: () => ({\n role: 'assistant',\n content: messageContent,\n tool_calls: message.tool_calls,\n }),\n },\n ];\n }\n\n // Return as system response (may contain XML tool calls or TaskCompletion)\n // Agent loop will extract tools and exit when no more tools remain\n return [\n {\n type: 'system',\n extractedResult: () => messageContent,\n rawContentFromLlm: messageContent,\n },\n ];\n }\n } catch (error: any) {\n const errorMsg = error.message || 'Unknown error';\n throw new ModelError(`OpenAI-compatible API call failed: ${errorMsg}, model config: ${JSON.stringify(this.config)}`);\n }\n }\n\n /**\n * Call Anthropic API\n */\n private async _callAnthropic(messages: any[], tools?: any[], stream: boolean = false): Promise<ModelResponse[]> {\n if (!this.anthropicClient) {\n throw new ModelError('Anthropic client not initialized');\n }\n\n try {\n // Anthropic requires system message to be separate\n const systemMessage = messages.find((m: any) => m.role === 'system');\n const nonSystemMessages = messages.filter((m: any) => m.role !== 'system');\n\n const params: any = {\n model: this.config.model || 'claude-3-sonnet-20240229',\n messages: nonSystemMessages,\n max_tokens: this.config.maxOutputTokens || 4096,\n temperature: this.config.temperature || 0.7,\n top_p: this.config.topP || 0.9,\n stream: stream,\n };\n\n if (systemMessage) {\n params.system = systemMessage.content;\n }\n\n // Add tools if provided (convert to Anthropic format)\n if (tools && tools.length > 0) {\n params.tools = tools.map((tool: any) => ({\n name: tool.function?.name || tool.name,\n description: tool.function?.description || tool.description,\n input_schema: tool.function?.parameters || tool.input_schema,\n }));\n }\n\n if (stream) {\n const streamResponse = await this.anthropicClient.messages.stream({\n ...params,\n stream: true,\n });\n\n let fullContent = '';\n let toolUses: any[] = [];\n\n for await (const event of streamResponse) {\n if (event.type === 'content_block_start') {\n if (event.content_block.type === 'tool_use') {\n const toolUse = event.content_block;\n streamLogger.info(`\\nTool Call: ${toolUse.name}\\nArguments: `);\n }\n } else if (event.type === 'content_block_delta') {\n if (event.delta.type === 'text_delta') {\n streamLogger.info(event.delta.text);\n fullContent += event.delta.text;\n } else if (event.delta.type === 'input_json_delta') {\n streamLogger.info(event.delta.partial_json);\n }\n } else if (event.type === 'message_delta') {\n // Handle message delta (e.g., stop_reason)\n }\n }\n streamLogger.info('\\n');\n\n // For streaming, we need to collect tool_use blocks from the final message\n // Since the SDK doesn't provide a clean way to get this during streaming,\n // we'll make another non-streaming call or handle differently\n const hasContent = fullContent.trim().length > 0;\n const hasToolUses = toolUses.length > 0;\n\n // Return as system response (may contain XML tool calls or TaskCompletion)\n // Agent loop will extract tools and exit when no more tools remain\n return [\n {\n type: 'system',\n extractedResult: () => fullContent || toolUses,\n rawContentFromLlm: fullContent,\n },\n ];\n } else {\n // Non-streaming\n const response = await this.anthropicClient.messages.create(params);\n\n if (!response.content || response.content.length === 0) {\n throw new ModelError('No content returned from Anthropic API');\n }\n\n // Handle tool calls\n const toolUse = response.content.find((c: any) => c.type === 'tool_use');\n if (toolUse) {\n return [\n {\n type: 'system',\n extractedResult: () => [toolUse],\n },\n ];\n }\n\n // Handle regular text response\n const textContent: any = response.content.find((c: any) => c.type === 'text');\n const messageContent = textContent?.text || '';\n\n // Return as system response (may contain XML tool calls or TaskCompletion)\n // Agent loop will extract tools and exit when no more tools remain\n return [\n {\n type: 'system',\n extractedResult: () => messageContent,\n rawContentFromLlm: messageContent,\n },\n ];\n }\n } catch (error: any) {\n const errorMsg = error.message || 'Unknown error';\n throw new ModelError(`Anthropic API call failed: ${errorMsg}`);\n }\n }\n\n /**\n * Call Google Gemini API\n */\n private async _callGemini(messages: any[], tools?: any[], stream: boolean = false): Promise<ModelResponse[]> {\n if (!this.geminiClient) {\n throw new ModelError('Gemini client not initialized');\n }\n\n try {\n const modelName = this.config.model || 'gemini-pro';\n const model = this.geminiClient.getGenerativeModel({\n model: modelName,\n generationConfig: {\n temperature: this.config.temperature || 0.7,\n maxOutputTokens: this.config.maxOutputTokens || 2048,\n topP: this.config.topP || 0.9,\n },\n });\n\n // Convert OpenAI format messages to Gemini format\n const contents = this._convertMessagesToGeminiFormat(messages);\n\n if (stream) {\n const result = await model.generateContentStream({ contents });\n\n let fullContent = '';\n let functionCalls: any[] = [];\n\n for await (const chunk of result.stream) {\n try {\n const chunkText = await chunk.text();\n if (chunkText) {\n streamLogger.info(chunkText);\n fullContent += chunkText;\n }\n } catch (e) {\n // text() may throw if there's no text in this chunk\n }\n\n // Check for function calls\n const candidates = chunk.candidates;\n if (candidates && candidates[0]?.content?.parts) {\n for (const part of candidates[0].content.parts) {\n if (part.functionCall) {\n functionCalls.push(part.functionCall);\n }\n }\n }\n }\n streamLogger.info('\\n');\n\n const hasContent = fullContent.trim().length > 0;\n const hasFunctionCalls = functionCalls.length > 0;\n\n if (hasFunctionCalls) {\n // Convert Gemini function calls to OpenAI format\n const toolCalls = functionCalls.map((fc: any, index: number) => ({\n id: `call_${Date.now()}_${index}`,\n type: 'function',\n function: {\n name: fc.name,\n arguments: JSON.stringify(fc.args),\n },\n }));\n\n return [\n {\n type: 'user',\n extractedResult: () => ({\n role: 'assistant',\n content: fullContent,\n tool_calls: toolCalls,\n }),\n },\n ];\n }\n\n // Return as system response (may contain XML tool calls or TaskCompletion)\n // Agent loop will extract tools and exit when no more tools remain\n return [\n {\n type: 'system',\n extractedResult: () => fullContent,\n rawContentFromLlm: fullContent,\n },\n ];\n } else {\n // Non-streaming\n const result = await model.generateContent({ contents });\n const response = result.response;\n\n if (!response.candidates || response.candidates.length === 0) {\n throw new ModelError('No candidates returned from Gemini API');\n }\n\n const candidate = response.candidates[0];\n const content = candidate.content;\n\n if (!content || !content.parts || content.parts.length === 0) {\n throw new ModelError('No content parts returned from Gemini API');\n }\n\n // Check for function calls\n const functionCalls = content.parts.filter((part: any) => part.functionCall);\n const hasFunctionCalls = functionCalls.length > 0;\n\n if (hasFunctionCalls) {\n const toolCalls = functionCalls.map((part: any, index: number) => ({\n id: `call_${Date.now()}_${index}`,\n type: 'function',\n function: {\n name: part.functionCall.name,\n arguments: JSON.stringify(part.functionCall.args),\n },\n }));\n\n const textParts = content.parts.filter((part: any) => part.text);\n const textContent = textParts.map((part: any) => part.text).join('');\n\n return [\n {\n type: 'user',\n extractedResult: () => ({\n role: 'assistant',\n content: textContent,\n tool_calls: toolCalls,\n }),\n },\n ];\n }\n\n // Handle regular text response\n const textParts = content.parts.filter((part: any) => part.text);\n const textContent = textParts.map((part: any) => part.text).join('');\n\n // Return as system response (may contain XML tool calls or TaskCompletion)\n // Agent loop will extract tools and exit when no more tools remain\n return [\n {\n type: 'system',\n extractedResult: () => textContent,\n rawContentFromLlm: textContent,\n },\n ];\n }\n } catch (error: any) {\n const errorMsg = error.message || 'Unknown error';\n throw new ModelError(`Gemini API call failed: ${errorMsg}`);\n }\n }\n\n /**\n * Convert OpenAI format messages to Gemini format\n */\n private _convertMessagesToGeminiFormat(messages: any[]): any[] {\n const contents: any[] = [];\n\n for (const message of messages) {\n if (message.role === 'system') {\n // Gemini doesn't have a separate system role, add as user message\n contents.push({\n role: 'user',\n parts: [{ text: message.content }],\n });\n } else if (message.role === 'user') {\n contents.push({\n role: 'user',\n parts: [{ text: message.content }],\n });\n } else if (message.role === 'assistant') {\n const parts: any[] = [];\n\n if (message.content) {\n parts.push({ text: message.content });\n }\n\n if (message.tool_calls) {\n for (const toolCall of message.tool_calls) {\n parts.push({\n functionCall: {\n name: toolCall.function.name,\n args: JSON.parse(toolCall.function.arguments),\n },\n });\n }\n }\n\n contents.push({\n role: 'model',\n parts: parts,\n });\n } else if (message.role === 'tool') {\n // Tool result message\n contents.push({\n role: 'function',\n parts: [\n {\n functionResponse: {\n name: message.name,\n response: {\n content: message.content,\n },\n },\n },\n ],\n });\n }\n }\n\n return contents;\n }\n\n /**\n * Get model configuration\n */\n getConfig(): ModelConfig {\n return { ...this.config };\n }\n\n /**\n * Get model name\n */\n getName(): string {\n return this.modelName;\n }\n\n /**\n * Check if model supports tool calling\n */\n supportsToolCalling(): boolean {\n const supportedModels = ['gpt-3.5-turbo', 'gpt-4', 'claude-3', 'deepseek-chat', 'gemini-pro', 'gemini-1.5'];\n return supportedModels.some(model => this.config.model.includes(model));\n }\n}\n","/**\n * Message class for conversation history\n *\n * Converts Python's message.py to TypeScript\n */\n\nimport * as fs from 'fs';\nimport { Message as MessageType } from '../types';\n\n/**\n * Content types for Vision API\n */\ninterface TextContent {\n type: 'text';\n text: string;\n}\n\ninterface ImageUrlContent {\n type: 'image_url';\n image_url: { url: string };\n}\n\ntype ContentPart = TextContent | ImageUrlContent;\n\n/**\n * Message class representing a single message in conversation\n */\nexport class Message implements MessageType {\n role: 'system' | 'user' | 'assistant';\n content: string;\n images?: string | string[];\n type?: string;\n\n constructor(role: 'system' | 'user' | 'assistant', content: string, images?: string | string[], type?: string) {\n this.role = role;\n this.content = content;\n this.images = images;\n this.type = type;\n }\n\n /**\n * Create message from user input\n */\n static fromUserMsg(content: string, images?: string | string[]): Message {\n return new Message('user', content, images);\n }\n\n /**\n * Create message from assistant response\n */\n static fromAssistantMsg(content: string): Message {\n return new Message('assistant', content);\n }\n\n /**\n * Create system message\n */\n static fromSystemMsg(content: string): Message {\n return new Message('system', content);\n }\n\n /**\n * Convert to plain object for API calls\n */\n toObject(): any {\n const obj: any = {\n role: this.role,\n content: this.content,\n };\n\n if (this.images) {\n obj.images = this.images;\n }\n\n if (this.type) {\n obj.type = this.type;\n }\n\n return obj;\n }\n\n /**\n * Check if message contains images\n */\n hasImages(): boolean {\n return !!this.images && (Array.isArray(this.images) ? this.images.length > 0 : true);\n }\n\n /**\n * Get message content length\n */\n getContentLength(): number {\n return this.content.length;\n }\n\n /**\n * Convert to string representation\n */\n toString(): string {\n return `${this.role}: ${this.content}`;\n }\n\n /**\n * Convert to OpenAI Vision API format with base64-encoded images\n * This method handles:\n * - HTTP/HTTPS URLs: Downloads and converts to base64\n * - Local file paths: Reads file and converts to base64\n * - Already base64 strings: Passes through\n */\n async toChatMessage(): Promise<Record<string, any>> {\n const role = this.role;\n\n if (!this.hasImages()) {\n return { role, content: this.content };\n }\n\n const content: ContentPart[] = [{ type: 'text', text: this.content }];\n const imageArray = Array.isArray(this.images) ? this.images : [this.images!];\n\n for (const img of imageArray) {\n let base64Data: string;\n\n if (img.startsWith('http://') || img.startsWith('https://')) {\n base64Data = await this.encodeHttpImage(img);\n } else if (fs.existsSync(img)) {\n base64Data = await this.encodeLocalFile(img);\n } else {\n // Assume already base64\n base64Data = img;\n }\n\n const mimeType = this.getMimeType(img);\n content.push({\n type: 'image_url',\n image_url: { url: `data:${mimeType};base64,${base64Data}` },\n });\n }\n\n return { role, content };\n }\n\n /**\n * Get MIME type from file path or URL\n */\n private getMimeType(path: string): string {\n const ext = path.toLowerCase().split('.').pop();\n const mimeTypes: Record<string, string> = {\n png: 'image/png',\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n gif: 'image/gif',\n webp: 'image/webp',\n bmp: 'image/bmp',\n };\n return mimeTypes[ext || ''] || 'image/jpeg';\n }\n\n /**\n * Encode local file to base64\n */\n private async encodeLocalFile(filePath: string): Promise<string> {\n const fileBuffer = await fs.promises.readFile(filePath);\n return fileBuffer.toString('base64');\n }\n\n /**\n * Fetch and encode HTTP image to base64\n */\n private async encodeHttpImage(url: string): Promise<string> {\n const response = await fetch(url);\n if (!response.ok) {\n throw new Error(`Failed to fetch image from ${url}: ${response.statusText}`);\n }\n const buffer = await response.arrayBuffer();\n return Buffer.from(buffer).toString('base64');\n }\n}\n","/**\n * Message history management\n *\n * Converts Python's message_history.py to TypeScript\n */\n\nimport { Message } from '../schemas/message';\nimport { Message as MessageType } from '../types';\n\n/**\n * Message history class for managing conversation context\n */\nexport class MessageHistory {\n private messages: (Message | Record<string, any>)[] = [];\n private systemPrompt: string;\n private model: string;\n private contextWindowTokens: number;\n private currentTokens: number = 0;\n\n constructor(model: string, system: string, contextWindowTokens: number) {\n this.model = model;\n this.systemPrompt = system;\n this.contextWindowTokens = contextWindowTokens;\n\n // Add system message if provided\n if (system) {\n const systemMessage = new Message('system', system);\n this.messages.push(systemMessage);\n this.currentTokens += this.estimateTokens(system);\n }\n }\n\n /**\n * Add a message to history\n */\n addMessage(message: Message): void;\n addMessage(role: 'system' | 'user' | 'assistant' | 'tool', content: string): void;\n addMessage(messageObject: any): void;\n addMessage(arg1: Message | 'system' | 'user' | 'assistant' | 'tool' | any, arg2?: string): void {\n let message: Message | Record<string, any>;\n\n if (arg1 instanceof Message) {\n message = arg1;\n } else if (typeof arg1 === 'string') {\n // Role + content format\n message = new Message(arg1 as any, arg2!);\n } else if (typeof arg1 === 'object' && arg1 !== null) {\n // Object format (e.g., tool call messages)\n // Store as-is without converting to Message instance\n this.messages.push(arg1);\n const contentStr = arg1.content || JSON.stringify(arg1);\n this.currentTokens += this.estimateTokens(contentStr);\n return;\n } else {\n throw new Error(`Invalid message format: ${arg1}`);\n }\n\n this.messages.push(message);\n this.currentTokens += this.estimateTokens(message.content);\n }\n\n /**\n * Get all messages\n */\n getMessages(): (Message | Record<string, any>)[] {\n return [...this.messages];\n }\n\n /**\n * Get messages formatted for API calls\n * Async version to handle base64 image encoding\n */\n async formatForApi(): Promise<any[]> {\n const results: any[] = [];\n for (const msg of this.messages) {\n if (msg instanceof Message) {\n if (msg.hasImages()) {\n results.push(await msg.toChatMessage());\n } else {\n results.push(msg.toObject());\n }\n } else if (typeof msg.toObject === 'function') {\n results.push(msg.toObject());\n } else {\n // Return plain object as is\n results.push(msg);\n }\n }\n return results;\n }\n\n /**\n * Update system prompt\n */\n updateSystem(system: string): void {\n // Remove existing system message if any\n this.messages = this.messages.filter(msg => {\n if (msg instanceof Message) {\n return msg.role !== 'system';\n }\n return msg.role !== 'system';\n });\n this.currentTokens = 0;\n\n // Add new system message\n if (system) {\n const systemMessage = new Message('system', system);\n this.messages.unshift(systemMessage);\n this.currentTokens += this.estimateTokens(system);\n }\n\n // Recalculate tokens for all messages\n for (const message of this.messages) {\n if (message instanceof Message) {\n if (message.role !== 'system') {\n this.currentTokens += this.estimateTokens(message.content);\n }\n } else {\n const contentStr = message.content || JSON.stringify(message);\n this.currentTokens += this.estimateTokens(contentStr);\n }\n }\n }\n\n /**\n * Truncate history to fit context window\n * Preserves tool call chains: assistant(with tool_calls) → tool messages\n */\n truncate(): void {\n if (this.currentTokens <= this.contextWindowTokens) {\n return;\n }\n\n // Find system message\n let systemMessageIndex = -1;\n for (let i = 0; i < this.messages.length; i++) {\n const msg = this.messages[i];\n if ((msg instanceof Message && msg.role === 'system') || msg.role === 'system') {\n systemMessageIndex = i;\n break;\n }\n }\n\n const systemMessage = systemMessageIndex >= 0 ? this.messages[systemMessageIndex] : null;\n const otherMessages = this.messages.filter((msg, index) => index !== systemMessageIndex);\n\n // Build a map of tool_call_id -> assistant message index for dependency tracking\n const toolCallDependencies = new Map<string, number>();\n for (let i = 0; i < otherMessages.length; i++) {\n const msg = otherMessages[i];\n const role = msg instanceof Message ? msg.role : msg.role;\n\n // Track assistant messages with tool_calls (only plain objects have tool_calls)\n if (role === 'assistant' && !(msg instanceof Message)) {\n const toolCalls = (msg as any).tool_calls;\n if (toolCalls && Array.isArray(toolCalls)) {\n for (const tc of toolCalls) {\n if (tc.id) {\n toolCallDependencies.set(tc.id, i);\n }\n }\n }\n }\n }\n\n // Mark messages that should be kept together (assistant + its tool responses)\n const mustKeepIndices = new Set<number>();\n for (let i = 0; i < otherMessages.length; i++) {\n const msg = otherMessages[i];\n const role = msg instanceof Message ? msg.role : msg.role;\n\n // If this is a tool message, mark both it and its assistant message\n if (role === 'tool' && !(msg instanceof Message)) {\n const toolCallId = (msg as any).tool_call_id;\n if (toolCallId) {\n const assistantIndex = toolCallDependencies.get(toolCallId);\n if (assistantIndex !== undefined) {\n mustKeepIndices.add(assistantIndex);\n mustKeepIndices.add(i);\n }\n }\n }\n }\n\n // Remove oldest messages while respecting dependencies\n let i = 0;\n while (this.currentTokens > this.contextWindowTokens && i < otherMessages.length) {\n // Skip if this message must be kept (part of a tool call chain)\n if (mustKeepIndices.has(i)) {\n i++;\n continue;\n }\n\n // Check if removing this message would break a tool call chain\n const msg = otherMessages[i];\n const role = msg instanceof Message ? msg.role : msg.role;\n\n // If it's an assistant with tool_calls, check if any tool messages depend on it\n let hasDependentToolMessages = false;\n if (role === 'assistant' && !(msg instanceof Message)) {\n const toolCalls = (msg as any).tool_calls;\n if (toolCalls && Array.isArray(toolCalls)) {\n for (const tc of toolCalls) {\n if (tc.id) {\n // Check if there's a tool message with this tool_call_id after this position\n for (let j = i + 1; j < otherMessages.length; j++) {\n const laterMsg = otherMessages[j];\n const laterRole = laterMsg instanceof Message ? laterMsg.role : laterMsg.role;\n if (laterRole === 'tool' && !(laterMsg instanceof Message)) {\n const laterToolCallId = (laterMsg as any).tool_call_id;\n if (laterToolCallId === tc.id) {\n hasDependentToolMessages = true;\n break;\n }\n }\n }\n }\n }\n }\n }\n\n if (hasDependentToolMessages) {\n // Can't remove this, skip it\n i++;\n continue;\n }\n\n // Safe to remove\n const removed = otherMessages.splice(i, 1)[0];\n if (removed) {\n let contentStr = '';\n if (removed instanceof Message) {\n contentStr = removed.content;\n } else {\n contentStr = removed.content || JSON.stringify(removed);\n }\n this.currentTokens -= this.estimateTokens(contentStr);\n\n // Update mustKeepIndices for remaining messages\n const newMustKeepIndices = new Set<number>();\n for (const idx of mustKeepIndices) {\n if (idx > i) {\n newMustKeepIndices.add(idx - 1);\n } else if (idx < i) {\n newMustKeepIndices.add(idx);\n }\n }\n mustKeepIndices.clear();\n for (const idx of newMustKeepIndices) {\n mustKeepIndices.add(idx);\n }\n }\n // Don't increment i since we removed an element\n }\n\n // Rebuild messages array\n this.messages = [];\n if (systemMessage) {\n this.messages.push(systemMessage);\n }\n this.messages.push(...otherMessages);\n }\n\n /**\n * Clear all messages except system\n */\n clear(): void {\n let systemMessage: Message | Record<string, any> | undefined;\n\n for (const msg of this.messages) {\n if ((msg instanceof Message && msg.role === 'system') || msg.role === 'system') {\n systemMessage = msg;\n break;\n }\n }\n\n this.messages = systemMessage ? [systemMessage] : [];\n\n if (systemMessage) {\n if (systemMessage instanceof Message) {\n this.currentTokens = this.estimateTokens(systemMessage.content);\n } else {\n this.currentTokens = this.estimateTokens(systemMessage.content || JSON.stringify(systemMessage));\n }\n } else {\n this.currentTokens = 0;\n }\n }\n\n /**\n * Get the last message\n */\n getLastMessage(): Message | Record<string, any> | null {\n return this.messages.length > 0 ? this.messages[this.messages.length - 1] : null;\n }\n\n /**\n * Get message count\n */\n getMessageCount(): number {\n return this.messages.length;\n }\n\n /**\n * Get formatted context usage information\n */\n get formattedContextUsage(): string {\n const usagePercent = (this.currentTokens / this.contextWindowTokens) * 100;\n return `Tokens: ${this.currentTokens}/${this.contextWindowTokens} (${usagePercent.toFixed(1)}%)`;\n }\n\n /**\n * Estimate tokens for text (simplified implementation)\n */\n private estimateTokens(text: string): number {\n // Simple estimation: ~4 characters per token for English text\n // In production, you might want to use a proper tokenizer\n if (!text) return 0;\n return Math.ceil(text.length / 4);\n }\n\n /**\n * Get conversation as string\n */\n toString(): string {\n return this.messages\n .map(msg => {\n if (msg instanceof Message) {\n return msg.toString();\n }\n return JSON.stringify(msg);\n })\n .join('\\n');\n }\n}\n","/**\n * Tool call management\n *\n * Converts Python's toolcall_manager.py to TypeScript\n */\n\nimport { randomUUID } from 'crypto';\nimport { Toolcall } from '../schemas/toolCall';\nimport { executeSingleTool } from '../utils/toolUtil';\nimport { ToolStore } from '../types';\nimport { runWithManager } from './context';\nimport { logger } from '../utils';\n\n// Re-export for backward compatibility\nexport { getCurrentManager } from './context';\n\n/**\n * Background process status\n */\nexport enum BackgroundProcessStatus {\n IDLE = 'idle',\n RUNNING = 'running',\n}\n\n/**\n * Background process info\n */\ninterface BackgroundProcessInfo {\n process: any; // Node.js ChildProcess or similar\n command: string;\n pid: number;\n cwd: string;\n}\n\n/**\n * Tool call manager for handling tool execution and observation\n */\nexport class ToolcallManager {\n private poolSize: number;\n private semaphore: { available: number };\n private tasks: Set<Promise<any>> = new Set();\n\n private todo: Map<string, Toolcall> = new Map();\n private done: Map<string, Toolcall> = new Map();\n private failed: Map<string, Toolcall> = new Map();\n\n private toolStores: ToolStore[];\n private executedResults: (string | Record<string, any>)[] = [];\n\n // Background process management\n private backgroundProcesses: Map<string, BackgroundProcessInfo> = new Map();\n private monitorTasks: Map<string, Promise<any>> = new Map();\n\n constructor(poolSize: number = 5, toolStore: ToolStore[] = []) {\n this.poolSize = poolSize;\n this.semaphore = { available: poolSize };\n this.toolStores = toolStore;\n }\n\n /**\n * Get executed results\n */\n getExecutedResults(): Toolcall[] {\n return Array.from(this.done.values()).concat(Array.from(this.failed.values()));\n }\n\n /**\n * Clear executed results\n */\n clear(): void {\n this.todo.clear();\n this.done.clear();\n this.failed.clear();\n this.executedResults = [];\n }\n\n /**\n * Add tool calls to be executed\n */\n addToolcall(toolCall: Toolcall | Toolcall[]): void {\n if (Array.isArray(toolCall)) {\n toolCall.forEach(tc => {\n this.todo.set(tc.toolCallId, tc);\n });\n logger.debug(`ToolcallManager: Added ${toolCall.length} toolcalls`);\n } else {\n this.todo.set(toolCall.toolCallId, toolCall);\n logger.debug(`ToolcallManager: Added toolcall: ${toolCall.name}`);\n }\n }\n\n /**\n * Execute single task with pool control\n */\n private async executeWithPool(toolcall: Toolcall): Promise<void> {\n if (!toolcall || !toolcall.name) {\n return;\n }\n\n if (!toolcall.isExtractedSuccess && toolcall.type === 'user') {\n this.failed.set(toolcall.toolCallId, toolcall);\n return;\n }\n\n // Acquire semaphore\n while (this.semaphore.available <= 0) {\n await new Promise(resolve => setTimeout(resolve, 100));\n }\n this.semaphore.available--;\n\n try {\n toolcall.executedState = 'running';\n\n // Truncate tool call input for logging\n let toolcallInputStr = JSON.stringify(toolcall.input);\n if (toolcallInputStr.length > 200) {\n toolcallInputStr = toolcallInputStr.substring(0, 100) + ' ...(truncated by 100 characters)';\n }\n\n const toolcallDescription = `${toolcall.name}(${toolcallInputStr})`;\n logger.debug(`开始执行任务: ${toolcallDescription}`);\n\n // Execute tool call\n const result = await runWithManager(this, () => executeSingleTool(toolcall, this.toolStores));\n // Do not overwrite executedState here, let executeSingleTool handle it\n // toolcall.executedState = 'success';\n\n // Update status and results\n // Important: Ensure we're not adding raw tool result objects that might not be compatible with MessageHistory\n // For tool calls, we generally want to pass the result object directly if it's a properly formatted tool output\n // or a string if it's a system tool output.\n\n const obs = result.executedResult();\n\n if (typeof obs === 'object' && 'content' in obs) {\n logger.debug(`Observation of ${toolcall.name}, tool_call_id: ${toolcall.toolCallId}:\\n${obs.content}`);\n } else {\n logger.debug(`Observation of ${toolcall.name}:\\n${obs}`);\n }\n\n if (result.executedState === 'success') {\n logger.debug(`任务执行成功: ${toolcallDescription}`);\n this.done.set(toolcall.toolCallId, result);\n } else if (result.executedState === 'failed') {\n logger.error(`任务执行失败: ${toolcallDescription}, 错误: ${result.executedContent || 'Unknown error'}`);\n this.failed.set(toolcall.toolCallId, result);\n } else if (result.executedState === 'running') {\n logger.warn(`任务执行中: ${toolcallDescription}`);\n } else {\n logger.warn(`任务执行状态未知: ${toolcallDescription}`);\n }\n\n // Add background process status if running\n const [backgroundProcessStatus, backgroundResult] = this.listBackgroundProcesses();\n if (backgroundProcessStatus === BackgroundProcessStatus.RUNNING) {\n // If background process info needs to be appended, we must be careful not to break the tool response structure\n // For now, appending to content string if it's a tool message object\n if (typeof obs === 'object' && 'content' in obs) {\n // Clone obs to avoid modifying reference\n const newObs = { ...obs };\n if (typeof backgroundResult === 'string') {\n newObs.content = `${newObs.content}\\n\\n${backgroundResult}`;\n } else if (typeof backgroundResult === 'object') {\n newObs.content = `${newObs.content}\\n\\nbackground process observation: ${(backgroundResult as any).content}`;\n }\n this.executedResults.push(newObs);\n } else if (typeof obs === 'string') {\n if (typeof backgroundResult === 'string') {\n this.executedResults.push(obs + '\\n\\n' + backgroundResult);\n } else {\n this.executedResults.push(obs + '\\n\\nbackground process observation: ' + (backgroundResult as any).content);\n }\n } else {\n // Unknown type, just push obs\n this.executedResults.push(obs);\n }\n } else {\n this.executedResults.push(obs);\n }\n } catch (error) {\n logger.error(`任务执行异常: ${toolcall.name}, 错误: ${error}`);\n toolcall.executedState = 'failed';\n toolcall.executedContent = String(error);\n this.failed.set(toolcall.toolCallId, toolcall);\n this.executedResults.push(toolcall.executedResult() as any); // Cast to any to allow string or object\n } finally {\n // Release semaphore\n this.semaphore.available++;\n }\n }\n\n /**\n * Execute all pending tasks (background execution, returns immediately)\n */\n async execute(): Promise<any[]> {\n const executionPromises: Promise<void>[] = [];\n\n for (const [toolcallId, toolcall] of this.todo) {\n this.todo.delete(toolcallId);\n\n const executionPromise = this.executeWithPool(toolcall);\n this.tasks.add(executionPromise);\n\n executionPromise.finally(() => {\n this.tasks.delete(executionPromise);\n });\n\n executionPromises.push(executionPromise);\n }\n\n // Wait for all executions to start\n await Promise.all(executionPromises);\n return this.executedResults;\n }\n\n /**\n * Observe execution results\n */\n async observe(\n waitAll: boolean = false,\n timeout: number | null = null\n ): Promise<string | Record<string, any> | (string | Record<string, any>)[]> {\n // Start all pending tasks\n await this.execute();\n\n // Give tasks some time to execute (even if not waiting for all)\n if (this.tasks.size > 0 && !waitAll) {\n await new Promise(resolve => setTimeout(resolve, 1000));\n }\n\n // Wait for all tasks to complete if requested\n if (waitAll && this.tasks.size > 0) {\n if (timeout) {\n // Wait with timeout\n try {\n await Promise.race([\n Promise.all(Array.from(this.tasks)),\n new Promise((_, reject) => setTimeout(() => reject(new Error(`Timeout after ${timeout}ms`)), timeout * 1000)),\n ]);\n } catch (error) {\n logger.warn(`等待任务完成超时 (${timeout}秒),当前还有 ${this.tasks.size} 个任务在运行`);\n }\n } else {\n // Wait without timeout\n await Promise.all(Array.from(this.tasks));\n }\n }\n\n if (this.executedResults.length === 0) {\n return '';\n }\n\n // Return array of results directly - Agent loop will handle them\n // This is important for preserving tool_call_id in objects\n const results = [...this.executedResults];\n this.clear(); // Clear observed results\n return results;\n }\n\n /**\n * Wait for all tasks to complete\n */\n async waitAll(): Promise<void> {\n if (this.tasks.size > 0) {\n await Promise.all(Array.from(this.tasks));\n logger.info('所有任务已完成');\n }\n }\n\n /**\n * Get current status\n */\n getStatus(): Record<string, any> {\n return {\n pool_size: this.poolSize,\n running_tasks: this.tasks.size,\n pending: this.todo.size,\n done: this.done.size,\n failed: this.failed.size,\n background_processes: this.backgroundProcesses.size,\n monitor_tasks: this.monitorTasks.size,\n };\n }\n\n /**\n * Get pending tool call count\n */\n getPendingCount(): number {\n return this.todo.size;\n }\n\n // Background process management methods\n\n /**\n * Register a background process\n */\n registerBackgroundProcess(process: any, command: string, cwd: string): string {\n const processId = randomUUID();\n this.backgroundProcesses.set(processId, {\n process,\n command,\n pid: process.pid,\n cwd,\n });\n\n // Create monitoring task\n const monitorTask = this.monitorProcess(processId, process);\n this.monitorTasks.set(processId, monitorTask);\n\n logger.info(`注册后台进程: ${command} (PID: ${process.pid}, ID: ${processId})`);\n return processId;\n }\n\n /**\n * Monitor process until it ends\n */\n private async monitorProcess(processId: string, process: any): Promise<void> {\n try {\n await new Promise<void>((resolve, reject) => {\n process.on('exit', (code: number) => {\n if (this.backgroundProcesses.has(processId)) {\n const command = this.backgroundProcesses.get(processId)!.command;\n this.backgroundProcesses.delete(processId);\n logger.info(`后台进程已结束: ${command} (PID: ${process.pid}, 返回码: ${code})`);\n }\n\n if (this.monitorTasks.has(processId)) {\n this.monitorTasks.delete(processId);\n }\n resolve();\n });\n\n process.on('error', (error: Error) => {\n reject(error);\n });\n });\n } catch (error) {\n logger.error(`监控进程 ${processId} 时发生错误: ${error}`);\n if (this.monitorTasks.has(processId)) {\n this.monitorTasks.delete(processId);\n }\n }\n }\n\n /**\n * Observe process stdout and stderr\n */\n private async observeProcess(processId: string, timeout: number = 5.0): Promise<string> {\n if (!this.backgroundProcesses.has(processId)) {\n return `未找到进程ID: ${processId}`;\n }\n\n const info = this.backgroundProcesses.get(processId)!;\n const process = info.process;\n\n // Simplified implementation - in real scenario you'd collect stdout/stderr\n return `进程ID: ${processId}\\n命令: ${info.command}\\nPID: ${info.pid}`;\n }\n\n /**\n * Stop specified background process\n */\n async stopBackgroundProcess(processId: string, force: boolean = false): Promise<string> {\n if (!this.backgroundProcesses.has(processId)) {\n return `未找到进程ID: ${processId}`;\n }\n\n try {\n const info = this.backgroundProcesses.get(processId);\n if (!info) {\n return `进程ID ${processId} 已被移除`;\n }\n\n const process = info.process;\n const command = info.command;\n\n if (process.exitCode !== null) {\n return `进程已经结束 (返回码: ${process.exitCode})\\n命令: ${command}`;\n }\n\n // Terminate process\n if (force) {\n process.kill('SIGKILL');\n logger.info(`强制杀死后台进程: ${command} (PID: ${process.pid})`);\n } else {\n process.kill('SIGTERM');\n logger.info(`终止后台进程: ${command} (PID: ${process.pid})`);\n }\n\n // Wait for process to end\n try {\n await new Promise<void>(resolve => {\n const timeoutId = setTimeout(() => {\n if (!force) {\n process.kill('SIGKILL');\n logger.warn(`后台进程未响应终止信号,已强制杀死: ${command}`);\n }\n resolve();\n }, 5000);\n\n process.on('exit', () => {\n clearTimeout(timeoutId);\n resolve();\n });\n });\n } catch (error) {\n logger.error(`等待进程结束失败: ${error}`);\n }\n\n // Cancel monitoring task\n if (this.monitorTasks.has(processId)) {\n const task = this.monitorTasks.get(processId);\n if (task) {\n // In Node.js, we can't cancel promises, but we can ignore them\n this.monitorTasks.delete(processId);\n }\n }\n\n this.backgroundProcesses.delete(processId);\n\n return `后台进程已停止\\n进程ID: ${processId}\\n命令: ${command}\\n返回码: ${process.exitCode}`;\n } catch (error) {\n logger.error(`停止后台进程 ${processId} 时发生错误: ${error}`);\n throw error;\n }\n }\n\n /**\n * Clean up all background processes\n */\n async cleanupBackgroundProcesses(): Promise<string> {\n if (this.backgroundProcesses.size === 0) {\n return '没有需要清理的后台进程';\n }\n\n const count = this.backgroundProcesses.size;\n const processIds = Array.from(this.backgroundProcesses.keys());\n\n const results: string[] = [];\n for (const processId of processIds) {\n try {\n const result = await this.stopBackgroundProcess(processId);\n results.push(result);\n } catch (error) {\n logger.error(`清理后台进程 ${processId} 时发生错误: ${error}`);\n results.push(`清理进程 ${processId} 失败: ${error}`);\n }\n }\n\n return `已清理 ${count} 个后台进程:\\n` + results.join('\\n---\\n');\n }\n\n /**\n * List all background processes\n */\n listBackgroundProcesses(): [BackgroundProcessStatus, string] {\n if (this.backgroundProcesses.size === 0) {\n return [BackgroundProcessStatus.IDLE, '当前没有运行的后台进程。'];\n }\n\n // Clean up finished processes\n const finishedIds: string[] = [];\n for (const [processId, info] of this.backgroundProcesses) {\n if (info.process.exitCode !== null) {\n finishedIds.push(processId);\n }\n }\n\n for (const processId of finishedIds) {\n this.backgroundProcesses.delete(processId);\n }\n\n if (this.backgroundProcesses.size === 0) {\n return [BackgroundProcessStatus.IDLE, '当前没有运行的后台进程。'];\n }\n\n const result =\n `当前有 ${this.backgroundProcesses.size} 个后台进程:\\n` +\n Array.from(this.backgroundProcesses.values())\n .map(process => `PID: ${process.pid}, Command: ${process.command}\\n`)\n .join('');\n\n return [BackgroundProcessStatus.RUNNING, result];\n }\n\n /**\n * Async context manager entry\n */\n async enter(): Promise<this> {\n return this;\n }\n\n /**\n * Async context manager exit, clean up all resources\n */\n async exit(): Promise<void> {\n await this.cleanupBackgroundProcesses();\n await this.waitAll();\n }\n}\n\n// Removed local getCurrentManager implementation as it is re-exported from context\n// export function getCurrentManager(): ToolcallManager | null {\n// return currentManagerStorage.getStore() || null;\n// }\n","/**\n * Tools prompts and output format templates\n *\n * Converts Python's prompts/tools.py to TypeScript\n */\n\nexport const REFLECT_OUTPUT_FORMAT_PROMPT = `**Reflection Prompt: Output Format Error** \nYour output does not follow the required XML format: \n<OutputFormat> \n<ToolName.method_name><arg1_name>value1</arg1_name><arg2_name>value2</arg2_name></ToolName.method_name> \n</OutputFormat> \n\nYour erroneous output: \n{output_text} \n\nPlease analyze the format discrepancies and re-output, ensuring: \n\n- Use the correct XML tag structure \n- All tags are properly closed \n- Parameter values are placed within the corresponding tags \n\nRe-output: \n`;\n\nexport const OUTPUT_FORMAT_PROMPT = `<System Tools OutputFormat>\n\nWe have three types of tasks: Generative Tasks, Analytical Tasks, and Operational Tasks.\nYou should choose the appropriate task type based on the task description.\n\n#### Generative Tasks Output Format\n<Generative Tasks Purpose>Create Something New</Generative Tasks Purpose> \n\n<Generative Tasks Definition>\nThese tasks focus on creating new artifacts from scratch, such as text, code, designs, or configurations. \nThe model synthesizes information and produces original outputs.\n</Generative Tasks Definition>\n\n<Generative Tasks Output Format>\nOutput a sequence of tool calls in the format below. Replace <ToolName.method_name> and <args_name> with actual tool and parameter names.\n\nYou may interleave tool calls with reasoning or explanations as needed:\n\n[Your reasoning or explanation here...]\n<ToolName.method_name><args_name1>args_value1</args_name1><args_name2>args_value2</args_name2>...</ToolName.method_name>\n\n[Additional thoughts or context...]\n<ToolName2.method_name2><args_name1>args_value1</args_name1><args_name2>args_value2</args_name2>...</ToolName2.method_name2>\n...\n</Generative Tasks Output Format>\n\n\n### Analytical Tasks Output Format\n<Analytical Tasks Purpose>Understand, Diagnose & Evaluate Existing Information</Analytical Tasks Purpose> \n\n<Analytical Tasks Definition>\nAnalytical tasks focus on understanding, decomposing, diagnosing, and evaluating existing information.\nThey include requirement analysis, code and system comprehension, quality evaluation, debugging and root-cause analysis, and data or behavioral analysis.\nSuch tasks produce structured insights and decisions that guide subsequent generative or operational steps.\n</Analytical Tasks Definition>\n\n<Analytical Tasks Output Format>\nYou should fellow the format below, replace the <ToolName.method_name> and <args_name> with the actual name.\n\nThoughts: ...\nToolCall: <ToolName.method_name><args_name1>args_value1</args_name1><args_name2>args_value2</args_name2>...</ToolName.method_name>\n// stop ToolCall here, and wait for the Observation of the ToolCall.\n\n</Analytical Tasks Output Format>\n\n### Operational Tasks Output Format\n\n<Operational Tasks Purpose>Act & Operate Tools</Operational Tasks Purpose> \n\n<Operational Tasks Definition>\nThese tasks involve performing concrete actions through tools, systems, or commands. \nThe focus is on executing operations rather than generating or analyzing content.\n</Operational Tasks Definition>\n\n<Operational Tasks Output Format>\nYou should follow the format below, replace the <ToolName.method_name> and <args_name> with the actual name.\n\n<ToolName.method_name><args_name1>args_value1</args_name1><args_name2>args_value2</args_name2>...</ToolName.method_name>\n</Operational Tasks Output Format>\n\n**YOUR OUTPUT MUST INCLUDE THE ACTUAL <args_name> AND <args_value>!!!**\n**If the task is completed, simply return the completion information like <TaskCompletion>your_completion_information</TaskCompletion>, No any tool call should be included.**\n</System Tools OutputFormat>\n`;\n\nexport const SYSTEM_TOOLS_PROMPT = `\n## System Tools And System Tools Call Format\n\nSystem Tools are represented by a predefined XML-like syntax structure. This structure encapsulates parameter lists within tags such as \\`<ToolName.method_name>\\`.\nBy identifying and matching keywords inside these tags, the system automatically parses the target tool name and its corresponding input parameter values to execute subsequent tool calls.\n\n### Available System Tools\n{availableSystemTools}\n\n### Description of Available System Tools\n{descOfSystemTools}\n\n### System Tools Output Format\n{outputFormat}\n`;\n","/**\n * Main Agent class with tool use capabilities\n *\n * Converts Python's agent.py to TypeScript\n */\n\nimport { Model } from './model';\nimport { MessageHistory } from './memory';\nimport { ToolcallManager } from './tools/toolcallManager';\n// IMPORTANT: Import from \"./tools\" to trigger tool registration via decorators\n// Now using TypeScript-native decorator system\nimport { SystemToolStore, FunctionCallingStore, registerAgentAsTool } from './tools';\nimport { AsyncExitStack } from './utils/connections';\nimport { Toolcall } from './schemas/toolCall';\nimport { extractToolcallsFromStr } from './utils/toolUtil';\nimport { AgentConfig, ModelConfig, ModelResponse, PostProcessor } from './types';\nimport { Message as MemoryMessage } from './schemas/message';\nimport { SYSTEM_TOOLS_PROMPT, OUTPUT_FORMAT_PROMPT } from './prompts/tools';\nimport { logger } from './utils';\n\n/**\n * Main Agent class\n */\nexport class Agent {\n name: string;\n private profile: string;\n private system: string;\n private tools: string[];\n private functionCallingTools: any[] = [];\n private mcpServerNames: string[];\n private modelConfig: string | ModelConfig;\n private verbose: boolean | number;\n private model: Model;\n private history: MessageHistory;\n private subAgents: any[] = [];\n private toolcallManagerPoolSize: number;\n private postProcessor: PostProcessor | null;\n private useFunctionCalling: boolean;\n\n constructor(config: AgentConfig) {\n const {\n name,\n profile,\n system,\n tools = [],\n subAgents = [],\n mcpServerNames = [],\n modelConfig,\n verbose = false,\n useFunctionCalling = false,\n postProcessor = null,\n toolcallManagerPoolSize = 5,\n } = config;\n\n this.name = name;\n this.profile = profile;\n this.verbose = verbose;\n this.modelConfig = modelConfig || 'deepseek';\n this.subAgents = subAgents || [];\n this.postProcessor = postProcessor;\n this.useFunctionCalling = useFunctionCalling;\n\n // Register sub-agents as tools and merge with provided tools\n const agentToolNames = registerAgentAsTool(this.subAgents, Boolean(this.verbose));\n this.tools = [...tools, ...agentToolNames];\n this.mcpServerNames = mcpServerNames;\n\n // Set system prompt with tools descriptions (system tools only)\n const systemPrompt = system || profile || '';\n this.system = this.tools.length > 0 ? this.setSystem(systemPrompt, this.tools) : systemPrompt;\n\n // Initialize model\n this.model = new Model(this.modelConfig);\n\n // Initialize message history\n const modelNameForHistory = typeof this.modelConfig === 'string' ? this.modelConfig : this.modelConfig.model || 'deepseek';\n this.history = new MessageHistory(modelNameForHistory, this.system, this.model.getConfig().contextWindowTokens);\n\n // Set up function calling tools if enabled\n if (this.useFunctionCalling) {\n this.functionCallingTools = this.setFunctionCallingTools(this.tools);\n }\n\n // Debug: Print system prompt when verbose is enabled\n if (this.verbose) {\n logger.info(`\\n========== [${this.name}] System Prompt ==========`);\n logger.info(this.system);\n logger.info(`========================================\\n`);\n\n if (typeof this.verbose === 'number' && this.verbose > 1) {\n logger.info(`[${this.name}] Tools: ${this.tools.join(', ')}`);\n logger.info('');\n }\n }\n this.toolcallManagerPoolSize = toolcallManagerPoolSize;\n }\n\n /**\n * Get the current system prompt\n */\n get systemPrompt(): string {\n return this.system;\n }\n\n /**\n * Set the system prompt and update history\n */\n set systemPrompt(value: string) {\n this.system = value;\n if (this.history) {\n this.history.updateSystem(value);\n }\n }\n\n /**\n * Set the system prompt with system tools descriptions\n * @private\n */\n private setSystem(system: string, systemTools: string[]): string {\n let toolDescriptions = '';\n\n for (const tool of systemTools) {\n if (SystemToolStore.hasTool(tool)) {\n const toolDesc = SystemToolStore.getTool(tool);\n toolDescriptions += (toolDesc?.desc || '') + '\\n\\n';\n }\n }\n\n if (systemTools.length > 0) {\n const availableSystemTools = systemTools.map(t => `- ${t}`).join('\\n');\n\n return (\n system +\n '\\n' +\n SYSTEM_TOOLS_PROMPT.replace('{availableSystemTools}', availableSystemTools)\n .replace('{descOfSystemTools}', toolDescriptions)\n .replace('{outputFormat}', OUTPUT_FORMAT_PROMPT)\n );\n }\n\n return system;\n }\n\n /**\n * Set up function calling tools for OpenAI-style function calling\n * @private\n */\n private setFunctionCallingTools(tools: string[]): any[] {\n const openaiToolCalls: any[] = [];\n\n for (let tool of tools) {\n tool = tool.replace('.', '-'); // OpenAI format\n\n if (!FunctionCallingStore.hasTool(tool)) {\n logger.warn(`Tool ${tool} not registered in FunctionCallingStore.`);\n } else {\n const toolSchema = FunctionCallingStore.getToolcallSchema(tool, 'openai');\n if (toolSchema && Object.keys(toolSchema).length > 0) {\n openaiToolCalls.push(toolSchema);\n }\n }\n }\n\n return openaiToolCalls;\n }\n\n /**\n * Agent loop - processes user input and handles tool calls\n * @private\n */\n private async _agentLoop(instruction: string, images?: string | string[]): Promise<string> {\n // Create user message\n const instructionMsg = MemoryMessage.fromUserMsg(instruction, images);\n this.history.addMessage(instructionMsg);\n\n if (this.verbose) {\n logger.info(`\\n[${this.name}] Received: ${instruction}`);\n }\n\n while (true) {\n // Truncate history to fit context window (now preserves tool call chains)\n this.history.truncate();\n\n if (typeof this.verbose === 'number' && this.verbose > 2) {\n logger.debug(\n `History raw messages before extract toolcall messages:\\n ${JSON.stringify(await this.history.formatForApi())}`\n );\n }\n\n // Get response from model\n const response: ModelResponse[] = await this.model.achat(\n await this.history.formatForApi(),\n this.useFunctionCalling ? this.functionCallingTools : undefined\n );\n\n // Extract system toolcall messages\n const systemToolcallResponses = response\n .filter(r => r.type === 'system')\n .map(r => r.extractedResult())\n .filter(r => typeof r === 'string') as string[];\n\n if (systemToolcallResponses.length > 0) {\n const systemToolcallResponse = systemToolcallResponses.join('\\n');\n this.history.addMessage('assistant', systemToolcallResponse);\n }\n\n // Extract user toolcall messages\n const userToolcallMessages = response.filter(r => r.type === 'user').map(r => r.extractedResult());\n\n if (userToolcallMessages.length > 0) {\n // Flatten user toolcall messages\n const userToolcallMessagesFlattened: any[] = [];\n for (const item of userToolcallMessages) {\n if (Array.isArray(item)) {\n userToolcallMessagesFlattened.push(...item);\n } else {\n userToolcallMessagesFlattened.push(item);\n }\n }\n\n // Add each toolcall to history (these are assistant messages with tool_calls)\n for (const toolcall of userToolcallMessagesFlattened) {\n this.history.addMessage(toolcall as any);\n }\n }\n\n if (typeof this.verbose === 'number' && this.verbose > 1) {\n const messages = await this.history.formatForApi();\n const last3 = messages.slice(-3);\n logger.debug(`History raw messages after extract toolcall messages (last 3):\\n ${JSON.stringify(last3)}`);\n }\n\n logger.debug(`History usage: ${this.history.formattedContextUsage}`);\n\n // Create toolcall manager\n const toolcallManager = new ToolcallManager(this.toolcallManagerPoolSize, [SystemToolStore, FunctionCallingStore]);\n\n // Collect and extract all tool calls\n const allToolCalls: Toolcall[] = [];\n\n // Prepare system tool map for extraction\n const systemToolMap: Record<string, any> = {};\n const systemToolNames = SystemToolStore.listTools();\n for (const name of systemToolNames) {\n const tool = SystemToolStore.getTool(name);\n if (tool) {\n systemToolMap[name] = tool;\n }\n }\n\n for (const r of response) {\n const result = r.extractedResult();\n\n if (typeof result === 'string') {\n // Extract XML system tool calls\n if (result.trim().length > 0) {\n const extracted = extractToolcallsFromStr(result, systemToolMap);\n allToolCalls.push(...extracted);\n }\n } else if (typeof result === 'object' && result !== null) {\n // Handle assistant message with tool_calls (from user/MCP tools)\n if (!Array.isArray(result) && result.role === 'assistant' && result.tool_calls && Array.isArray(result.tool_calls)) {\n for (const tc of result.tool_calls) {\n // OpenAI format: { id, type: 'function', function: { name, arguments } }\n if (tc.type === 'function' && tc.function) {\n let args = {};\n try {\n args = JSON.parse(tc.function.arguments);\n } catch (e) {\n logger.warn(`Failed to parse arguments for tool ${tc.function.name}: ${tc.function.arguments}`);\n args = { raw_args: tc.function.arguments };\n }\n\n allToolCalls.push(\n new Toolcall({\n name: tc.function.name,\n input: args,\n toolCallId: tc.id,\n type: 'user',\n rawContentFromLlm: tc.function.arguments,\n })\n );\n }\n }\n }\n // Handle array of tool calls (legacy format)\n else if (Array.isArray(result)) {\n for (const item of result) {\n // OpenAI format: { id, type: 'function', function: { name, arguments } }\n if (item.type === 'function' && item.function) {\n let args = {};\n try {\n args = JSON.parse(item.function.arguments);\n } catch (e) {\n logger.warn(`Failed to parse arguments for tool ${item.function.name}: ${item.function.arguments}`);\n args = { raw_args: item.function.arguments };\n }\n\n allToolCalls.push(\n new Toolcall({\n name: item.function.name,\n input: args,\n toolCallId: item.id,\n type: 'user',\n rawContentFromLlm: item.function.arguments,\n })\n );\n }\n // Anthropic format: { id, type: 'tool_use', name, input }\n else if (item.type === 'tool_use') {\n allToolCalls.push(\n new Toolcall({\n name: item.name,\n input: item.input,\n toolCallId: item.id,\n type: 'user',\n })\n );\n }\n }\n }\n }\n }\n\n if (allToolCalls.length > 0) {\n toolcallManager.addToolcall(allToolCalls);\n const obs = await toolcallManager.observe(true, 60.0);\n\n // Handle array of observations (which may include tool messages)\n if (Array.isArray(obs)) {\n for (const item of obs) {\n if (typeof item === 'object') {\n // Direct message object (e.g. tool response)\n this.history.addMessage(item);\n } else if (typeof item === 'string') {\n this.history.addMessage('user', item);\n }\n }\n } else if (typeof obs === 'string') {\n this.history.addMessage('user', obs);\n } else if (typeof obs === 'object') {\n this.history.addMessage(obs as any);\n } else {\n logger.warn(`Unknown observation type: ${typeof obs}`);\n }\n } else {\n // No tool calls - extract text from system responses and strip TaskCompletion tags\n for (const r of response) {\n if (r.type === 'system') {\n const result = r.extractedResult();\n if (typeof result === 'string') {\n // Strip TaskCompletion tags (matching Python behavior)\n const cleanResult = result\n .replace(/<TaskCompletion>/g, '')\n .replace(/<\\/TaskCompletion>/g, '')\n .trim();\n return cleanResult;\n }\n }\n }\n return ''; // No content found\n }\n }\n }\n\n /**\n * Run the agent with given instruction\n */\n async run(instruction: string, images?: string | string[]): Promise<string | any> {\n // AsyncExitStack for MCP tools management\n const stack = new AsyncExitStack();\n\n try {\n // Add MCP tools if configured\n for (const serverName of this.mcpServerNames) {\n await FunctionCallingStore.addMcpTools?.(this.name, serverName, stack);\n const mcpTools = FunctionCallingStore.getMcpToolsSchemas?.(this.name, serverName, 'openai') || [];\n\n if (this.verbose) {\n logger.info(`[${this.name}] Loaded MCP tools from ${serverName}: ${mcpTools.length} tools found.`);\n if (typeof this.verbose === 'number' && this.verbose > 1) {\n logger.info(`[${this.name}] MCP tools sample: ${JSON.stringify(mcpTools).substring(0, 200)} ...`);\n }\n }\n\n if (this.useFunctionCalling) {\n this.functionCallingTools.push(...mcpTools);\n }\n }\n\n // Run agent loop (now returns string)\n const responseText = await this._agentLoop(instruction, images);\n\n // Apply post_processor if provided\n if (this.postProcessor) {\n try {\n return await this.postProcessor(responseText);\n } catch (error) {\n logger.error(`Post-processor error in agent ${this.name}:`, error);\n throw new Error(`Post-processor failed: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n // Return raw string response\n return responseText;\n } catch (error) {\n logger.error(`Agent ${this.name} execution error:`);\n logger.error(error);\n if (error instanceof Error) {\n logger.error(`Error message: ${error.message}`);\n logger.error(`Error stack: ${error.stack}`);\n }\n throw error;\n } finally {\n // Cleanup MCP tools\n await stack.close();\n }\n }\n\n /**\n * Get agent profile\n */\n getProfile(): string {\n return this.profile;\n }\n\n /**\n * Get tools\n */\n getTools(): string[] {\n return [...this.tools];\n }\n\n /**\n * Get function calling tools schemas\n */\n getFunctionCallingTools(): any[] {\n return [...this.functionCallingTools];\n }\n\n /**\n * Get MCP server names\n */\n getMcpServerNames(): string[] {\n return [...this.mcpServerNames];\n }\n\n /**\n * Get model config (string or ModelConfig object)\n */\n getModelConfig(): string | ModelConfig {\n return this.modelConfig;\n }\n\n /**\n * Get model name (for backward compatibility)\n */\n getModelName(): string {\n if (typeof this.modelConfig === 'string') {\n return this.modelConfig;\n }\n return this.modelConfig.model || 'deepseek';\n }\n\n /**\n * Get verbose setting\n */\n getVerbose(): boolean | number {\n return this.verbose;\n }\n\n /**\n * Get sub-agents\n */\n getSubAgents(): any[] {\n return [...this.subAgents];\n }\n}\n","/**\n * Base environment for agent management\n *\n * Converts Python's environment/base.py to TypeScript\n */\n\nimport { Agent } from '../agent';\nimport { SkillsTool } from '../tools/skills';\nimport { SKILLS_DIR } from '../configs/paths';\nimport { logger } from '../utils';\n\n/**\n * Instruction type enumeration\n */\nexport enum InstructionType {\n VALID = 'valid',\n QUIT = 'quit',\n SEND_TO_ALL = 'sendToAll',\n NO_AGENT_NAME = 'noAgentName',\n NO_AVAILABLE_AGENT_NAME = 'noAvailableAgentName',\n}\n\n/**\n * Environment for the agent\n */\nexport class BaseEnvironment {\n /**\n * List of agents in the environment\n */\n agents: Agent[] = [];\n\n /**\n * Assign skills to agent with their names\n */\n agentSkills: Record<string, string[]> = {};\n\n constructor(agents: Agent[] = [], agentSkills: Record<string, string[]> = {}) {\n this.agents = agents;\n this.agentSkills = agentSkills;\n this.setAgentSkills();\n }\n\n /**\n * Set agent skills after initialization\n */\n private setAgentSkills(): void {\n if (this.agents.length === 0 || Object.keys(this.agentSkills).length === 0) {\n return;\n }\n\n const skiller = new SkillsTool(SKILLS_DIR);\n\n // Handle \"all\" keyword for assigning skills to all agents\n if ('all' in this.agentSkills) {\n for (const agent of this.agents) {\n this.agentSkills[agent.name] = this.agentSkills['all'];\n }\n delete this.agentSkills['all'];\n }\n\n logger.debug(`Assigning skills to agents: ${JSON.stringify(this.agentSkills)}`);\n\n // Assign skills to specified agents\n for (const [agentName, skillNames] of Object.entries(this.agentSkills)) {\n for (const agent of this.agents) {\n if (agent.name === agentName) {\n const skillDescriptions: string[] = [];\n\n // Read skill descriptions asynchronously\n (async () => {\n for (const skillName of skillNames) {\n try {\n const skillDescription = await skiller.readSkillDescription(skillName);\n skillDescriptions.push(skillDescription);\n } catch (error) {\n logger.warn(`Failed to read skill description for ${skillName}:`, error);\n }\n }\n\n const skillDescription =\n '\\n--- <SKILLS START> ---\\n' + skillDescriptions.join('\\n-----\\n') + '\\n--- <SKILLS END> ---\\n';\n\n agent.systemPrompt = agent.systemPrompt + skillDescription;\n })();\n }\n }\n }\n }\n\n /**\n * Check if instruction has agent name\n */\n hasAgentName(instruction: string): boolean {\n if (!instruction.includes('@')) {\n return false;\n }\n\n for (const agent of this.agents) {\n if (instruction.includes(`@${agent.name}`)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Post process instruction\n */\n postProcessInstruction(instruction: string, agentNames: string[]): [InstructionType, string] {\n // Direct return instructions\n if (['/q', 'exit', 'quit'].includes(instruction.toLowerCase()) || agentNames.length === 0) {\n return [InstructionType.QUIT, instruction];\n }\n\n // Single agent case: add @agent_name\n if (agentNames.length === 1) {\n return [InstructionType.VALID, `${instruction}@${agentNames[0]}`];\n }\n\n // Multiple agents case: ensure @agent_name is present\n if (instruction.includes('@all')) {\n return [InstructionType.SEND_TO_ALL, instruction];\n }\n\n if (this.hasAgentName(instruction)) {\n return [InstructionType.VALID, instruction];\n }\n\n return [InstructionType.NO_AVAILABLE_AGENT_NAME, instruction];\n }\n\n /**\n * Run with a single goal until completion (non-interactive mode)\n */\n async runGoal(goal: string): Promise<void> {\n if (this.agents.length === 0) {\n logger.error('No agents in the environment.');\n return;\n }\n\n const [instructionType, processedInstruction] = this.postProcessInstruction(\n goal,\n this.agents.map(agent => agent.name)\n );\n\n if (instructionType === InstructionType.QUIT) {\n logger.info('Invalid goal instruction.');\n return;\n }\n\n if (instructionType === InstructionType.NO_AVAILABLE_AGENT_NAME) {\n logger.warn(\"No available agent name in instruction. Please provide instruction with '@agent_name'.\");\n return;\n }\n\n logger.info('Goal:', goal);\n logger.info('Processing goal...\\n');\n\n for (const agent of this.agents) {\n if (instructionType === InstructionType.SEND_TO_ALL || processedInstruction.includes(`@${agent.name}`)) {\n try {\n const response = await agent.run(processedInstruction);\n logger.info(`\\n> Agent ${agent.name} completed the goal.`);\n logger.info(`Final response: ${response}`);\n } catch (error) {\n logger.error(`Error running agent ${agent.name}:`, error);\n }\n }\n }\n }\n\n /**\n * Run the environment (interactive mode)\n */\n async run(): Promise<void> {\n const readline = await import('readline');\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n const question = (prompt: string): Promise<string> => {\n return new Promise(resolve => {\n rl.question(prompt, resolve);\n });\n };\n\n try {\n while (true) {\n try {\n // Get instruction from user\n let instruction: string;\n if (this.agents.length === 0) {\n logger.error('No agents in the environment.');\n break;\n } else if (this.agents.length === 1) {\n instruction = await question(\"Enter your instruction (or '/q' to quit): \");\n } else {\n const agentNames = this.agents.map(agent => agent.name).join(', ');\n instruction = await question(\n `Enter your instruction with '@agent_name' (or '/q' to quit), available agents: ${agentNames}: `\n );\n }\n\n const [instructionType, processedInstruction] = this.postProcessInstruction(\n instruction,\n this.agents.map(agent => agent.name)\n );\n\n if (instructionType === InstructionType.QUIT) {\n logger.info('Quitting...');\n break;\n } else if (instructionType === InstructionType.NO_AVAILABLE_AGENT_NAME) {\n logger.warn(\"No available agent name in instruction. Please enter your instruction with '@agent_name'.\");\n continue;\n }\n\n logger.info('Processing your request...');\n for (const agent of this.agents) {\n if (instructionType === InstructionType.SEND_TO_ALL || processedInstruction.includes(`@${agent.name}`)) {\n const response = await agent.run(processedInstruction);\n logger.info(`Agent ${agent.name} response:`, response);\n }\n }\n } catch (error) {\n logger.error('Error processing instruction:', error);\n }\n }\n } finally {\n rl.close();\n }\n }\n}\n","/**\n * Coding environment for agent management\n *\n * Converts Python's environment/coding.py to TypeScript\n */\n\nimport * as fs from 'fs';\nimport { BaseEnvironment } from './base';\nimport { Agent } from '../agent';\nimport { WORKSPACE_DIR } from '../configs/paths';\nimport { logger } from '../utils';\n\n/**\n * Environment for coding\n */\nexport class CodingEnvironment extends BaseEnvironment {\n /**\n * Workspace directory\n */\n workspaceDir: string = '';\n\n constructor(agents: Agent[] = [], agentSkills: Record<string, string[]> = {}, workspaceDir: string = '') {\n super(agents, agentSkills);\n this.workspaceDir = workspaceDir;\n this.setWorkspaceDir();\n }\n\n /**\n * Set workspace directory after initialization\n */\n private setWorkspaceDir(): void {\n if (!this.workspaceDir) {\n this.workspaceDir = WORKSPACE_DIR;\n }\n\n // Create workspace directory if it doesn't exist\n if (!fs.existsSync(this.workspaceDir)) {\n fs.mkdirSync(this.workspaceDir, { recursive: true });\n } else {\n logger.debug(`Workspace directory already exists: ${this.workspaceDir}`);\n }\n\n // Inject workspace_dir into all agents' system\n for (const agent of this.agents) {\n if (!agent.systemPrompt.includes(this.workspaceDir)) {\n agent.systemPrompt =\n agent.systemPrompt +\n `\\n\\nYour workspace directory is: <workspace>${this.workspaceDir}</workspace>` +\n `\\n\\n**Note**: your any output files must be saved in ${this.workspaceDir}`;\n }\n }\n\n logger.debug(`Setting workspace directory: ${this.workspaceDir}`);\n for (const agent of this.agents) {\n logger.debug(`Agent ${agent.name} system: ${agent.systemPrompt}`);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;AAMA,SAAS,cAAc;AACvB,SAAS,4BAA4B;AACrC,SAAS,0BAA0B;;;ACFnC,SAAS,kBAAkB;AAgBpB,IAAM,WAAN,MAAe;AAAA,EAClB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA,YAAYA,SAUT;AACC,SAAK,OAAOA,QAAO;AACnB,SAAK,QAAQA,QAAO,SAAS,CAAC;AAC9B,SAAK,qBAAqBA,QAAO,sBAAsB;AACvD,SAAK,wBAAwBA,QAAO;AACpC,SAAK,gBAAgBA,QAAO,iBAAiB;AAC7C,SAAK,kBAAkBA,QAAO;AAC9B,SAAK,aAAaA,QAAO,cAAc,WAAW;AAClD,SAAK,OAAOA,QAAO,QAAQ;A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AM,IAAI,YAAY,MAAM,YAAY,EAAE;AAAA,IACpE;AAAA,EACJ;AACJ;","names":["config","logger","streamLogger","config","fs","path","fs","getConfigPath","config","config","fs","resolve","fs","path","fs","path","fs","path","config","resolve","format","tools","streamLogger","textParts","textContent","fs","path","i","randomUUID","resolve","process","randomUUID","config","tools","skillDescription","resolve","fs"]}