evoltagent 1.1.2 → 1.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +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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,MAAM,SAAS,MAAM,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"]}
1
+ {"version":3,"sources":["../src/utils/connections.ts","../src/schemas/toolCall.ts","../src/utils/toolUtil.ts","../src/utils/deprecated.ts","../src/utils/readImage.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/schemas/message.ts","../src/tools/imageTool.ts","../src/tools/patchTool.ts","../src/core/agent.ts","../src/core/model.ts","../src/runtime/memory/messageHistory.ts","../src/tools/toolcallManager.ts","../src/prompts/tools.ts","../src/schemas/feedback.ts","../src/runtime/orchestrator/base.ts","../src/runtime/orchestrator/coding.ts","../src/runtime/orchestrator/reflexion.ts","../src/runtime/environment/base.ts","../src/runtime/executors/base.ts","../src/runtime/executors/utils.ts","../src/runtime/executors/localExecutor.ts","../src/runtime/state/store.ts","../src/runtime/state/jsonlStore.ts","../src/runtime/state/context.ts","../src/runtime/state/decorator.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 * Deprecated decorator for marking methods as deprecated\n *\n * Corresponds to Python's utils/deprecated.py\n */\n\nexport interface DeprecatedOptions {\n version?: string;\n replacement?: string;\n}\n\n/**\n * Decorator to mark a method as deprecated.\n * Logs a warning when the method is called.\n *\n * @param options - Configuration options\n * @param options.version - Version in which the method will be removed\n * @param options.replacement - Suggested replacement method\n *\n * @example\n * ```typescript\n * class MyClass {\n * @deprecated({ version: '0.2.2', replacement: 'formatForApi' })\n * oldMethod() {\n * // ...\n * }\n * }\n * ```\n */\nexport function deprecated(options: DeprecatedOptions = {}) {\n return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {\n const original = descriptor.value;\n\n descriptor.value = function (...args: any[]) {\n const parts: string[] = [`${propertyKey} is deprecated`];\n\n if (options.version) {\n parts.push(`will be removed in ${options.version}`);\n }\n\n if (options.replacement) {\n parts.push(`use ${options.replacement} instead`);\n }\n\n console.warn(parts.join(', '));\n\n return original.apply(this, args);\n };\n\n return descriptor;\n };\n}\n","/**\n * Image reading utilities\n *\n * Corresponds to Python's utils/read_image.py\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\n\n/**\n * OpenAI vision API format for image content\n */\nexport interface ImageContent {\n type: 'image_url';\n image_url: {\n url: string;\n };\n}\n\n/**\n * MIME type mapping for image extensions\n */\nconst MIME_TYPES: Record<string, string> = {\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.png': 'image/png',\n '.gif': 'image/gif',\n '.webp': 'image/webp',\n};\n\n/**\n * Supported image extensions (SVG is not supported by AI models)\n */\nconst SUPPORTED_FORMATS = new Set(['.jpg', '.jpeg', '.png', '.gif', '.webp']);\n\n/**\n * Get MIME type from path or URL\n */\nfunction getMimeType(pathOrUrl: string): string {\n // Remove URL query parameters\n const cleanPath = pathOrUrl.split('?')[0];\n const ext = path.extname(cleanPath).toLowerCase();\n return MIME_TYPES[ext] || 'image/jpeg';\n}\n\n/**\n * Check if the file is a supported image format\n *\n * @param imagePath - Path or URL to the image\n * @returns true if the image format is supported (jpeg, jpg, png, gif, webp), false otherwise (svg, etc.)\n */\nexport function isSupportedImageFile(imagePath: string): boolean {\n const cleanPath = imagePath.split('?')[0];\n const ext = path.extname(cleanPath).toLowerCase();\n return SUPPORTED_FORMATS.has(ext);\n}\n\n/**\n * Fetch URL content\n */\nasync function fetchUrl(url: string): Promise<Buffer> {\n const response = await fetch(url, {\n signal: AbortSignal.timeout(30000),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch image from ${url}: ${response.statusText}`);\n }\n\n const arrayBuffer = await response.arrayBuffer();\n return Buffer.from(arrayBuffer);\n}\n\n/**\n * Synchronously read image and convert to base64 format\n *\n * @param imagePath - Image path or URL\n * @returns OpenAI vision API format image content\n * @throws Error if image file not found or URL request fails\n */\nexport function readImage(imagePath: string): ImageContent {\n const mimeType = getMimeType(imagePath);\n let content: Buffer;\n\n if (imagePath.startsWith('http://') || imagePath.startsWith('https://')) {\n // For sync version, we don't support URL fetching\n throw new Error('Synchronous URL fetching is not supported. Use areadImage instead.');\n } else {\n if (!fs.existsSync(imagePath)) {\n throw new Error(`Image file not found: ${imagePath}`);\n }\n content = fs.readFileSync(imagePath);\n }\n\n const b64Content = content.toString('base64');\n const dataUrl = `data:${mimeType};base64,${b64Content}`;\n\n return {\n type: 'image_url',\n image_url: { url: dataUrl },\n };\n}\n\n/**\n * Asynchronously read image and convert to base64 format\n *\n * @param imagePath - Image path or URL\n * @returns OpenAI vision API format image content\n * @throws Error if image file not found or URL request fails\n */\nexport async function areadImage(imagePath: string): Promise<ImageContent> {\n const mimeType = getMimeType(imagePath);\n let content: Buffer;\n\n if (imagePath.startsWith('http://') || imagePath.startsWith('https://')) {\n content = await fetchUrl(imagePath);\n } else {\n if (!fs.existsSync(imagePath)) {\n throw new Error(`Image file not found: ${imagePath}`);\n }\n content = await fs.promises.readFile(imagePath);\n }\n\n const b64Content = content.toString('base64');\n const dataUrl = `data:${mimeType};base64,${b64Content}`;\n\n return {\n type: 'image_url',\n image_url: { url: dataUrl },\n };\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';\nexport { deprecated, DeprecatedOptions } from './deprecated';\nexport { isSupportedImageFile, readImage, areadImage, ImageContent } from './readImage';\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' | 'tool';\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 * 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';\nimport { deprecated } from '../utils/deprecated';\nimport { ImageContent } from '../utils/readImage';\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' | 'tool';\n content: string;\n images?: string | string[];\n\n // OpenAI vision API format image content\n imagesContent?: ImageContent[];\n\n // Message tag for wrapping content\n tag?: string;\n\n // Function calling / OpenAI tool call message information\n isFunctionCall?: boolean;\n toolCallId?: string;\n toolName?: string;\n\n // Legacy type field (kept for compatibility)\n type?: string;\n\n constructor(\n role: 'system' | 'user' | 'assistant' | 'tool',\n content: string,\n images?: string | string[],\n type?: string\n ) {\n this.role = role;\n this.content = content;\n this.images = images;\n this.type = type;\n this.imagesContent = [];\n this.tag = '';\n this.isFunctionCall = false;\n this.toolCallId = '';\n this.toolName = '';\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 * Check if message is truthy based on content\n */\n isTruthy(): boolean {\n if (typeof this.content === 'string') {\n return Boolean(this.content.trim());\n }\n return false;\n }\n\n /**\n * Format the content with pre/post content and optional tag wrapping\n */\n private _formatForContent(preContent: string = '', postContent: string = ''): string {\n if (this.tag) {\n return `${preContent}<${this.tag}>\\n${this.content}\\n</${this.tag}>${postContent}`.trim();\n }\n return `${preContent}${this.content}${postContent}`.trim();\n }\n\n /**\n * Ensure text content is not empty to avoid API errors\n */\n private static _ensureNonEmptyText(text: string): string {\n return text.trim() ? text : ' ';\n }\n\n /**\n * Format message for OpenAI API\n *\n * This is the recommended method replacing toChatMessage.\n *\n * @param preContent - Content to prepend\n * @param postContent - Content to append\n * @returns Formatted message object for API\n */\n formatForApi(preContent: string = '', postContent: string = ''): Record<string, any> {\n const role = ['user', 'assistant', 'system', 'tool'].includes(this.role) ? this.role : 'user';\n const functionCallingMeta = { tool_call_id: this.toolCallId, name: this.toolName };\n\n if (!this.imagesContent || this.imagesContent.length === 0) {\n const msg: Record<string, any> = {\n role,\n content: this._formatForContent(preContent, postContent),\n };\n return this.isFunctionCall ? { ...msg, ...functionCallingMeta } : msg;\n }\n\n let formattedText = this._formatForContent(preContent, postContent);\n // Ensure text content is not empty to avoid API errors\n formattedText = Message._ensureNonEmptyText(formattedText);\n\n const content: ContentPart[] = [{ type: 'text', text: formattedText }];\n content.push(...this.imagesContent);\n\n const msg: Record<string, any> = { role, content };\n return this.isFunctionCall ? { ...msg, ...functionCallingMeta } : msg;\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 if (this.tag) {\n obj.tag = this.tag;\n }\n\n if (this.imagesContent && this.imagesContent.length > 0) {\n obj.images_content = this.imagesContent;\n }\n\n if (this.isFunctionCall) {\n obj.is_function_call = this.isFunctionCall;\n obj.tool_call_id = this.toolCallId;\n obj.tool_name = this.toolName;\n }\n\n return obj;\n }\n\n /**\n * Convert to dictionary representation\n */\n toDict(): Record<string, any> {\n return {\n role: this.role,\n content: this.content,\n tag: this.tag || '',\n images_content: this.imagesContent || [],\n is_function_call: this.isFunctionCall || false,\n tool_call_id: this.toolCallId || '',\n tool_name: this.toolName || '',\n };\n }\n\n /**\n * Check if message contains images\n */\n hasImages(): boolean {\n return (\n (!!this.images && (Array.isArray(this.images) ? this.images.length > 0 : true)) ||\n (!!this.imagesContent && this.imagesContent.length > 0)\n );\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 const parts: string[] = [];\n\n parts.push(`role=${this.role}`);\n if (this.content) {\n const truncatedContent = this.content.length > 100 ? this.content.slice(0, 100) + '...' : this.content;\n parts.push(`content=${truncatedContent}`);\n }\n if (this.tag) {\n parts.push(`tag=${this.tag}`);\n }\n\n // Handle images_content, only show file paths\n if (this.imagesContent && this.imagesContent.length > 0) {\n const imagePaths: string[] = [];\n for (const img of this.imagesContent) {\n if (img && img.image_url && img.image_url.url) {\n const url = img.image_url.url;\n if (!url.startsWith('data:')) {\n imagePaths.push(url);\n }\n }\n }\n if (imagePaths.length > 0) {\n parts.push(`images_paths=[${imagePaths.join(', ')}]`);\n }\n }\n\n return `Message(${parts.join(', ')})`;\n }\n\n /**\n * Merge two messages into one\n *\n * @param other - Message to merge with\n * @returns New merged Message\n */\n merge(other: Message): Message {\n if (this.role !== other.role) {\n throw new Error('Messages must have the same role to merge');\n }\n if (this.isFunctionCall !== other.isFunctionCall) {\n throw new Error('Messages must have the same isFunctionCall to merge');\n }\n if (this.toolCallId !== other.toolCallId) {\n throw new Error('Messages must have the same toolCallId to merge');\n }\n if (this.toolName !== other.toolName) {\n throw new Error('Messages must have the same toolName to merge');\n }\n\n let selfContent = this.content;\n let otherContent = other.content;\n let resultTag = this.tag;\n\n // If tags are different, wrap content with tags and clear tags\n if (this.tag !== other.tag) {\n selfContent = this.tag ? `<${this.tag}>\\n${this.content}\\n</${this.tag}>` : this.content;\n otherContent = other.tag ? `<${other.tag}>\\n${other.content}\\n</${other.tag}>` : other.content;\n resultTag = '';\n }\n\n const merged = new Message(this.role, `${selfContent}\\n${otherContent}`);\n merged.tag = resultTag;\n merged.imagesContent = [...(this.imagesContent || []), ...(other.imagesContent || [])];\n merged.isFunctionCall = this.isFunctionCall;\n merged.toolCallId = this.toolCallId;\n merged.toolName = this.toolName;\n\n return merged;\n }\n\n /**\n * Convert to OpenAI Vision API format with base64-encoded images\n *\n * @deprecated Use formatForApi instead. Will be removed in 0.2.2.\n *\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 @deprecated({ version: '0.2.2', replacement: 'formatForApi' })\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\n // Handle legacy images field\n if (this.images) {\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\n // Handle imagesContent field\n if (this.imagesContent && this.imagesContent.length > 0) {\n content.push(...this.imagesContent);\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 * ImageTool - Tool for reading images from paths or URLs\n *\n * Corresponds to Python's tools/image_tool.py\n */\n\nimport { Message } from '../schemas/message';\nimport { isSupportedImageFile, areadImage } from '../utils/readImage';\nimport { tools } from './toolRegister';\nimport { logger } from '../utils';\n\n/**\n * Tool for reading images from paths or URLs\n */\n@tools({\n readImage: {\n description: 'Read and analyze an image (JPEG, JPG, PNG, GIF, WebP) from image path or URL. Note: SVG format is not supported by the AI model.',\n params: [\n { name: 'imagePath', type: 'string', description: 'Image path or URL' },\n { name: 'instruction', type: 'string', description: 'Instruction for analyzing the image', optional: true },\n ],\n returns: { type: 'Message', description: 'Message containing image content in base64 format' },\n },\n readImages: {\n description: 'Read images (JPEG, JPG, PNG, GIF, WebP) from image paths or URLs. Note: SVG format is not supported by the AI model and will be automatically filtered out.',\n params: [\n { name: 'imagePaths', type: 'array', description: 'List of image paths or URLs' },\n { name: 'instruction', type: 'string', description: 'Instruction for reading the images', optional: true },\n ],\n returns: { type: 'Message', description: 'Message containing multiple image contents in base64 format' },\n },\n})\nexport class ImageTool {\n /**\n * Read and analyze an image (JPEG, JPG, PNG, GIF, WebP) from image path or URL.\n *\n * Note: SVG format is not supported by the AI model.\n *\n * @param imagePath - Image path or URL\n * @param instruction - Instruction for analyzing the image\n * @returns Message containing image content in base64 format\n */\n async readImage(imagePath: string, instruction: string = ''): Promise<Message> {\n try {\n // Check if image format is supported\n if (!isSupportedImageFile(imagePath)) {\n logger.warn(`Unsupported image format: ${imagePath}. Only JPEG, PNG, GIF, and WebP are supported.`);\n const errorMsg = new Message(\n 'user',\n `Error: Unsupported image format '${imagePath}'. Only JPEG, PNG, GIF, and WebP are supported by the AI model.`\n );\n return errorMsg;\n }\n\n const imageContent = await areadImage(imagePath);\n\n // Build analysis instruction\n let content: string;\n if (instruction) {\n // When there's an explicit instruction, ask LLM to analyze according to it\n content = `Please analyze the image from ${imagePath} according to the following instruction:\\n\\n${instruction}\\n\\nPlease provide a detailed analysis of the image content based on this instruction.`;\n } else {\n // When no instruction, ask LLM to describe the image in detail\n content = `Please analyze and describe the image from ${imagePath} in detail. Include information about:\\n- What is shown in the image\\n- Key elements, objects, or features\\n- Colors, composition, and visual characteristics\\n- Any text or symbols present\\n- Overall context and meaning`;\n }\n\n const msg = new Message('user', content);\n msg.imagesContent = [imageContent];\n msg.tag = 'image_content';\n return msg;\n } catch (error) {\n return new Message('user', `Error reading image ${imagePath}: ${error}`);\n }\n }\n\n /**\n * Read images (JPEG, JPG, PNG, GIF, WebP) from image paths or URLs.\n *\n * Note: SVG format is not supported by the AI model and will be automatically filtered out.\n *\n * @param imagePaths - List of image paths or URLs\n * @param instruction - Instruction for reading the images\n * @returns Message containing multiple image contents in base64 format\n */\n async readImages(imagePaths: string[], instruction: string = ''): Promise<Message> {\n try {\n // Filter supported image formats\n const supportedPaths = imagePaths.filter(path => isSupportedImageFile(path));\n const unsupportedPaths = imagePaths.filter(path => !isSupportedImageFile(path));\n\n // Log unsupported formats\n if (unsupportedPaths.length > 0) {\n logger.warn(\n `Skipping unsupported image formats (only JPEG/PNG/GIF/WebP are supported): ${unsupportedPaths.join(', ')}`\n );\n }\n\n if (supportedPaths.length === 0) {\n return new Message(\n 'user',\n `No supported image formats found in the provided list. Only JPEG, PNG, GIF, and WebP are supported. Unsupported files: ${unsupportedPaths.join(', ')}`\n );\n }\n\n // Read supported images\n const imageContents = await Promise.all(\n supportedPaths.map(imagePath => areadImage(imagePath))\n );\n\n // Build return message\n const contentParts = [`Successfully loaded ${supportedPaths.length} image(s): ${supportedPaths.join(', ')}`];\n if (unsupportedPaths.length > 0) {\n contentParts.push(`Skipped ${unsupportedPaths.length} unsupported file(s): ${unsupportedPaths.join(', ')}`);\n }\n\n const msg = new Message('user', contentParts.join('\\n'));\n msg.imagesContent = imageContents;\n return msg;\n } catch (error) {\n return new Message('user', `Error reading images ${imagePaths.join(', ')}: ${error}`);\n }\n }\n}\n","/**\n * PatchTool - Tool for applying patches to files\n *\n * Corresponds to Python's tools/patch_tool.py\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { spawn } from 'child_process';\nimport { tools } from './toolRegister';\nimport { logger } from '../utils';\n\n/**\n * Tool for applying patches to files\n */\n@tools({\n writePatchFile: {\n description: 'Write patch content to file. IMPORTANT: Always read the target file first before generating a patch. Use correct line numbers based on actual file content. Never use @@ -0,0 format unless file is truly empty.',\n params: [\n { name: 'patchPath', type: 'string', description: 'Path to the patch file. Will automatically append .patch suffix if not present.' },\n { name: 'patchContent', type: 'string', description: 'Content of the patch in unified diff format. Must start with --- a/file_path and include +++ b/file_path lines.' },\n ],\n returns: { type: 'string', description: 'Success message with bytes written' },\n },\n applyPatch: {\n description: 'Apply a patch to a file. The patch should be generated using writePatchFile first. IMPORTANT: Ensure patch line numbers match the actual file content to avoid duplicate content.',\n params: [\n { name: 'patchPath', type: 'string', description: 'Path to the patch file. Will automatically append .patch suffix if not present.' },\n { name: 'patchContent', type: 'string', description: 'Optional patch content to write before applying', optional: true },\n ],\n returns: { type: 'string', description: 'Success message describing the applied patch' },\n },\n})\nexport class PatchTool {\n /**\n * Write patch content to file\n *\n * @param patchPath - Path to the patch file\n * @param patchContent - Content of the patch in unified diff format\n * @returns Success message\n */\n async writePatchFile(patchPath: string, patchContent: string): Promise<string> {\n let warningMsg = '';\n\n // Ensure patch_path ends with .patch\n if (!patchPath.endsWith('.patch')) {\n patchPath = `${patchPath}.patch`;\n warningMsg = `Warning: Patch path does not end with '.patch', automatically appended '.patch' to ${patchPath}`;\n }\n\n // Create directory if needed\n const dirPath = path.dirname(patchPath);\n if (dirPath) {\n await fs.promises.mkdir(dirPath, { recursive: true });\n }\n\n // Clean up patch content\n patchContent = patchContent.trim();\n\n // Remove code block markers if present\n if (patchContent.startsWith('```')) {\n const newlineIndex = patchContent.indexOf('\\n');\n patchContent = newlineIndex !== -1 ? patchContent.slice(newlineIndex + 1) : patchContent.slice(3);\n }\n if (patchContent.endsWith('```')) {\n patchContent = patchContent.slice(0, -3).trimEnd();\n }\n patchContent = patchContent.trim();\n\n // Convert git diff format to unified diff if needed\n if (patchContent && patchContent.split('\\n')[0].startsWith('diff --git')) {\n patchContent = this._convertGitDiffToUnifiedDiff(patchContent);\n }\n\n // Validate patch format\n this._validatePatchFormat(patchContent);\n\n // Backup existing patch file if it exists\n if (fs.existsSync(patchPath)) {\n const baseName = path.basename(patchPath, '.patch');\n const oldPatchPath = path.join(path.dirname(patchPath), `${baseName}1.patch`);\n await fs.promises.rename(patchPath, oldPatchPath);\n }\n\n // Write patch file\n await fs.promises.writeFile(patchPath, patchContent, 'utf-8');\n\n const bytesWritten = Buffer.from(patchContent, 'utf-8').length;\n const resultMsg = `Successfully wrote patch to ${patchPath}, wrote ${bytesWritten} bytes`;\n return warningMsg ? `${resultMsg}\\n${warningMsg}` : resultMsg;\n }\n\n /**\n * Apply a patch to a file\n *\n * @param patchPath - Path to the patch file\n * @param patchContent - Optional patch content to write before applying\n * @returns Success message\n */\n async applyPatch(patchPath: string, patchContent?: string): Promise<string> {\n let warningMsg = '';\n\n // Ensure patch_path ends with .patch\n if (!patchPath.endsWith('.patch')) {\n patchPath = `${patchPath}.patch`;\n warningMsg = `Warning: Patch path does not end with '.patch', automatically appended '.patch' to ${patchPath}`;\n }\n\n const patchFileAbs = path.resolve(patchPath);\n\n // Read existing patch file if no content provided\n if (patchContent === undefined) {\n if (!fs.existsSync(patchFileAbs)) {\n throw new Error(`Patch file does not exist: ${patchPath}`);\n }\n patchContent = await fs.promises.readFile(patchFileAbs, 'utf-8');\n }\n\n // Determine working directory\n const workDir = this._determineWorkDir(patchFileAbs, patchContent);\n\n // Write patch content to file if provided\n let writeMsg: string | undefined;\n if (patchContent !== undefined) {\n writeMsg = await this.writePatchFile(patchPath, patchContent);\n }\n\n // Apply the patch\n const applyMsg = await this._applyPatch(patchFileAbs, workDir);\n\n if (writeMsg) {\n return `${writeMsg}. ${applyMsg}.`;\n }\n return `Successfully applied existing patch file ${patchPath}. ${applyMsg}.\\n${warningMsg}`;\n }\n\n /**\n * Validate patch format\n */\n private _validatePatchFormat(patchContent: string): void {\n if (!patchContent.trim()) {\n throw new Error('Patch content is empty.');\n }\n\n const lines = patchContent.split('\\n');\n\n // Check for essential format elements\n const hasMinusLine = lines.slice(0, 50).some(line => line.startsWith('--- '));\n const hasPlusLine = lines.slice(0, 50).some(line => line.startsWith('+++ '));\n const hasHunkHeader = lines.slice(0, 100).some(line => /^@@ -\\d+,\\d+ \\+\\d+,\\d+ @@/.test(line));\n\n if (!(hasMinusLine && hasPlusLine)) {\n throw new Error(\n \"Patch does not appear to be in standard unified diff format. \" +\n \"Expected lines starting with '--- ' and '+++ '.\"\n );\n }\n\n if (!hasHunkHeader) {\n throw new Error(\n \"Patch does not contain valid hunk headers (lines starting with '@@'). \" +\n \"Example: '@@ -1,2 +1,2 @@'\"\n );\n }\n }\n\n /**\n * Convert git diff format to unified diff format\n */\n private _convertGitDiffToUnifiedDiff(patchContent: string): string {\n const lines = patchContent.split('\\n');\n const convertedLines: string[] = [];\n\n const skipPrefixes = [\n 'diff --git',\n 'index ',\n 'new file mode',\n 'old file mode',\n 'deleted file mode',\n 'rename from',\n 'rename to',\n 'similarity index',\n 'copy from',\n 'copy to',\n ];\n\n for (const line of lines) {\n // Skip git-specific headers\n if (skipPrefixes.some(prefix => line.startsWith(prefix))) {\n continue;\n }\n\n // Convert file paths from git format\n if (line.startsWith('--- a/')) {\n const filePath = line.slice(6).split('\\t')[0];\n convertedLines.push(`--- ${filePath}`);\n } else if (line.startsWith('+++ b/')) {\n const filePath = line.slice(6).split('\\t')[0];\n convertedLines.push(`+++ ${filePath}`);\n } else {\n convertedLines.push(line);\n }\n }\n\n return convertedLines.join('\\n');\n }\n\n /**\n * Extract target file path from patch content\n */\n private _extractTargetFile(patchContent: string): string | null {\n for (const line of patchContent.split('\\n')) {\n if (line.startsWith('+++ b/')) {\n return line.slice(6).split('\\t')[0];\n } else if (line.startsWith('+++ ') && !line.startsWith('+++ /dev/null')) {\n return line.slice(4).split('\\t')[0];\n }\n }\n return null;\n }\n\n /**\n * Determine working directory for applying patch\n */\n private _determineWorkDir(patchFileAbs: string, patchContent: string): string {\n const patchDir = path.dirname(patchFileAbs) || process.cwd();\n const defaultWorkDir = path.resolve(patchDir);\n\n const targetFile = this._extractTargetFile(patchContent);\n if (!targetFile || targetFile === '/dev/null') {\n return defaultWorkDir;\n }\n\n // Search for target file\n const searchDirs = [process.cwd(), patchDir];\n for (const searchDir of searchDirs) {\n const candidate = path.join(searchDir, targetFile);\n if (fs.existsSync(candidate)) {\n return path.dirname(candidate);\n }\n }\n\n return defaultWorkDir;\n }\n\n /**\n * Apply patch using patch command or manual fallback\n */\n private async _applyPatch(patchFileAbs: string, workDir: string): Promise<string> {\n // Try patch command first\n try {\n const result = await this._executePatchCommand(patchFileAbs, workDir);\n if (result.exitCode === 0) {\n return `Successfully applied patch using patch command${result.stdout ? ': ' + result.stdout : ''}`;\n }\n } catch (error) {\n logger.debug(`Patch command failed: ${error}`);\n }\n\n // Try manual application as fallback\n const manualResult = await this._applyPatchManually(patchFileAbs, workDir);\n if (manualResult) {\n return manualResult;\n }\n\n throw new Error(\n `Failed to apply patch ${patchFileAbs}. ` +\n `Working directory: ${workDir}. ` +\n 'Both patch command and manual application failed. ' +\n 'Please check: 1) patch format is correct, 2) target file exists, 3) line numbers match the file content.'\n );\n }\n\n /**\n * Execute patch command\n */\n private _executePatchCommand(patchFileAbs: string, workDir: string): Promise<{ exitCode: number; stdout: string; stderr: string }> {\n return new Promise((resolve, reject) => {\n const patchProcess = spawn('patch', ['--batch', '-p1', '-i', patchFileAbs], {\n cwd: workDir,\n });\n\n let stdout = '';\n let stderr = '';\n\n patchProcess.stdout.on('data', (data) => {\n stdout += data.toString();\n });\n\n patchProcess.stderr.on('data', (data) => {\n stderr += data.toString();\n });\n\n patchProcess.on('close', (code) => {\n resolve({\n exitCode: code || 0,\n stdout: stdout.trim(),\n stderr: stderr.trim(),\n });\n });\n\n patchProcess.on('error', (error) => {\n reject(error);\n });\n });\n }\n\n /**\n * Manually apply patch by parsing unified diff format\n */\n private async _applyPatchManually(patchFileAbs: string, workDir: string): Promise<string | null> {\n try {\n const patchContent = await fs.promises.readFile(patchFileAbs, 'utf-8');\n\n const targetFile = this._extractTargetFile(patchContent);\n if (!targetFile || targetFile === '/dev/null') {\n return null;\n }\n\n const targetPath = path.join(workDir, targetFile);\n const targetDir = path.dirname(targetPath);\n\n if (!fs.existsSync(targetDir)) {\n await fs.promises.mkdir(targetDir, { recursive: true });\n }\n\n // Read existing file or start with empty\n let fileLines: string[] = [];\n if (fs.existsSync(targetPath)) {\n const content = await fs.promises.readFile(targetPath, 'utf-8');\n fileLines = content.split('\\n');\n }\n\n // Parse and apply hunks\n const resultLines = [...fileLines];\n const lines = patchContent.split('\\n');\n let inHunk = false;\n let oldLineNum = 0;\n let newLineNum = 0;\n\n const skipPrefixes = ['diff --git', 'new file mode', 'index ', '---', '+++'];\n\n for (const line of lines) {\n // Hunk header\n const hunkMatch = line.match(/^@@ -(\\d+)(?:,(\\d+))? \\+(\\d+)(?:,(\\d+))? @@/);\n if (hunkMatch) {\n inHunk = true;\n oldLineNum = parseInt(hunkMatch[1], 10) - 1;\n newLineNum = parseInt(hunkMatch[3], 10) - 1;\n continue;\n }\n\n if (skipPrefixes.some(prefix => line.startsWith(prefix))) {\n continue;\n }\n\n if (!inHunk) {\n continue;\n }\n\n if (line.startsWith(' ')) {\n // Context line\n if (oldLineNum < resultLines.length) {\n oldLineNum++;\n }\n newLineNum++;\n } else if (line.startsWith('-')) {\n // Delete line\n if (oldLineNum < resultLines.length) {\n resultLines.splice(oldLineNum, 1);\n }\n } else if (line.startsWith('+')) {\n // Add line\n resultLines.splice(newLineNum, 0, line.slice(1));\n newLineNum++;\n }\n }\n\n // Write result\n await fs.promises.writeFile(targetPath, resultLines.join('\\n'), 'utf-8');\n\n return 'Successfully applied patch manually by parsing and applying changes';\n } catch (error) {\n logger.debug(`Manual patch application failed: ${error}`);\n return null;\n }\n }\n}\n","/**\n * Main Agent class with tool use capabilities\n *\n * Converts Python's core/agent.py to TypeScript\n */\n\nimport { v4 as uuidv4 } from 'uuid';\nimport * as path from 'path';\nimport * as fs from 'fs';\nimport { Model } from './model';\nimport { MessageHistory } from '../runtime/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 { 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';\nimport { AgentConfig, ToolExecutorProtocol } from './agentConfig';\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 // New properties from Python 0.2.2\n agentId: string;\n workspaceDir: string;\n executor: ToolExecutorProtocol | null;\n autoShutdownExecutor: boolean;\n private parallelExecution: boolean;\n private observeTimeout: number;\n private skills: string[];\n\n constructor(config: AgentConfig) {\n const {\n name,\n profile,\n system,\n tools = [],\n subAgents = [],\n mcpServerNames = [],\n modelConfig,\n udfModelName,\n verbose = false,\n useFunctionCalling = false,\n postProcessor = null,\n toolcallManagerPoolSize = 5,\n // New parameters from Python 0.2.2\n agentId,\n workspaceDir = '',\n executor = null,\n autoShutdownExecutor = false,\n parallelExecution = false,\n observeTimeout = 60.0,\n skills = [],\n } = config;\n\n this.name = name;\n this.profile = profile;\n this.verbose = verbose;\n // Support both modelConfig (legacy) and udfModelName (new)\n this.modelConfig = udfModelName || modelConfig || 'deepseek';\n this.subAgents = subAgents || [];\n this.postProcessor = postProcessor;\n this.useFunctionCalling = useFunctionCalling;\n\n // New properties from Python 0.2.2\n this.agentId = agentId || uuidv4();\n this.workspaceDir = workspaceDir ? path.resolve(workspaceDir) : '';\n this.executor = executor;\n this.autoShutdownExecutor = autoShutdownExecutor;\n this.parallelExecution = parallelExecution;\n this.observeTimeout = observeTimeout;\n this.skills = skills;\n\n // Create workspace directory if specified and doesn't exist\n if (this.workspaceDir && !fs.existsSync(this.workspaceDir)) {\n fs.mkdirSync(this.workspaceDir, { recursive: true });\n logger.debug(`Created workspace directory for agent ${this.name}: ${this.workspaceDir}`);\n }\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 // Auto shutdown executor if configured\n if (this.autoShutdownExecutor && this.executor) {\n try {\n await this.executor.shutdown({ wait: true });\n logger.debug(`Executor shutdown completed for agent ${this.name}`);\n } catch (error) {\n logger.warn(`Error during executor shutdown: ${error}`);\n }\n }\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 * Get agent ID\n */\n getAgentId(): string {\n return this.agentId;\n }\n\n /**\n * Get workspace directory\n */\n getWorkspaceDir(): string {\n return this.workspaceDir;\n }\n\n /**\n * Get parallel execution setting\n */\n getParallelExecution(): boolean {\n return this.parallelExecution;\n }\n\n /**\n * Get observe timeout setting\n */\n getObserveTimeout(): number {\n return this.observeTimeout;\n }\n\n /**\n * Get skills\n */\n getSkills(): string[] {\n return [...this.skills];\n }\n\n /**\n * Get executor\n */\n getExecutor(): ToolExecutorProtocol | null {\n return this.executor;\n }\n\n /**\n * Set executor\n */\n setExecutor(executor: ToolExecutorProtocol): void {\n this.executor = executor;\n }\n\n /**\n * Get chat history message\n */\n get chatHistoryMessage(): MessageHistory {\n return this.history;\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 case 'anthropic':\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 '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 case 'anthropic':\n return await this._callOpenAICompatible(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 history management\n *\n * Converts Python's runtime/memory/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\n/**\n * Simplified output format prompt (aligned with Python 0.2.2)\n *\n * This version removes the task classification (Generative/Analytical/Operational)\n * and uses a unified react-style format.\n */\nexport const OUTPUT_FORMAT_PROMPT = `<OutputFormat>\n\nYou should use one tool or multiple tools (depends on your task), follow the format below, replace the <ToolName.method_name> and <args_name> with the actual tool name.\n\nThought: ...\nAction: <ToolName1.method_name1><args_name1>args_value1</args_name1><args_name2>args_value2</args_name2>...</ToolName1.method_name1>\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</OutputFormat>\n`;\n\n/**\n * Tools prompt template (new name aligned with Python 0.2.2)\n *\n * Placeholders:\n * - {available_tools}: List of available tool names\n * - {desc_of_tools}: Descriptions of available tools\n * - {output_format}: Output format instructions\n */\nexport const TOOLS_PROMPT = `\n## Tools And Tool Calls Format\n\nTools 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 Tools\n{available_tools}\n\n### Description of Available Tools\n{desc_of_tools}\n\n### Output Format\n{output_format}\n`;\n\n/**\n * System tools prompt template (legacy name, kept for backward compatibility)\n *\n * @deprecated Use TOOLS_PROMPT instead. This is an alias with camelCase placeholders.\n *\n * Placeholders:\n * - {availableSystemTools}: List of available tool names\n * - {descOfSystemTools}: Descriptions of available tools\n * - {outputFormat}: Output format instructions\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/**\n * Legacy output format prompt with task classification\n *\n * @deprecated This version includes task classification (Generative/Analytical/Operational)\n * which has been removed in Python 0.2.2. Use OUTPUT_FORMAT_PROMPT instead.\n */\nexport const OUTPUT_FORMAT_PROMPT_LEGACY = `<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","/**\n * Feedback class for environment evaluation results\n *\n * Corresponds to Python's schemas/feedback.py\n * Used by ReflexionOrchestrator for environment feedback\n */\n\nimport { Message } from './message';\n\n/**\n * Feedback class representing evaluation results from an Environment\n *\n * Used in Reflexion loops where:\n * - Actor Agent generates/improves implementation\n * - Environment evaluates the implementation\n * - Feedback is returned with pass/fail status and detailed feedback message\n */\nexport class Feedback {\n /**\n * Whether the test/evaluation passed\n */\n isPassing: boolean;\n\n /**\n * Detailed feedback message\n */\n feedback: Message;\n\n constructor(isPassing: boolean = false, feedback?: Message) {\n this.isPassing = isPassing;\n this.feedback =\n feedback ||\n new Message('user', 'No feedback provided. Please check feedback settings.');\n\n // Validate feedback\n this._validate();\n }\n\n /**\n * Validate the feedback\n */\n private _validate(): void {\n if (!this.feedback.content) {\n throw new Error('Feedback content cannot be empty');\n }\n\n // Ensure tag contains 'feedback' (will be used when Message has tag property)\n if (this.feedback.tag !== undefined) {\n if (!this.feedback.tag) {\n this.feedback.tag = 'feedback';\n } else if (!this.feedback.tag.toLowerCase().includes('feedback')) {\n this.feedback.tag = `feedback_${this.feedback.tag}`;\n }\n }\n }\n\n /**\n * Convert feedback to a Message, optionally with pre/post content\n *\n * @param preContent - Content to prepend to the feedback\n * @param postContent - Content to append to the feedback\n * @returns Combined Message\n */\n toMessage(preContent: string = '', postContent: string = ''): Message {\n // Create a deep copy of the feedback message\n const feedbackMsg = new Message(\n this.feedback.role as 'system' | 'user' | 'assistant',\n this.feedback.content,\n this.feedback.images,\n this.feedback.type\n );\n\n // Copy additional properties if they exist\n if (this.feedback.tag !== undefined) {\n feedbackMsg.tag = this.feedback.tag;\n }\n\n let result = feedbackMsg;\n\n if (preContent) {\n const preMsg = new Message('user', preContent);\n result = this._mergeMessages(preMsg, result);\n }\n\n if (postContent) {\n const postMsg = new Message('user', postContent);\n result = this._mergeMessages(result, postMsg);\n }\n\n return result;\n }\n\n /**\n * Merge two messages into one\n */\n private _mergeMessages(first: Message, second: Message): Message {\n // Simple merge by concatenating content\n const merged = new Message(\n first.role as 'system' | 'user' | 'assistant',\n `${first.content}\\n${second.content}`,\n first.images || second.images,\n first.type || second.type\n );\n\n // Copy tag from second message if present\n if ((second as any).tag !== undefined) {\n (merged as any).tag = (second as any).tag;\n }\n\n return merged;\n }\n\n /**\n * Format feedback for API calls\n *\n * @param preContent - Content to prepend\n * @param postContent - Content to append\n * @returns Formatted object for API\n */\n formatForApi(preContent: string = '', postContent: string = ''): Record<string, any> {\n const message = this.toMessage(preContent, postContent);\n return message.toObject();\n }\n\n /**\n * Create a passing feedback\n */\n static pass(content: string): Feedback {\n return new Feedback(true, new Message('user', content));\n }\n\n /**\n * Create a failing feedback\n */\n static fail(content: string): Feedback {\n return new Feedback(false, new Message('user', content));\n }\n}\n","/**\n * Base orchestrator for multi-agent management\n *\n * Renamed from BaseEnvironment to BaseOrchestrator in 0.2.x\n * Converts Python's runtime/orchestrator/base.py to TypeScript\n */\n\nimport { Agent } from '../../core/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 * Base orchestrator for multi-agent coordination\n *\n * Renamed from BaseEnvironment in Python 0.2.x.\n * The old \"Environment\" name now refers to evaluation environments used by Reflexion.\n */\nexport class BaseOrchestrator {\n /**\n * List of agents in the orchestrator\n */\n agents: Agent[] = [];\n\n /**\n * Assign skills to agent with their names\n */\n agentSkills: Record<string, string[]> = {};\n\n /**\n * Whether to always wait for human input\n */\n alwaysWaitHumanInput: boolean = false;\n\n /**\n * Maximum number of rounds for agent execution\n */\n maxRounds: number = 100;\n\n constructor(options: {\n agents?: Agent[];\n agentSkills?: Record<string, string[]>;\n alwaysWaitHumanInput?: boolean;\n maxRounds?: number;\n } = {}) {\n const {\n agents = [],\n agentSkills = {},\n alwaysWaitHumanInput = false,\n maxRounds = 100,\n } = options;\n\n this.agents = agents;\n this.agentSkills = agentSkills;\n this.alwaysWaitHumanInput = alwaysWaitHumanInput;\n this.maxRounds = maxRounds;\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 * Shutdown all agent executors\n */\n async shutdownAllExecutors(options?: { wait?: boolean }): Promise<void> {\n const wait = options?.wait ?? true;\n for (const agent of this.agents) {\n // Future: when agents have executors, shut them down here\n // await agent.executor?.shutdown({ wait });\n }\n logger.debug('All agent executors shutdown');\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 orchestrator.');\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 orchestrator (interactive mode)\n */\n async run(instruction?: string): Promise<void> {\n // If instruction provided, run in non-interactive mode\n if (instruction) {\n await this.runGoal(instruction);\n return;\n }\n\n // Interactive mode\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 userInstruction: string;\n if (this.agents.length === 0) {\n logger.error('No agents in the orchestrator.');\n break;\n } else if (this.agents.length === 1) {\n userInstruction = await question(\"Enter your instruction (or '/q' to quit): \");\n } else {\n const agentNames = this.agents.map(agent => agent.name).join(', ');\n userInstruction = 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 userInstruction,\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/**\n * @deprecated Use BaseOrchestrator instead. This alias is kept for backward compatibility.\n */\nexport const BaseEnvironment = BaseOrchestrator;\n","/**\n * Coding orchestrator for multi-agent management\n *\n * Renamed from CodingEnvironment to CodingOrchestrator in 0.2.x\n * Converts Python's runtime/orchestrator/coding.py to TypeScript\n */\n\nimport * as fs from 'fs';\nimport { BaseOrchestrator } from './base';\nimport { Agent } from '../../core/agent';\nimport { WORKSPACE_DIR } from '../../configs/paths';\nimport { logger } from '../../utils';\n\n/**\n * Orchestrator for coding tasks\n *\n * Renamed from CodingEnvironment in Python 0.2.x.\n * Extends BaseOrchestrator with workspace directory management.\n */\nexport class CodingOrchestrator extends BaseOrchestrator {\n /**\n * Workspace directory\n */\n workspaceDir: string = '';\n\n constructor(options: {\n agents?: Agent[];\n agentSkills?: Record<string, string[]>;\n workspaceDir?: string;\n alwaysWaitHumanInput?: boolean;\n maxRounds?: number;\n } = {}) {\n const { workspaceDir = '', ...baseOptions } = options;\n super(baseOptions);\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\n/**\n * @deprecated Use CodingOrchestrator instead. This alias is kept for backward compatibility.\n */\nexport const CodingEnvironment = CodingOrchestrator;\n","/**\n * Reflexion Orchestrator\n *\n * Orchestrator for self-improvement loops using actor-critic pattern.\n *\n * Corresponds to Python's runtime/orchestrator/reflexion.py\n */\n\nimport { Agent } from '../../core/agent';\nimport { AgentConfig } from '../../core/agentConfig';\nimport { Environment } from '../environment';\nimport { Feedback } from '../../schemas/feedback';\nimport { Message } from '../../schemas/message';\nimport { logger } from '../../utils';\n\n/**\n * Configuration for the critic agent\n */\nexport interface CriticAgentConfig extends Partial<AgentConfig> {\n name?: string;\n profile?: string;\n tools?: string[];\n udfModelName?: string;\n workspaceDir?: string;\n fewShot?: string;\n verbose?: boolean | number;\n saveSelfReflection?: boolean;\n postContent?: string;\n}\n\n/**\n * Configuration for the actor agent\n */\nexport interface ActorAgentConfig extends Partial<AgentConfig> {\n name?: string;\n profile?: string;\n tools?: string[];\n udfModelName?: string;\n workspaceDir?: string;\n fewShot?: string;\n verbose?: boolean | number;\n}\n\n/**\n * Options for ReflexionOrchestrator\n */\nexport interface ReflexionOrchestratorOptions {\n /**\n * The task description\n */\n task: string;\n\n /**\n * The type of task (e.g., \"coding\", \"writing\")\n */\n taskType: string;\n\n /**\n * The type of feedback expected\n */\n feedbackType: string;\n\n /**\n * The evaluation environment\n */\n environment: Environment;\n\n /**\n * Configuration for the critic agent\n */\n criticAgentConfig?: CriticAgentConfig;\n\n /**\n * Configuration for the actor agent\n */\n actorAgentConfig?: ActorAgentConfig;\n\n /**\n * Maximum number of reflection rounds\n */\n maxIterations?: number;\n}\n\n/**\n * Result of a reflexion run\n */\nexport interface ReflexionResult {\n success: boolean;\n iterations: number;\n finalOutput: string;\n}\n\n/**\n * Default system prompt for critic agent\n */\nconst CRITIC_SYSTEM_PROMPT = `You are a critic agent specialized in {taskType} tasks.\n\nYour role is to:\n1. Analyze the implementation provided\n2. Identify issues and areas for improvement\n3. Provide constructive feedback in the form of {feedbackType}\n4. Suggest specific improvements\n\nBe thorough but constructive in your feedback.`;\n\n/**\n * Default system prompt for actor agent\n */\nconst ACTOR_SYSTEM_PROMPT = `You are an actor agent specialized in {taskType} tasks.\n\nYour role is to:\n1. Review the feedback and self-reflection\n2. Improve the implementation based on the suggestions\n3. Produce a better version of the code/output\n\nFocus on addressing all issues mentioned in the feedback.`;\n\n/**\n * Reflexion Orchestrator for self-improvement loops\n *\n * Implements the Reflexion pattern:\n * 1. Environment evaluates current implementation\n * 2. Critic agent generates self-reflection based on feedback\n * 3. Actor agent improves implementation based on reflection\n * 4. Repeat until passing or max iterations reached\n */\nexport class ReflexionOrchestrator {\n private task: string;\n private taskType: string;\n private feedbackType: string;\n private environment: Environment;\n private criticAgentConfig: CriticAgentConfig;\n private actorAgentConfig: ActorAgentConfig;\n private maxIterations: number;\n\n constructor(options: ReflexionOrchestratorOptions) {\n this.task = options.task;\n this.taskType = options.taskType;\n this.feedbackType = options.feedbackType;\n this.environment = options.environment;\n this.maxIterations = options.maxIterations ?? 3;\n\n // Default critic agent config\n this.criticAgentConfig = {\n name: 'CriticAgent',\n profile: 'You are an AI assistant.',\n tools: ['CommandLineTool.execute', 'FileEditor.write', 'FileEditor.read'],\n udfModelName: 'deepseek',\n workspaceDir: '',\n fewShot: '',\n verbose: false,\n saveSelfReflection: false,\n postContent: '',\n ...options.criticAgentConfig,\n };\n\n // Default actor agent config\n this.actorAgentConfig = {\n name: 'ActorAgent',\n profile: 'You are an AI engineer.',\n tools: ['CommandLineTool.execute', 'FileEditor.write', 'ThinkTool.execute'],\n udfModelName: 'deepseek',\n workspaceDir: '',\n fewShot: '',\n verbose: false,\n ...options.actorAgentConfig,\n };\n }\n\n /**\n * Create system prompt for critic agent\n */\n private createCriticSystemPrompt(): string {\n return CRITIC_SYSTEM_PROMPT\n .replace('{taskType}', this.taskType)\n .replace('{feedbackType}', this.feedbackType);\n }\n\n /**\n * Create system prompt for actor agent\n */\n private createActorSystemPrompt(): string {\n return ACTOR_SYSTEM_PROMPT\n .replace('{taskType}', this.taskType)\n .replace('{feedbackType}', this.feedbackType);\n }\n\n /**\n * Build history message for critic agent\n */\n private buildCriticHistoryMessage(impl: string, feedback: Feedback): Message[] {\n const preContent = this.criticAgentConfig.workspaceDir\n ? `Your workspace directory is: ${this.criticAgentConfig.workspaceDir}\\n\\n`\n : '';\n\n const postContent = (this.criticAgentConfig.postContent || '') +\n '\\nDo not change the impl file, just use tools to find the correct way and give the self-reflection.';\n\n return [feedback.toMessage(preContent, postContent)];\n }\n\n /**\n * Build history message for actor agent\n */\n private buildActorHistoryMessage(\n feedback: Message,\n selfReflection: string,\n improvedImplPath: string\n ): Message[] {\n const messages: Message[] = [];\n\n if (this.actorAgentConfig.fewShot) {\n messages.push(new Message('user', this.actorAgentConfig.fewShot));\n }\n\n messages.push(feedback);\n messages.push(new Message(\n 'assistant',\n `<self_reflection>\\n${selfReflection}\\n</self_reflection>`\n ));\n messages.push(new Message(\n 'user',\n `Use ThinkTool to recap the feedback and self-reflection, think how to improve the previous impl, and use FileEditor tools to write your improved implementation, and saved it to the file \\`${improvedImplPath}\\`.`\n ));\n\n return messages;\n }\n\n /**\n * Run the reflexion loop\n */\n async run(): Promise<ReflexionResult> {\n // Create agents\n const actor = new Agent({\n name: this.actorAgentConfig.name || 'ActorAgent',\n profile: this.actorAgentConfig.profile || 'You are an AI engineer.',\n system: this.createActorSystemPrompt(),\n tools: this.actorAgentConfig.tools,\n modelConfig: this.actorAgentConfig.udfModelName,\n verbose: this.actorAgentConfig.verbose,\n });\n\n const critic = new Agent({\n name: this.criticAgentConfig.name || 'CriticAgent',\n profile: this.criticAgentConfig.profile || 'You are an AI assistant.',\n system: this.createCriticSystemPrompt(),\n tools: this.criticAgentConfig.tools,\n modelConfig: this.criticAgentConfig.udfModelName,\n verbose: this.criticAgentConfig.verbose,\n });\n\n let currentRound = 0;\n let feedback = await this.environment.step(this.environment.initStepKwargs);\n let finalOutput = '';\n\n // Reflexion loop\n while (!feedback.isPassing && currentRound < this.maxIterations) {\n logger.debug(`Feedback: ${feedback.feedback.content}`);\n\n // Critic agent generates reflection\n const criticHistoryMsgs = this.buildCriticHistoryMessage(\n this.environment.improvedImpl,\n feedback\n );\n\n let selfReflection = await critic.run(\n criticHistoryMsgs[0].content\n );\n\n // Clean up task completion tags\n if (selfReflection.includes('<TaskCompletion>')) {\n selfReflection = selfReflection\n .replace(/<TaskCompletion>/g, '<self-reflection>')\n .replace(/<\\/TaskCompletion>/g, '</self-reflection>')\n .trim();\n }\n\n logger.info(`Critic agent self-reflection: ${selfReflection}`);\n\n // Actor agent generates improved implementation\n const actorHistoryMsgs = this.buildActorHistoryMessage(\n criticHistoryMsgs[criticHistoryMsgs.length - 1],\n selfReflection,\n this.environment.improvedImpl\n );\n\n let improvedImplSummary = await actor.run(\n actorHistoryMsgs[actorHistoryMsgs.length - 1].content\n );\n\n // Clean up task completion tags\n if (improvedImplSummary.includes('<TaskCompletion>')) {\n improvedImplSummary = improvedImplSummary\n .replace(/<TaskCompletion>/g, '<improved-impl-summary>')\n .replace(/<\\/TaskCompletion>/g, '</improved-impl-summary>')\n .trim();\n }\n\n logger.info(`Actor agent improved impl summary: ${improvedImplSummary}`);\n finalOutput = improvedImplSummary;\n\n // Next round\n feedback = await this.environment.step(this.environment.improvedStepKwargs);\n currentRound++;\n }\n\n logger.info(`Reflection task completed in ${currentRound} rounds`);\n\n // Cleanup: shutdown environment\n try {\n await this.environment.shutdown();\n logger.info('Environment shutdown completed');\n } catch (error) {\n logger.warn(`Error during environment shutdown: ${error}`);\n }\n\n return {\n success: feedback.isPassing,\n iterations: currentRound,\n finalOutput,\n };\n }\n}\n","/**\n * Abstract Environment class for Reflexion evaluation\n *\n * This is a NEW concept in 0.2.x, different from the old BaseEnvironment\n * (which has been renamed to BaseOrchestrator).\n *\n * The Environment is used by ReflexionOrchestrator to:\n * 1. Evaluate implementations against test cases\n * 2. Provide feedback on whether tests pass or fail\n * 3. Support iterative improvement cycles\n *\n * Corresponds to Python's runtime/environment/base.py\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { Feedback } from '../../schemas/feedback';\n\n/**\n * Environment options\n */\nexport interface EnvironmentOptions {\n /**\n * Path to the initial implementation file\n */\n initImpl: string;\n\n /**\n * Path to the improved implementation file\n * Must be different from initImpl\n */\n improvedImpl: string;\n\n /**\n * Arguments passed to step() for initial implementation\n */\n initStepKwargs?: Record<string, any>;\n\n /**\n * Arguments passed to step() for improved implementation\n */\n improvedStepKwargs?: Record<string, any>;\n}\n\n/**\n * Abstract Environment class for Reflexion evaluation\n *\n * Subclasses should implement:\n * - hasImpl(): Check if implementation exists\n * - step(): Execute and evaluate implementation, returning Feedback\n */\nexport abstract class Environment {\n /**\n * Arguments for the step method (initial implementation)\n */\n initStepKwargs: Record<string, any> = {};\n\n /**\n * Arguments for the step method (improved implementation)\n */\n improvedStepKwargs: Record<string, any> = {};\n\n /**\n * Path to the initial implementation file\n */\n initImpl: string;\n\n /**\n * Path to the improved implementation file\n */\n improvedImpl: string;\n\n constructor(options: EnvironmentOptions) {\n this.initImpl = path.resolve(options.initImpl);\n this.improvedImpl = path.resolve(options.improvedImpl);\n this.initStepKwargs = options.initStepKwargs || {};\n this.improvedStepKwargs = options.improvedStepKwargs || {};\n\n // Initialize the improved implementation by copying from init\n this._initImprovedImpl();\n }\n\n /**\n * Initialize the improved implementation by copying from init\n */\n private _initImprovedImpl(): void {\n if (fs.existsSync(this.initImpl)) {\n // Remove existing improved implementation if it exists\n if (fs.existsSync(this.improvedImpl)) {\n const stats = fs.statSync(this.improvedImpl);\n if (stats.isDirectory()) {\n fs.rmSync(this.improvedImpl, { recursive: true });\n } else {\n fs.unlinkSync(this.improvedImpl);\n }\n }\n\n // Copy init to improved\n fs.copyFileSync(this.initImpl, this.improvedImpl);\n }\n }\n\n /**\n * Check if the initial implementation exists\n */\n abstract hasImpl(): boolean;\n\n /**\n * Check if the improved implementation exists\n */\n hasImprovedImpl(): boolean {\n return fs.existsSync(this.improvedImpl);\n }\n\n /**\n * Execute and evaluate the implementation\n *\n * This method should:\n * 1. Run the implementation (or tests against it)\n * 2. Determine if it passes or fails\n * 3. Return a Feedback object with results\n *\n * @param args - Additional arguments\n * @returns Feedback with isPassing status and feedback message\n */\n abstract step(...args: any[]): Promise<Feedback>;\n\n /**\n * Shutdown the environment\n *\n * Called when the evaluation is complete or interrupted.\n * Override to clean up resources.\n */\n async shutdown(): Promise<void> {\n // Default implementation does nothing\n // Override in subclasses if cleanup is needed\n }\n\n /**\n * Evaluate the environment on a benchmark\n *\n * TODO: Add benchmark support for self-evolving\n *\n * @returns Whether the benchmark passed\n */\n async bench(): Promise<boolean> {\n throw new Error('bench() is not implemented');\n }\n}\n","/**\n * Tool Executor Protocol definitions\n *\n * Corresponds to Python's runtime/executors/base.py\n *\n * This module defines the protocol interfaces for tool execution:\n * - GeneratedToolcallProtocol: Represents a parsed tool call from LLM output\n * - ExecutedToolcallProtocol: Represents the result of executing a tool call\n * - ToolExecutorProtocol: Interface for tool execution backends\n */\n\n/**\n * Source of the tool call\n */\nexport type ToolcallSource = 'chat' | 'function_call';\n\n/**\n * Protocol for a generated tool call (parsed from LLM output)\n */\nexport interface GeneratedToolcallProtocol {\n /**\n * Name of the tool to execute\n */\n toolName: string;\n\n /**\n * Arguments for the tool\n */\n toolArguments: Record<string, any>;\n\n /**\n * Unique identifier for this tool call\n */\n toolCallId: string;\n\n /**\n * Source of the tool call (chat = XML extraction, function_call = OpenAI function calling)\n */\n source: ToolcallSource;\n\n /**\n * Whether the tool call was successfully parsed\n */\n isSuccess: boolean;\n\n /**\n * Reason for failure if isSuccess is false\n */\n failedReason?: string;\n\n /**\n * Raw content from LLM that generated this tool call\n */\n rawContentFromLlm?: string;\n\n /**\n * Idempotency key for deduplication\n */\n idempotencyKey: string;\n}\n\n/**\n * Protocol for an executed tool call (result)\n */\nexport interface ExecutedToolcallProtocol {\n /**\n * The original tool call metadata\n */\n metadata: GeneratedToolcallProtocol;\n\n /**\n * Whether the tool execution was successful\n */\n isSuccess: boolean;\n\n /**\n * Result of the tool execution (can be any type)\n */\n result: any;\n}\n\n/**\n * Status information returned by executor.status()\n */\nexport interface ExecutorStatus {\n /**\n * Number of pending tasks in queue\n */\n pending: number;\n\n /**\n * Number of currently running tasks\n */\n running: number;\n\n /**\n * Number of completed tasks\n */\n finished: number;\n\n /**\n * Number of failed tasks\n */\n failed: number;\n\n /**\n * Total tasks submitted\n */\n totalSubmitted: number;\n\n /**\n * Whether the executor is running\n */\n isRunning: boolean;\n}\n\n/**\n * Protocol interface for tool executors\n *\n * Tool executors are responsible for:\n * 1. Managing a pool of concurrent tool executions\n * 2. Tracking execution status and results\n * 3. Providing idempotency (avoiding duplicate executions)\n */\nexport interface ToolExecutorProtocol {\n // ---- Lifecycle ----\n\n /**\n * Initialize executor resources\n */\n start(): Promise<void>;\n\n /**\n * Shutdown executor and optionally wait for running tasks\n *\n * @param options.wait - Whether to wait for running tasks to complete\n */\n shutdown(options?: { wait?: boolean }): Promise<void>;\n\n // ---- Execution ----\n\n /**\n * Submit a tool call for background execution (non-blocking)\n *\n * @param toolcall - The tool call to execute\n */\n submit(toolcall: GeneratedToolcallProtocol): Promise<void>;\n\n /**\n * Submit multiple tool calls\n *\n * @param toolcalls - Tool calls to execute\n * @param options.parallel - Whether to execute in parallel (default: true)\n */\n submitMany(\n toolcalls: Iterable<GeneratedToolcallProtocol>,\n options?: { parallel?: boolean }\n ): Promise<void>;\n\n // ---- Observation ----\n\n /**\n * Observe finished executions\n *\n * @param options.wait - Whether to wait for results\n * @param options.timeout - Timeout in seconds\n * @param options.maxItems - Maximum number of items to return\n * @returns List of executed tool calls\n */\n observe(options?: {\n wait?: boolean;\n timeout?: number;\n maxItems?: number;\n }): Promise<ExecutedToolcallProtocol[]>;\n\n /**\n * Wait until all submitted tool calls are finished\n */\n waitAll(): Promise<void>;\n\n // ---- Status ----\n\n /**\n * Return executor runtime status\n */\n status(): ExecutorStatus;\n\n /**\n * Clear finished execution results\n */\n clear(): void;\n}\n\n/**\n * Helper function to create a GeneratedToolcallProtocol from basic info\n */\nexport function createGeneratedToolcall(options: {\n toolName: string;\n toolArguments: Record<string, any>;\n toolCallId?: string;\n source?: ToolcallSource;\n rawContentFromLlm?: string;\n}): GeneratedToolcallProtocol {\n const toolCallId = options.toolCallId || `call_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n\n return {\n toolName: options.toolName,\n toolArguments: options.toolArguments,\n toolCallId,\n source: options.source || 'chat',\n isSuccess: true,\n rawContentFromLlm: options.rawContentFromLlm,\n idempotencyKey: `${options.toolName}-${JSON.stringify(options.toolArguments)}-${toolCallId}`,\n };\n}\n\n/**\n * Helper function to create an ExecutedToolcallProtocol\n */\nexport function createExecutedToolcall(\n metadata: GeneratedToolcallProtocol,\n isSuccess: boolean,\n result: any\n): ExecutedToolcallProtocol {\n return {\n metadata,\n isSuccess,\n result,\n };\n}\n","/**\n * Tool execution utilities\n *\n * Corresponds to Python's runtime/executors/utils.py\n */\n\nimport { ToolStore } from '../../types';\nimport { Message } from '../../schemas/message';\nimport {\n GeneratedToolcallProtocol,\n ExecutedToolcallProtocol,\n createExecutedToolcall,\n} from './base';\nimport { logger } from '../../utils';\n\n/**\n * Execute a single tool and handle errors\n *\n * @param generatedToolcall - The tool call to execute\n * @param toolStore - Tool store(s) containing the tool implementations\n * @returns Executed tool call result\n */\nexport async function _executeSingleTool(\n generatedToolcall: GeneratedToolcallProtocol,\n toolStore: ToolStore | ToolStore[]\n): Promise<ExecutedToolcallProtocol> {\n // Normalize tool store to array\n const toolStores = Array.isArray(toolStore) ? toolStore : [toolStore];\n\n // Handle failed tool call extraction\n if (!generatedToolcall.isSuccess) {\n return createExecutedToolcall(\n generatedToolcall,\n false,\n `Tool extraction failed: ${generatedToolcall.failedReason || 'Unknown'}`\n );\n }\n\n // Handle TaskCompletion pseudo-tool\n if (generatedToolcall.toolName.toLowerCase() === 'taskcompletion') {\n return createExecutedToolcall(\n generatedToolcall,\n true,\n 'The task has been completed.'\n );\n }\n\n try {\n // Find and execute the tool\n for (const ts of toolStores) {\n if (ts.hasTool && ts.hasTool(generatedToolcall.toolName)) {\n const toolDef = ts.getTool!(generatedToolcall.toolName);\n if (!toolDef) {\n continue;\n }\n\n // Get the execute function\n const toolExecute = toolDef.execute;\n if (!toolExecute) {\n return createExecutedToolcall(\n generatedToolcall,\n false,\n `Tool '${generatedToolcall.toolName}' has no execute function`\n );\n }\n\n // Execute the tool\n const result = await toolExecute(generatedToolcall.toolArguments);\n\n // Convert result to string if not already a Message\n const resultValue = result instanceof Message ? result : String(result);\n\n return createExecutedToolcall(\n generatedToolcall,\n true,\n resultValue\n );\n }\n }\n\n // Tool not found\n return createExecutedToolcall(\n generatedToolcall,\n false,\n `Tool '${generatedToolcall.toolName}' not found in tool_store. Please check the tool name.`\n );\n } catch (error) {\n const errorMsg = `Error executing tool: ${error instanceof Error ? error.message : String(error)}`;\n logger.error(errorMsg);\n return createExecutedToolcall(\n generatedToolcall,\n false,\n errorMsg\n );\n }\n}\n\n/**\n * Execute multiple tools sequentially\n *\n * @param toolcalls - Tool calls to execute\n * @param toolStore - Tool store(s) containing the tool implementations\n * @returns Array of executed tool call results\n */\nexport async function executeToolsSequential(\n toolcalls: GeneratedToolcallProtocol[],\n toolStore: ToolStore | ToolStore[]\n): Promise<ExecutedToolcallProtocol[]> {\n const results: ExecutedToolcallProtocol[] = [];\n\n for (const toolcall of toolcalls) {\n const result = await _executeSingleTool(toolcall, toolStore);\n results.push(result);\n }\n\n return results;\n}\n\n/**\n * Execute multiple tools in parallel\n *\n * @param toolcalls - Tool calls to execute\n * @param toolStore - Tool store(s) containing the tool implementations\n * @param maxConcurrency - Maximum concurrent executions (default: 5)\n * @returns Array of executed tool call results\n */\nexport async function executeToolsParallel(\n toolcalls: GeneratedToolcallProtocol[],\n toolStore: ToolStore | ToolStore[],\n maxConcurrency: number = 5\n): Promise<ExecutedToolcallProtocol[]> {\n const results: ExecutedToolcallProtocol[] = [];\n const pending: Promise<void>[] = [];\n let runningCount = 0;\n\n for (const toolcall of toolcalls) {\n // Wait if we're at max concurrency\n while (runningCount >= maxConcurrency) {\n await Promise.race(pending);\n }\n\n runningCount++;\n const promise = (async () => {\n try {\n const result = await _executeSingleTool(toolcall, toolStore);\n results.push(result);\n } finally {\n runningCount--;\n }\n })();\n\n pending.push(promise);\n }\n\n // Wait for all remaining tasks\n await Promise.all(pending);\n\n return results;\n}\n","/**\n * LocalToolExecutor - Local tool executor implementation\n *\n * Implements ToolExecutorProtocol for local execution:\n * - Background async tool call execution\n * - Configurable concurrency limits\n * - Task queue management\n * - Execution result observation\n * - Background process management\n *\n * Corresponds to Python's runtime/executors/local_executor.py\n */\n\nimport { ChildProcess } from 'child_process';\nimport { v4 as uuidv4 } from 'uuid';\nimport { ToolStore } from '../../types';\nimport { logger } from '../../utils';\nimport {\n ToolExecutorProtocol,\n GeneratedToolcallProtocol,\n ExecutedToolcallProtocol,\n ExecutorStatus,\n createExecutedToolcall,\n} from './base';\nimport { _executeSingleTool } from './utils';\n\n/**\n * Background process info\n */\ninterface BackgroundProcessInfo {\n process: ChildProcess;\n command: string;\n cwd: string;\n pid: number;\n status: 'running' | 'stopped' | 'completed';\n}\n\n/**\n * Context variable for current executor (process-level)\n */\nlet _currentExecutor: LocalToolExecutor | null = null;\n\n/**\n * Get current executor from context\n */\nexport function getCurrentExecutor(): LocalToolExecutor | null {\n return _currentExecutor;\n}\n\n/**\n * Set current executor in context\n */\nexport function setCurrentExecutor(executor: LocalToolExecutor | null): void {\n _currentExecutor = executor;\n}\n\n/**\n * Local tool executor implementation\n *\n * Implements ToolExecutorProtocol for local execution.\n */\nexport class LocalToolExecutor implements ToolExecutorProtocol {\n private poolSize: number;\n private toolStores: ToolStore[];\n\n // Concurrency control\n private semaphore: { available: number };\n\n // Task management\n private pendingTasks: GeneratedToolcallProtocol[] = [];\n private runningTasks: Set<Promise<void>> = new Set();\n private finishedResults: ExecutedToolcallProtocol[] = [];\n private successTasks: Map<string, ExecutedToolcallProtocol> = new Map();\n private failedTasks: Map<string, ExecutedToolcallProtocol> = new Map();\n\n // Statistics\n private totalSubmitted: number = 0;\n private totalFinished: number = 0;\n private totalFailed: number = 0;\n\n // Lifecycle state\n private started: boolean = false;\n private isShutdown: boolean = false;\n\n // Background process management\n private backgroundProcesses: Map<string, BackgroundProcessInfo> = new Map();\n\n constructor(poolSize: number = 5, toolStores: ToolStore[] = []) {\n this.poolSize = poolSize;\n this.toolStores = toolStores;\n this.semaphore = { available: poolSize };\n }\n\n // ---- Lifecycle Methods ----\n\n async start(): Promise<void> {\n if (this.started) {\n logger.warn('Executor already started');\n return;\n }\n\n this.semaphore = { available: this.poolSize };\n this.started = true;\n this.isShutdown = false;\n logger.info(`LocalToolExecutor started with max concurrency: ${this.poolSize}`);\n }\n\n async shutdown(options?: { wait?: boolean }): Promise<void> {\n const wait = options?.wait ?? true;\n\n if (this.isShutdown) {\n logger.warn('Executor already shutdown');\n return;\n }\n\n this.isShutdown = true;\n\n if (wait && this.runningTasks.size > 0) {\n logger.info(`Waiting for ${this.runningTasks.size} running tasks to complete...`);\n await Promise.allSettled(Array.from(this.runningTasks));\n logger.info('All tasks completed');\n }\n\n // Clean up background processes\n if (this.backgroundProcesses.size > 0) {\n logger.info('Cleaning up background processes...');\n await this.cleanupBackgroundProcesses();\n }\n\n this.started = false;\n logger.info('LocalToolExecutor shutdown');\n }\n\n // ---- Execution Methods ----\n\n async submit(toolcall: GeneratedToolcallProtocol): Promise<void> {\n if (!this.started) {\n throw new Error('Executor not started. Call start() first.');\n }\n\n if (this.isShutdown) {\n throw new Error('Executor already shutdown');\n }\n\n this.totalSubmitted++;\n\n // Create background task\n const task = this._executeToolcall(toolcall);\n this.runningTasks.add(task);\n\n // Auto cleanup when done\n task.finally(() => {\n this.runningTasks.delete(task);\n });\n\n logger.debug(`Submitted tool call: ${toolcall.toolName}`);\n }\n\n async submitMany(\n toolcalls: Iterable<GeneratedToolcallProtocol>,\n options?: { parallel?: boolean }\n ): Promise<void> {\n if (!this.started) {\n throw new Error('Executor not started. Call start() first.');\n }\n\n const toolcallList = Array.from(toolcalls);\n if (toolcallList.length === 0) {\n return;\n }\n\n const parallel = options?.parallel ?? true;\n\n if (parallel) {\n // Parallel: submit all immediately\n for (const toolcall of toolcallList) {\n await this.submit(toolcall);\n }\n logger.debug(`Submitted ${toolcallList.length} tool calls in parallel`);\n } else {\n // Sequential: wait for each to complete\n logger.debug(`Starting sequential execution of ${toolcallList.length} tool calls`);\n for (const toolcall of toolcallList) {\n await this.submit(toolcall);\n // Wait for this task to complete\n while (this.runningTasks.size > 0) {\n await new Promise(resolve => setTimeout(resolve, 100));\n }\n }\n logger.debug('Sequential execution completed');\n }\n }\n\n // ---- Observation Methods ----\n\n async observe(options?: {\n wait?: boolean;\n timeout?: number;\n maxItems?: number;\n }): Promise<ExecutedToolcallProtocol[]> {\n const wait = options?.wait ?? false;\n const timeout = options?.timeout;\n const maxItems = options?.maxItems;\n\n if (wait && this.finishedResults.length === 0 && this.runningTasks.size > 0) {\n // Wait for at least one result\n const startTime = Date.now();\n while (this.finishedResults.length === 0 && this.runningTasks.size > 0) {\n if (timeout !== undefined) {\n const elapsed = (Date.now() - startTime) / 1000;\n if (elapsed >= timeout) {\n logger.warn(`Observe timeout (${timeout}s), no results yet`);\n break;\n }\n }\n await new Promise(resolve => setTimeout(resolve, 100));\n }\n }\n\n // Collect results\n const results: ExecutedToolcallProtocol[] = [];\n let count = 0;\n\n while (this.finishedResults.length > 0 && (maxItems === undefined || count < maxItems)) {\n results.push(this.finishedResults.shift()!);\n count++;\n }\n\n if (results.length > 0) {\n logger.debug(`Returning ${results.length} execution results`);\n }\n\n return results;\n }\n\n async waitAll(): Promise<void> {\n if (this.runningTasks.size > 0) {\n logger.debug(`Waiting for ${this.runningTasks.size} tasks to complete...`);\n await Promise.allSettled(Array.from(this.runningTasks));\n logger.info('All tasks completed');\n }\n }\n\n // ---- Status Methods ----\n\n status(): ExecutorStatus {\n return {\n pending: this.pendingTasks.length,\n running: this.runningTasks.size,\n finished: this.successTasks.size,\n failed: this.failedTasks.size,\n totalSubmitted: this.totalSubmitted,\n isRunning: this.started && !this.isShutdown,\n };\n }\n\n clear(): void {\n const cleared = this.finishedResults.length;\n this.finishedResults = [];\n this.successTasks.clear();\n this.failedTasks.clear();\n if (cleared > 0) {\n logger.debug(`Cleared ${cleared} execution results`);\n }\n }\n\n // ---- Private Methods ----\n\n private async _executeToolcall(toolcall: GeneratedToolcallProtocol): Promise<void> {\n // Check if already executed (idempotency)\n if (this.successTasks.has(toolcall.idempotencyKey) || this.failedTasks.has(toolcall.idempotencyKey)) {\n logger.debug(`Tool call already executed: ${toolcall.toolName}, using cached result`);\n const result = this.successTasks.get(toolcall.idempotencyKey) || this.failedTasks.get(toolcall.idempotencyKey);\n if (result) {\n this.finishedResults.push(result);\n }\n return;\n }\n\n // Check extraction success\n if (!toolcall.isSuccess) {\n logger.warn(`Tool call extraction failed: ${toolcall.toolName}, reason: ${toolcall.failedReason || 'Unknown'}`);\n const result = createExecutedToolcall(\n toolcall,\n false,\n `Tool extraction failed: ${toolcall.failedReason || 'Unknown'}`\n );\n this.finishedResults.push(result);\n this.totalFailed++;\n this.failedTasks.set(toolcall.idempotencyKey, result);\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 // Set current executor in context\n const previousExecutor = _currentExecutor;\n _currentExecutor = this;\n\n try {\n // Execute tool\n logger.debug(`Starting execution: ${toolcall.toolName}(${JSON.stringify(toolcall.toolArguments)})`);\n const executedToolcall = await _executeSingleTool(toolcall, this.toolStores);\n\n // Check execution result\n if (executedToolcall.isSuccess) {\n logger.debug(`Execution successful: ${executedToolcall.metadata.toolName}`);\n this.totalFinished++;\n this.successTasks.set(toolcall.idempotencyKey, executedToolcall);\n } else {\n logger.warn(\n `Execution failed: ${executedToolcall.metadata.toolName}, ` +\n `status: ${executedToolcall.isSuccess}, ` +\n `reason: ${executedToolcall.result}`\n );\n this.totalFailed++;\n this.failedTasks.set(toolcall.idempotencyKey, executedToolcall);\n }\n this.finishedResults.push(executedToolcall);\n } finally {\n // Restore context\n _currentExecutor = previousExecutor;\n }\n } catch (error) {\n logger.error(`Exception executing tool ${toolcall.toolName}: ${error}`);\n const result = createExecutedToolcall(\n toolcall,\n false,\n `Execution exception: ${error instanceof Error ? error.message : String(error)}`\n );\n this.finishedResults.push(result);\n this.failedTasks.set(toolcall.idempotencyKey, result);\n this.totalFailed++;\n } finally {\n // Release semaphore\n this.semaphore.available++;\n }\n }\n\n // ---- Background Process Management ----\n\n registerBackgroundProcess(process: ChildProcess, command: string, cwd: string): string {\n const processId = uuidv4().slice(0, 8);\n this.backgroundProcesses.set(processId, {\n process,\n command,\n cwd,\n pid: process.pid || 0,\n status: 'running',\n });\n logger.debug(`Registered background process: ${processId}, PID: ${process.pid}, Command: ${command}`);\n return processId;\n }\n\n listBackgroundProcesses(): string {\n if (this.backgroundProcesses.size === 0) {\n return 'No running background processes';\n }\n\n const lines: string[] = [`Total ${this.backgroundProcesses.size} background processes:\\n`];\n for (const [processId, info] of this.backgroundProcesses) {\n const status = info.process.exitCode !== null ? 'completed' : 'running';\n lines.push(\n `- Process ID: ${processId}\\n` +\n ` PID: ${info.pid}\\n` +\n ` Command: ${info.command}\\n` +\n ` Working Dir: ${info.cwd}\\n` +\n ` Status: ${status}`\n );\n if (info.process.exitCode !== null) {\n lines.push(` Exit Code: ${info.process.exitCode}`);\n }\n }\n return lines.join('\\n');\n }\n\n async stopBackgroundProcess(processId: string, force: boolean = false): Promise<string> {\n if (!this.backgroundProcesses.has(processId)) {\n return `Process ${processId} not found`;\n }\n\n const info = this.backgroundProcesses.get(processId)!;\n const process = info.process;\n\n if (process.exitCode !== null) {\n return `Process ${processId} already terminated (exit code: ${process.exitCode})`;\n }\n\n try {\n if (force) {\n process.kill('SIGKILL');\n logger.info(`Force killed process ${process.pid} (Process ID: ${processId})`);\n } else {\n process.kill('SIGTERM');\n logger.info(`Sent SIGTERM to process ${process.pid} (Process ID: ${processId})`);\n }\n\n // Wait for process to exit\n await new Promise<void>((resolve) => {\n const timeout = setTimeout(() => {\n if (process.exitCode === null && !force) {\n process.kill('SIGKILL');\n logger.warn(`Process ${process.pid} did not respond to SIGTERM, force killed`);\n }\n resolve();\n }, 5000);\n\n process.on('exit', () => {\n clearTimeout(timeout);\n resolve();\n });\n });\n\n info.status = 'stopped';\n return `Process ${processId} stopped`;\n } catch (error) {\n logger.error(`Error stopping process ${processId}: ${error}`);\n return `Failed to stop process ${processId}: ${error}`;\n }\n }\n\n async cleanupBackgroundProcesses(): Promise<string> {\n if (this.backgroundProcesses.size === 0) {\n return 'No background processes to clean up';\n }\n\n const total = this.backgroundProcesses.size;\n let cleaned = 0;\n const errors: string[] = [];\n\n for (const processId of Array.from(this.backgroundProcesses.keys())) {\n const info = this.backgroundProcesses.get(processId)!;\n const process = info.process;\n\n if (process.exitCode === null) {\n try {\n process.kill('SIGTERM');\n await new Promise<void>((resolve) => {\n const timeout = setTimeout(() => {\n if (process.exitCode === null) {\n process.kill('SIGKILL');\n }\n resolve();\n }, 3000);\n\n process.on('exit', () => {\n clearTimeout(timeout);\n resolve();\n });\n });\n } catch (error) {\n errors.push(`Process ${processId}: ${error}`);\n continue;\n }\n }\n\n this.backgroundProcesses.delete(processId);\n cleaned++;\n }\n\n if (errors.length > 0) {\n return `Cleaned ${cleaned}/${total} processes. Errors:\\n${errors.join('\\n')}`;\n }\n return `Successfully cleaned ${cleaned} background processes`;\n }\n}\n","/**\n * Agent State Store Protocol and Record Model\n *\n * Defines the interface for agent state persistence backends.\n *\n * Corresponds to Python's runtime/state/store.py\n */\n\n/**\n * Record type for state persistence\n */\nexport type StateRecordType = 'message' | 'tool_call' | 'instruction' | 'system' | 'completion';\n\n/**\n * A single state record for persistence\n */\nexport interface StateRecord {\n /**\n * Session identifier\n */\n sessionId: string;\n\n /**\n * Agent name\n */\n agentName: string;\n\n /**\n * Unix timestamp when the record was created\n */\n timestamp: number;\n\n /**\n * Record type\n */\n type: StateRecordType;\n\n /**\n * The actual payload data (serialized message or toolcall)\n */\n data: Record<string, any>;\n}\n\n/**\n * Session metadata information\n */\nexport interface SessionMeta {\n /**\n * Session identifier\n */\n sessionId: string;\n\n /**\n * Session creation timestamp (Unix timestamp)\n */\n timestamp: number;\n\n /**\n * First instruction content for display (optional)\n */\n firstInstruction?: string;\n\n /**\n * List of agent names that have records in this session\n */\n agents: string[];\n}\n\n/**\n * Protocol interface for agent state persistence backends\n *\n * All implementations must provide async append, getAll, and clear methods.\n * The sessionId + agentName combination uniquely identifies a record set.\n */\nexport interface AgentStateStore {\n /**\n * Append a single state record\n *\n * @param sessionId - Session identifier\n * @param agentName - Agent name\n * @param record - Record data containing type, data, and timestamp\n */\n append(sessionId: string, agentName: string, record: Omit<StateRecord, 'sessionId' | 'agentName'>): Promise<void>;\n\n /**\n * Get all records for a session/agent combination\n *\n * @param sessionId - Session identifier\n * @param agentName - Agent name\n * @returns List of StateRecord objects ordered by timestamp\n */\n getAll(sessionId: string, agentName: string): Promise<StateRecord[]>;\n\n /**\n * Clear all records for a session/agent combination\n *\n * @param sessionId - Session identifier\n * @param agentName - Agent name\n */\n clear(sessionId: string, agentName: string): Promise<void>;\n\n /**\n * Export records to a JSON file\n *\n * @param sessionId - Session identifier\n * @param agentName - Agent name\n * @param filename - Output file path\n */\n exportJson(sessionId: string, agentName: string, filename: string): void;\n\n /**\n * Import records from a JSON file\n *\n * @param filename - Input file path\n */\n importJson(filename: string): void;\n\n /**\n * Delete the last n records for a session/agent combination\n *\n * Records are ordered by timestamp, and the last n records\n * (most recent) will be deleted.\n *\n * @param sessionId - Session identifier\n * @param agentName - Agent name\n * @param n - Number of records to delete from the end\n * @returns Number of records actually deleted\n */\n deleteLastN(sessionId: string, agentName: string, n: number): Promise<number>;\n\n /**\n * Check if a session exists (regardless of agent)\n *\n * This method checks if any records exist for the given sessionId,\n * without filtering by agentName. Useful for distinguishing between\n * \"session does not exist\" and \"session exists but agent has no records\".\n *\n * @param sessionId - Session identifier\n * @returns True if any records exist for this sessionId, False otherwise\n */\n sessionExists(sessionId: string): Promise<boolean>;\n\n /**\n * List all available sessions\n *\n * @returns List of SessionMeta objects containing session metadata\n */\n listSessions(): SessionMeta[];\n\n /**\n * Get list of agent names that have records in a session\n *\n * @param sessionId - Session identifier\n * @returns List of unique agent names in this session\n */\n getAgentsInSession(sessionId: string): Promise<string[]>;\n}\n\n/**\n * Create a StateRecord from data\n */\nexport function createStateRecord(\n sessionId: string,\n agentName: string,\n type: StateRecordType,\n data: Record<string, any>\n): StateRecord {\n return {\n sessionId,\n agentName,\n timestamp: Date.now() / 1000,\n type,\n data,\n };\n}\n","/**\n * JSONL Agent State Store Implementation\n *\n * File-based persistence using JSON Lines format for append-friendly storage.\n *\n * Corresponds to Python's runtime/state/jsonl_store.py\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as os from 'os';\nimport { AgentStateStore, StateRecord, SessionMeta, StateRecordType } from './store';\nimport { logger } from '../../utils';\n\n/**\n * JSONL file-based state store implementation\n *\n * Stores records as JSON Lines (one JSON object per line) for efficient\n * append operations. Each session gets its own file named by session_id.\n *\n * File naming: {session_id}.jsonl\n */\nexport class JsonlAgentStateStore implements AgentStateStore {\n private storageDir: string;\n private maxSessions: number;\n private sessionFileMap: Map<string, string> = new Map();\n\n /**\n * Create a new JSONL state store\n *\n * @param storageDir - Directory to store JSONL files. Defaults to ~/.evolt/state/\n * @param maxSessions - Maximum number of session files to keep. Older sessions are automatically cleaned up.\n */\n constructor(storageDir?: string, maxSessions: number = 3) {\n this.storageDir = storageDir || path.join(os.homedir(), '.evolt', 'state');\n this.maxSessions = maxSessions;\n\n // Ensure storage directory exists\n if (!fs.existsSync(this.storageDir)) {\n fs.mkdirSync(this.storageDir, { recursive: true });\n }\n\n // Load existing session mappings\n this._loadSessionMap();\n }\n\n /**\n * Load existing session_id to file mappings from disk\n */\n private _loadSessionMap(): void {\n try {\n const files = fs.readdirSync(this.storageDir);\n for (const file of files) {\n if (file.endsWith('.jsonl')) {\n const sessionId = path.basename(file, '.jsonl');\n this.sessionFileMap.set(sessionId, path.join(this.storageDir, file));\n }\n }\n } catch (error) {\n logger.warn(`Failed to load session map: ${error}`);\n }\n }\n\n /**\n * Get existing file path for session or create a new one\n */\n private _getOrCreateFilePath(sessionId: string): string {\n if (this.sessionFileMap.has(sessionId)) {\n return this.sessionFileMap.get(sessionId)!;\n }\n\n const filePath = path.join(this.storageDir, `${sessionId}.jsonl`);\n this.sessionFileMap.set(sessionId, filePath);\n logger.debug(`Created new session file: ${filePath} for session=${sessionId}`);\n\n // Cleanup old sessions after new session is created\n this._cleanupOldSessions();\n\n return filePath;\n }\n\n /**\n * Cleanup old session files to maintain max_sessions limit\n */\n private _cleanupOldSessions(): number {\n try {\n const files = fs.readdirSync(this.storageDir)\n .filter(f => f.endsWith('.jsonl'))\n .map(f => path.join(this.storageDir, f));\n\n // Get files with their latest timestamps\n const filesWithTs: Array<{ path: string; timestamp: number }> = [];\n for (const filePath of files) {\n const timestamp = this._getLatestTimestamp(filePath);\n filesWithTs.push({ path: filePath, timestamp });\n }\n\n // Sort by timestamp descending (most recent first)\n filesWithTs.sort((a, b) => b.timestamp - a.timestamp);\n\n // Delete files beyond max_sessions limit\n let deleted = 0;\n for (let i = this.maxSessions; i < filesWithTs.length; i++) {\n const filePath = filesWithTs[i].path;\n try {\n // Remove from session map\n const sessionId = path.basename(filePath, '.jsonl');\n this.sessionFileMap.delete(sessionId);\n\n fs.unlinkSync(filePath);\n deleted++;\n logger.debug(`Deleted old session file: ${filePath}`);\n } catch (error) {\n logger.warn(`Failed to delete ${filePath}: ${error}`);\n }\n }\n\n if (deleted > 0) {\n logger.info(`Cleaned up ${deleted} old session files`);\n }\n\n return deleted;\n } catch (error) {\n logger.error(`Failed to cleanup old sessions: ${error}`);\n return 0;\n }\n }\n\n /**\n * Get the latest record timestamp from a session file\n */\n private _getLatestTimestamp(filePath: string): number {\n try {\n if (!fs.existsSync(filePath)) {\n return 0;\n }\n\n const content = fs.readFileSync(filePath, 'utf-8');\n const lines = content.trim().split('\\n').filter(l => l.trim());\n\n if (lines.length === 0) {\n return 0;\n }\n\n // Parse last line to get timestamp\n const lastLine = lines[lines.length - 1];\n try {\n const record = JSON.parse(lastLine);\n return record.timestamp || 0;\n } catch {\n return 0;\n }\n } catch (error) {\n return 0;\n }\n }\n\n async append(\n sessionId: string,\n agentName: string,\n record: Omit<StateRecord, 'sessionId' | 'agentName'>\n ): Promise<void> {\n const filePath = this._getOrCreateFilePath(sessionId);\n\n const fullRecord: StateRecord = {\n sessionId,\n agentName,\n ...record,\n };\n\n const line = JSON.stringify(fullRecord) + '\\n';\n\n await fs.promises.appendFile(filePath, line, 'utf-8');\n logger.debug(`Appended record to session ${sessionId}: type=${record.type}`);\n }\n\n async getAll(sessionId: string, agentName: string): Promise<StateRecord[]> {\n const filePath = this.sessionFileMap.get(sessionId);\n if (!filePath || !fs.existsSync(filePath)) {\n return [];\n }\n\n try {\n const content = await fs.promises.readFile(filePath, 'utf-8');\n const lines = content.trim().split('\\n').filter(l => l.trim());\n const records: StateRecord[] = [];\n\n for (const line of lines) {\n try {\n const record = JSON.parse(line) as StateRecord;\n if (record.agentName === agentName) {\n records.push(record);\n }\n } catch {\n logger.warn(`Failed to parse record line: ${line}`);\n }\n }\n\n // Sort by timestamp\n records.sort((a, b) => a.timestamp - b.timestamp);\n\n return records;\n } catch (error) {\n logger.error(`Failed to read session file: ${error}`);\n return [];\n }\n }\n\n async clear(sessionId: string, agentName: string): Promise<void> {\n const filePath = this.sessionFileMap.get(sessionId);\n if (!filePath || !fs.existsSync(filePath)) {\n return;\n }\n\n try {\n // Read all records\n const content = await fs.promises.readFile(filePath, 'utf-8');\n const lines = content.trim().split('\\n').filter(l => l.trim());\n\n // Keep only records from other agents\n const remainingLines: string[] = [];\n for (const line of lines) {\n try {\n const record = JSON.parse(line) as StateRecord;\n if (record.agentName !== agentName) {\n remainingLines.push(line);\n }\n } catch {\n // Keep unparseable lines\n remainingLines.push(line);\n }\n }\n\n // Rewrite file\n await fs.promises.writeFile(filePath, remainingLines.join('\\n') + '\\n', 'utf-8');\n logger.debug(`Cleared records for agent ${agentName} in session ${sessionId}`);\n } catch (error) {\n logger.error(`Failed to clear records: ${error}`);\n }\n }\n\n exportJson(sessionId: string, agentName: string, filename: string): void {\n // Sync wrapper for async operation\n const filePath = this.sessionFileMap.get(sessionId);\n if (!filePath || !fs.existsSync(filePath)) {\n fs.writeFileSync(filename, '[]', 'utf-8');\n return;\n }\n\n const content = fs.readFileSync(filePath, 'utf-8');\n const lines = content.trim().split('\\n').filter(l => l.trim());\n const records: StateRecord[] = [];\n\n for (const line of lines) {\n try {\n const record = JSON.parse(line) as StateRecord;\n if (record.agentName === agentName) {\n records.push(record);\n }\n } catch {\n // Skip unparseable lines\n }\n }\n\n fs.writeFileSync(filename, JSON.stringify(records, null, 2), 'utf-8');\n logger.info(`Exported ${records.length} records to ${filename}`);\n }\n\n importJson(filename: string): void {\n if (!fs.existsSync(filename)) {\n logger.warn(`Import file not found: ${filename}`);\n return;\n }\n\n const content = fs.readFileSync(filename, 'utf-8');\n const records = JSON.parse(content) as StateRecord[];\n\n // Group by sessionId\n const bySession = new Map<string, StateRecord[]>();\n for (const record of records) {\n if (!bySession.has(record.sessionId)) {\n bySession.set(record.sessionId, []);\n }\n bySession.get(record.sessionId)!.push(record);\n }\n\n // Write to files\n for (const [sessionId, sessionRecords] of bySession) {\n const filePath = this._getOrCreateFilePath(sessionId);\n const lines = sessionRecords.map(r => JSON.stringify(r));\n fs.appendFileSync(filePath, lines.join('\\n') + '\\n', 'utf-8');\n }\n\n logger.info(`Imported ${records.length} records from ${filename}`);\n }\n\n async deleteLastN(sessionId: string, agentName: string, n: number): Promise<number> {\n const filePath = this.sessionFileMap.get(sessionId);\n if (!filePath || !fs.existsSync(filePath)) {\n return 0;\n }\n\n try {\n const content = await fs.promises.readFile(filePath, 'utf-8');\n const lines = content.trim().split('\\n').filter(l => l.trim());\n\n // Parse and filter records\n const agentRecordIndices: number[] = [];\n const parsedRecords: Array<{ line: string; record: StateRecord | null }> = [];\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n try {\n const record = JSON.parse(line) as StateRecord;\n parsedRecords.push({ line, record });\n if (record.agentName === agentName) {\n agentRecordIndices.push(i);\n }\n } catch {\n parsedRecords.push({ line, record: null });\n }\n }\n\n // Determine which records to delete\n const indicesToDelete = new Set(agentRecordIndices.slice(-n));\n const deleted = indicesToDelete.size;\n\n // Keep records not in deletion set\n const remainingLines = parsedRecords\n .filter((_, i) => !indicesToDelete.has(i))\n .map(r => r.line);\n\n // Rewrite file\n await fs.promises.writeFile(filePath, remainingLines.join('\\n') + '\\n', 'utf-8');\n logger.debug(`Deleted ${deleted} records for agent ${agentName} in session ${sessionId}`);\n\n return deleted;\n } catch (error) {\n logger.error(`Failed to delete records: ${error}`);\n return 0;\n }\n }\n\n async sessionExists(sessionId: string): Promise<boolean> {\n const filePath = this.sessionFileMap.get(sessionId);\n return filePath !== undefined && fs.existsSync(filePath);\n }\n\n listSessions(): SessionMeta[] {\n const sessions: SessionMeta[] = [];\n\n for (const [sessionId, filePath] of this.sessionFileMap) {\n if (!fs.existsSync(filePath)) {\n continue;\n }\n\n try {\n const content = fs.readFileSync(filePath, 'utf-8');\n const lines = content.trim().split('\\n').filter(l => l.trim());\n\n if (lines.length === 0) {\n continue;\n }\n\n // Get first instruction and agents\n let firstInstruction: string | undefined;\n const agents = new Set<string>();\n let timestamp = 0;\n\n for (const line of lines) {\n try {\n const record = JSON.parse(line) as StateRecord;\n agents.add(record.agentName);\n\n if (timestamp === 0) {\n timestamp = record.timestamp;\n }\n\n if (!firstInstruction && record.type === 'instruction') {\n firstInstruction = record.data.content?.slice(0, 100);\n }\n } catch {\n // Skip unparseable lines\n }\n }\n\n sessions.push({\n sessionId,\n timestamp,\n firstInstruction,\n agents: Array.from(agents),\n });\n } catch (error) {\n logger.warn(`Failed to read session file ${filePath}: ${error}`);\n }\n }\n\n // Sort by timestamp descending\n sessions.sort((a, b) => b.timestamp - a.timestamp);\n\n return sessions;\n }\n\n async getAgentsInSession(sessionId: string): Promise<string[]> {\n const filePath = this.sessionFileMap.get(sessionId);\n if (!filePath || !fs.existsSync(filePath)) {\n return [];\n }\n\n try {\n const content = await fs.promises.readFile(filePath, 'utf-8');\n const lines = content.trim().split('\\n').filter(l => l.trim());\n const agents = new Set<string>();\n\n for (const line of lines) {\n try {\n const record = JSON.parse(line) as StateRecord;\n agents.add(record.agentName);\n } catch {\n // Skip unparseable lines\n }\n }\n\n return Array.from(agents);\n } catch (error) {\n logger.error(`Failed to read session file: ${error}`);\n return [];\n }\n }\n}\n","/**\n * Persistence Context Management\n *\n * Provides:\n * - Process-level session_id management (shared across all agents)\n * - Agent name tracking (per async context)\n * - Global store management for single-store-per-process pattern\n *\n * Corresponds to Python's runtime/state/context.py\n */\n\nimport { v4 as uuidv4 } from 'uuid';\nimport { AgentStateStore } from './store';\nimport { JsonlAgentStateStore } from './jsonlStore';\n\n// ---- Process-level Session ID Management ----\n// A single session_id shared across all agents in the process.\n// This ensures all agents in one run share the same session.\n\nlet _sessionId: string | null = null;\nlet _sessionIdExplicit: boolean = false; // Whether session_id was explicitly set\nlet _skipExecutorRestore: boolean = false; // Whether to skip executor restore\n\n/**\n * Use a specific session_id for restoring a historical session.\n *\n * @param sessionId - The session ID to restore from.\n * @param options.skipExecutorRestore - If true, skip restoring executor state (tool calls).\n *\n * @throws Error if session_id has already been set\n */\nexport function useSessionId(sessionId: string, options?: { skipExecutorRestore?: boolean }): void {\n if (_sessionId !== null) {\n throw new Error(\n `Session ID already set to '${_sessionId}'. ` +\n `Cannot change to '${sessionId}'. Call resetSessionId() first.`\n );\n }\n\n _sessionId = sessionId;\n _sessionIdExplicit = true;\n _skipExecutorRestore = options?.skipExecutorRestore ?? false;\n}\n\n/**\n * Get current session_id, or auto-create one if not set.\n *\n * The same session_id is shared across the entire process runtime.\n * Auto-created sessions will not attempt to restore.\n */\nexport function getOrCreateSessionId(): string {\n if (_sessionId === null) {\n _sessionId = uuidv4();\n _sessionIdExplicit = false; // auto-generated\n }\n return _sessionId;\n}\n\n/**\n * Get current session_id, or null if not set (will not auto-create).\n */\nexport function getSessionId(): string | null {\n return _sessionId;\n}\n\n/**\n * Check if this is a new session (auto-created, no restore needed).\n */\nexport function isNewSession(): boolean {\n return !_sessionIdExplicit;\n}\n\n/**\n * Reset session_id (for testing or when starting a new session).\n */\nexport function resetSessionId(): void {\n _sessionId = null;\n _sessionIdExplicit = false;\n _skipExecutorRestore = false;\n}\n\n/**\n * Check if executor restore should be skipped during session recovery.\n */\nexport function shouldSkipExecutorRestore(): boolean {\n return _skipExecutorRestore;\n}\n\n// ---- Global Store Management ----\n// A single store instance shared across all agents in the process.\n\nlet _globalStore: AgentStateStore | null = null;\n\n/**\n * Enable the global state store for persistence.\n *\n * Call this once at application startup to set up persistence.\n * All agents will automatically use this store.\n *\n * @param store - A pre-configured store instance. If not provided, creates a default JSONL store.\n * @param options.backend - Store backend type: \"jsonl\". Used if store is null.\n * @param options.storageDir - Directory for state storage. Defaults to ~/.evolt/state.\n * @returns The configured global store instance.\n */\nexport function enableStateStore(\n store?: AgentStateStore | null,\n options?: { backend?: 'jsonl'; storageDir?: string }\n): AgentStateStore | null {\n if (store !== undefined) {\n _globalStore = store;\n } else if (options?.backend === 'jsonl' || !options?.backend) {\n _globalStore = new JsonlAgentStateStore(options?.storageDir);\n } else {\n _globalStore = null;\n }\n\n return _globalStore;\n}\n\n/**\n * Get the global persistence store.\n *\n * @returns The global store instance, or null if not configured.\n */\nexport function getGlobalStore(): AgentStateStore | null {\n return _globalStore;\n}\n\n/**\n * Check if persistence is enabled globally.\n *\n * @returns True if a global store is configured.\n */\nexport function isPersistenceEnabled(): boolean {\n return _globalStore !== null;\n}\n\n// ---- Agent Name Context ----\n// Tracks the current agent name. Since Node.js doesn't have native ContextVars like Python,\n// we use a simple process-level variable. For proper async context tracking, consider\n// using AsyncLocalStorage from 'async_hooks'.\n\nlet _agentName: string | null = null;\n\n/**\n * Set the current agent name.\n *\n * @param agentName - Agent name to set\n */\nexport function setAgentName(agentName: string): void {\n _agentName = agentName;\n}\n\n/**\n * Get the current agent name.\n *\n * @returns Current agent name, or null if not set\n */\nexport function getAgentName(): string | null {\n return _agentName;\n}\n\n/**\n * Reset the agent name.\n */\nexport function resetAgentName(): void {\n _agentName = null;\n}\n","/**\n * Persistent State Decorator\n *\n * Decorator for automatically persisting state changes after successful\n * function execution.\n *\n * Corresponds to Python's runtime/state/decorator.py\n */\n\nimport { logger } from '../../utils';\nimport { StateRecordType } from './store';\nimport {\n getAgentName,\n getGlobalStore,\n getOrCreateSessionId,\n setAgentName,\n resetAgentName,\n} from './context';\n\n/**\n * Decorator to persist state after successful function execution.\n *\n * This decorator records state changes to the persistence store after\n * the decorated function completes successfully.\n *\n * @param recordType - Type of record to create (\"message\" or \"tool_call\")\n *\n * @example\n * ```typescript\n * class MyClass {\n * @persistentState(\"message\")\n * async addMessage(message: Message): Promise<void> {\n * // ... add message logic ...\n * }\n * }\n * ```\n */\nexport function persistentState(recordType: StateRecordType) {\n return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {\n const originalMethod = descriptor.value;\n\n descriptor.value = async function (...args: any[]) {\n // Execute the original function first\n const result = await originalMethod.apply(this, args);\n\n // Get persistence context\n const sessionId = getOrCreateSessionId();\n const agentName = getAgentName();\n const store = getGlobalStore();\n\n // Only persist if store is configured and agent_name is set\n if (store !== null && agentName) {\n // Determine actual record type\n let currentType: StateRecordType = recordType;\n\n // Serialize the data based on type\n const data = _serializeForPersistence(recordType, args, result);\n\n try {\n await store.append(sessionId, agentName, {\n type: currentType,\n data,\n timestamp: Date.now() / 1000,\n });\n logger.debug(`Persisted ${currentType} record for session=${sessionId}, agent=${agentName}`);\n } catch (error) {\n // Log but don't fail the operation\n logger.error(`Failed to persist state: ${error}`);\n }\n }\n\n return result;\n };\n\n return descriptor;\n };\n}\n\n/**\n * Serialize function arguments/result for persistence.\n */\nfunction _serializeForPersistence(\n recordType: StateRecordType,\n args: any[],\n result: any\n): Record<string, any> {\n if (recordType === 'message') {\n // For add_message, serialize the message argument\n const message = args[0];\n\n if (message !== undefined) {\n if (typeof message.toDict === 'function') {\n return { message: message.toDict() };\n } else if (typeof message.toObject === 'function') {\n return { message: message.toObject() };\n } else if (typeof message === 'object') {\n return { message };\n }\n }\n\n return { args: String(args) };\n } else if (recordType === 'tool_call') {\n // For submit_many, serialize the toolcalls\n const toolcalls: any[] = [];\n const toolcallsArg = args[0];\n\n if (toolcallsArg !== undefined && Symbol.iterator in Object(toolcallsArg)) {\n for (const tc of toolcallsArg) {\n if (typeof tc.toDict === 'function') {\n toolcalls.push(tc.toDict());\n } else if (typeof tc === 'object') {\n toolcalls.push(tc);\n }\n }\n }\n\n return { toolcalls };\n }\n\n return {};\n}\n\n/**\n * Decorator to handle session state for Agent.run method.\n *\n * This decorator manages the session lifecycle:\n * 1. Get or create session_id\n * 2. Set agent_name context\n * 3. Try restore from state store (if applicable)\n * 4. On success, record completion event\n *\n * @example\n * ```typescript\n * class Agent {\n * @agentAutoRestore\n * async run(instruction: string): Promise<string> {\n * // ... run logic ...\n * }\n * }\n * ```\n */\nexport function agentAutoRestore(target: any, propertyKey: string, descriptor: PropertyDescriptor) {\n const originalMethod = descriptor.value;\n\n descriptor.value = async function (this: any, instruction?: string, images?: string | string[]) {\n const inst = instruction || '';\n\n // Get or create session_id from process-level state\n const sessionId = getOrCreateSessionId();\n\n // Set agent name for persistence context\n const agentName = this.name;\n setAgentName(agentName);\n\n try {\n // Call the original run method\n const result = await originalMethod.call(this, inst, images);\n\n // Record completion event on success\n const store = getGlobalStore();\n if (store !== null && typeof result === 'string') {\n try {\n await store.append(sessionId, agentName, {\n type: 'completion',\n data: { response: result },\n timestamp: Date.now() / 1000,\n });\n logger.debug(`Recorded completion for session=${sessionId}, agent=${agentName}`);\n } catch (error) {\n logger.error(`Failed to record completion: ${error}`);\n }\n }\n\n return result;\n } catch (error) {\n logger.error(`Agent ${agentName} run error: ${error}`);\n throw error;\n } finally {\n // Reset agent name context\n resetAgentName();\n\n // Auto shutdown executor if configured\n if (this.autoShutdownExecutor && this.executor) {\n await this.executor.shutdown({ wait: true });\n }\n }\n };\n\n return descriptor;\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;AAC3B,SAA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,MACJ;AAAA,IACJ;AAEA,WAAO,EAAE,UAAU;AAAA,EACvB;AAEA,SAAO,CAAC;AACZ;AAqBO,SAAS,iBAAiB,QAAa,aAAqB,YAAgC;AAC/F,QAAM,iBAAiB,WAAW;AAElC,aAAW,QAAQ,eAA2B,aAAsB,QAA4B;AAC5F,UAAM,OAAO,eAAe;AAG5B,UAAM,YAAY,qBAAqB;AAGvC,UAAM,YAAY,KAAK;AACvB,iBAAa,SAAS;AAEtB,QAAI;AAEA,YAAM,SAAS,MAAM,eAAe,KAAK,MAAM,MAAM,MAAM;AAG3D,YAAM,QAAQ,eAAe;AAC7B,UAAI,UAAU,QAAQ,OAAO,WAAW,UAAU;AAC9C,YAAI;AACA,gBAAM,MAAM,OAAO,WAAW,WAAW;AAAA,YACrC,MAAM;AAAA,YACN,MAAM,EAAE,UAAU,OAAO;AAAA,YACzB,WAAW,KAAK,IAAI,IAAI;AAAA,UAC5B,CAAC;AACD,iBAAO,MAAM,mCAAmC,SAAS,WAAW,SAAS,EAAE;AAAA,QACnF,SAAS,OAAO;AACZ,iBAAO,MAAM,gCAAgC,KAAK,EAAE;AAAA,QACxD;AAAA,MACJ;AAEA,aAAO;AAAA,IACX,SAAS,OAAO;AACZ,aAAO,MAAM,SAAS,SAAS,eAAe,KAAK,EAAE;AACrD,YAAM;AAAA,IACV,UAAE;AAEE,qBAAe;AAGf,UAAI,KAAK,wBAAwB,KAAK,UAAU;AAC5C,cAAM,KAAK,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;AAAA,MAC/C;AAAA,IACJ;AAAA,EACJ;AAEA,SAAO;AACX;","names":["config","fs","logger","streamLogger","config","fs","path","path","fs","getConfigPath","config","config","fs","resolve","fs","path","fs","path","fs","path","config","resolve","format","fs","msg","path","path","fs","path","spawn","resolve","spawn","path","fs","tools","streamLogger","textParts","textContent","i","randomUUID","resolve","process","randomUUID","config","tools","InstructionType","skillDescription","resolve","fs","fs","path","uuidv4","resolve","process","uuidv4","fs","path","uuidv4","uuidv4"]}