@defai.digital/automatosx 5.0.13 → 5.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/CHANGELOG.md +110 -0
  2. package/README.md +310 -92
  3. package/dist/index.js +7784 -6097
  4. package/dist/index.js.map +1 -1
  5. package/dist/version.json +3 -3
  6. package/examples/AGENTS_INFO.md +495 -0
  7. package/examples/README.md +434 -0
  8. package/examples/abilities/accessibility.md +115 -0
  9. package/examples/abilities/api-design.md +159 -0
  10. package/examples/abilities/best-practices.md +102 -0
  11. package/examples/abilities/caching-strategy.md +165 -0
  12. package/examples/abilities/ci-cd.md +61 -0
  13. package/examples/abilities/code-generation.md +95 -0
  14. package/examples/abilities/code-review.md +42 -0
  15. package/examples/abilities/component-architecture.md +112 -0
  16. package/examples/abilities/content-creation.md +97 -0
  17. package/examples/abilities/data-modeling.md +171 -0
  18. package/examples/abilities/data-validation.md +50 -0
  19. package/examples/abilities/db-modeling.md +158 -0
  20. package/examples/abilities/debugging.md +43 -0
  21. package/examples/abilities/dependency-audit.md +60 -0
  22. package/examples/abilities/design-system-implementation.md +126 -0
  23. package/examples/abilities/documentation.md +54 -0
  24. package/examples/abilities/error-analysis.md +107 -0
  25. package/examples/abilities/etl-pipelines.md +44 -0
  26. package/examples/abilities/feasibility-study.md +20 -0
  27. package/examples/abilities/general-assistance.md +26 -0
  28. package/examples/abilities/idea-evaluation.md +21 -0
  29. package/examples/abilities/infra-as-code.md +57 -0
  30. package/examples/abilities/job-orchestration.md +44 -0
  31. package/examples/abilities/literature-review.md +19 -0
  32. package/examples/abilities/logical-analysis.md +21 -0
  33. package/examples/abilities/longform-report.md +25 -0
  34. package/examples/abilities/observability.md +61 -0
  35. package/examples/abilities/our-architecture-decisions.md +180 -0
  36. package/examples/abilities/our-code-review-checklist.md +149 -0
  37. package/examples/abilities/our-coding-standards.md +270 -0
  38. package/examples/abilities/our-project-structure.md +175 -0
  39. package/examples/abilities/performance-analysis.md +56 -0
  40. package/examples/abilities/performance.md +80 -0
  41. package/examples/abilities/problem-solving.md +50 -0
  42. package/examples/abilities/refactoring.md +49 -0
  43. package/examples/abilities/release-strategy.md +58 -0
  44. package/examples/abilities/risk-assessment.md +19 -0
  45. package/examples/abilities/secrets-policy.md +61 -0
  46. package/examples/abilities/secure-coding-review.md +51 -0
  47. package/examples/abilities/security-audit.md +65 -0
  48. package/examples/abilities/sql-optimization.md +84 -0
  49. package/examples/abilities/state-management.md +96 -0
  50. package/examples/abilities/task-planning.md +65 -0
  51. package/examples/abilities/technical-writing.md +77 -0
  52. package/examples/abilities/testing.md +47 -0
  53. package/examples/abilities/threat-modeling.md +49 -0
  54. package/examples/abilities/troubleshooting.md +80 -0
  55. package/examples/agents/.tmp +0 -0
  56. package/examples/agents/backend.yaml +69 -0
  57. package/examples/agents/ceo.yaml +60 -0
  58. package/examples/agents/cto.yaml +59 -0
  59. package/examples/agents/data.yaml +77 -0
  60. package/examples/agents/design.yaml +73 -0
  61. package/examples/agents/devops.yaml +82 -0
  62. package/examples/agents/frontend.yaml +74 -0
  63. package/examples/agents/product.yaml +69 -0
  64. package/examples/agents/quality.yaml +70 -0
  65. package/examples/agents/researcher.yaml +71 -0
  66. package/examples/agents/security.yaml +84 -0
  67. package/examples/agents/writer.yaml +77 -0
  68. package/examples/claude/commands/ax:agent.md +37 -0
  69. package/examples/claude/commands/ax:clear.md +22 -0
  70. package/examples/claude/commands/ax:init.md +25 -0
  71. package/examples/claude/commands/ax:list.md +19 -0
  72. package/examples/claude/commands/ax:memory.md +25 -0
  73. package/examples/claude/commands/ax:status.md +24 -0
  74. package/examples/claude/commands/ax:update.md +28 -0
  75. package/examples/claude/mcp/automatosx.json +244 -0
  76. package/examples/teams/business.yaml +56 -0
  77. package/examples/teams/core.yaml +59 -0
  78. package/examples/teams/design.yaml +58 -0
  79. package/examples/teams/engineering.yaml +69 -0
  80. package/examples/teams/research.yaml +56 -0
  81. package/examples/templates/analyst.yaml +60 -0
  82. package/examples/templates/assistant.yaml +48 -0
  83. package/examples/templates/basic-agent.yaml +28 -0
  84. package/examples/templates/code-reviewer.yaml +52 -0
  85. package/examples/templates/debugger.yaml +63 -0
  86. package/examples/templates/designer.yaml +69 -0
  87. package/examples/templates/developer.yaml +60 -0
  88. package/examples/templates/fullstack-developer.yaml +395 -0
  89. package/examples/templates/qa-specialist.yaml +71 -0
  90. package/examples/use-cases/01-web-app-development.md +374 -0
  91. package/package.json +2 -1
  92. package/version.json +3 -3
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../node_modules/tsup/assets/esm_shims.js","../src/types/path.ts","../src/core/path-resolver.ts","../src/cli/index.ts","../src/utils/logger.ts","../src/utils/performance.ts","../src/cli/commands/config.ts","../src/types/config.ts","../src/utils/error-formatter.ts","../src/utils/errors.ts","../src/utils/message-formatter.ts","../src/utils/config-validator.ts","../src/core/config.ts","../src/utils/deep-merge.ts","../src/core/validation-limits.ts","../src/core/cache.ts","../src/cli/commands/init.ts","../src/cli/commands/list.ts","../src/cli/commands/memory.ts","../src/core/memory-manager.ts","../src/types/memory.ts","../src/utils/progress.ts","../src/cli/commands/run.ts","../src/agents/context-manager.ts","../src/agents/profile-loader.ts","../src/types/agent.ts","../src/agents/abilities-manager.ts","../src/agents/executor.ts","../src/types/orchestration.ts","../src/agents/delegation-parser.ts","../src/agents/stage-executor.ts","../src/agents/advanced-stage-executor.ts","../src/core/router.ts","../src/core/session-manager.ts","../src/core/workspace-manager.ts","../src/core/team-manager.ts","../src/types/team.ts","../src/providers/claude-provider.ts","../src/providers/base-provider.ts","../src/providers/gemini-provider.ts","../src/providers/openai-provider.ts","../src/utils/output-formatter.ts","../src/cli/commands/session.ts","../src/cli/utils/session-utils.ts","../src/cli/commands/status.ts","../src/cli/commands/update.ts","../src/cli/commands/workspace.ts","../src/cli/commands/agent/index.ts","../src/cli/commands/agent/templates.ts","../src/cli/commands/agent/create.ts","../src/agents/template-engine.ts","../src/cli/commands/agent/helpers.ts","../src/cli/commands/agent/list.ts","../src/cli/commands/agent/show.ts","../src/cli/commands/agent/remove.ts"],"sourcesContent":["// Shim globals in esm bundle\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nconst getFilename = () => fileURLToPath(import.meta.url)\nconst getDirname = () => path.dirname(getFilename())\n\nexport const __dirname = /* @__PURE__ */ getDirname()\nexport const __filename = /* @__PURE__ */ getFilename()\n","/**\n * Path resolution types\n */\n\nexport type PathType =\n | 'agent_workspace'\n | 'user_project'\n | 'system_restricted'\n | 'outside_boundaries';\n\nexport interface PathResolverConfig {\n projectDir: string;\n workingDir: string;\n agentWorkspace: string;\n allowSystemAccess?: boolean;\n}\n\nexport interface PathContext {\n /** Auto-detect project root (priority: .git > package.json > cwd) */\n detectProjectRoot(startDir?: string): Promise<string>;\n\n /** Resolve paths relative to project root */\n resolveProjectPath(relativePath: string): string;\n\n /** Resolve paths relative to working directory */\n resolveWorkingPath(relativePath: string): string;\n\n /** Validate path safety (prevent path traversal) */\n validatePath(path: string, baseDir: string): boolean;\n\n /** Check if path is within allowed boundaries */\n isPathAllowed(path: string): boolean;\n}\n\nexport class PathError extends Error {\n constructor(\n message: string,\n public readonly context?: Record<string, unknown>\n ) {\n super(message);\n this.name = 'PathError';\n }\n}\n","/**\n * Path Resolution Module\n *\n * Handles path resolution for AutomatosX v4.0 with three directory contexts:\n * 1. Project Directory - User's project root (auto-detected)\n * 2. Working Directory - Command execution location\n * 3. Agent Workspace - Agent's isolated workspace\n *\n * @see PRD/16-path-resolution-strategy.md\n */\n\nimport { resolve, dirname, relative, isAbsolute, sep } from 'path';\nimport { findUp } from 'find-up';\nimport type { PathResolverConfig, PathType, PathContext } from '../types/path.js';\nimport { PathError } from '../types/path.js';\n\n/**\n * Check if a path is a Windows-style path (e.g., C:\\, D:\\)\n */\nfunction isWindowsPath(path: string): boolean {\n return /^[a-zA-Z]:[/\\\\]/.test(path);\n}\n\n/**\n * Project root detection\n * Priority: .git > package.json > other markers > fallback to cwd\n */\nexport async function detectProjectRoot(\n startDir: string = process.cwd()\n): Promise<string> {\n // Priority 1: Find .git directory\n const gitDir = await findUp('.git', {\n cwd: startDir,\n type: 'directory'\n });\n if (gitDir) {\n return dirname(gitDir);\n }\n\n // Priority 2: Find package.json\n const pkgJson = await findUp('package.json', {\n cwd: startDir\n });\n if (pkgJson) {\n return dirname(pkgJson);\n }\n\n // Priority 3: Find other project markers\n const markers = [\n 'pyproject.toml', // Python\n 'Cargo.toml', // Rust\n 'go.mod', // Go\n 'pom.xml', // Java/Maven\n 'build.gradle', // Java/Gradle\n '.automatosx' // AutomatosX marker\n ];\n\n for (const marker of markers) {\n const found = await findUp(marker, { cwd: startDir });\n if (found) {\n return dirname(found);\n }\n }\n\n // Priority 4: Fallback to startDir\n return startDir;\n}\n\n/**\n * Path Resolver\n * Provides safe path resolution with boundary validation\n */\nexport class PathResolver implements PathContext {\n private readonly config: PathResolverConfig;\n\n constructor(config: PathResolverConfig) {\n this.config = config;\n }\n\n /**\n * Auto-detect project root\n */\n async detectProjectRoot(startDir?: string): Promise<string> {\n return detectProjectRoot(startDir);\n }\n\n /**\n * Resolve user-provided path\n * - Absolute paths: validated within project\n * - Relative paths: resolved from workingDir\n */\n resolveUserPath(userPath: string): string {\n // Reject Windows paths on non-Windows platforms\n if (process.platform !== 'win32' && isWindowsPath(userPath)) {\n throw new PathError(\n `Windows paths are not supported on ${process.platform}`,\n { path: userPath, type: 'invalid_path' }\n );\n }\n\n // Handle absolute paths\n if (isAbsolute(userPath)) {\n const normalized = resolve(userPath);\n this.validateInProject(normalized);\n return normalized;\n }\n\n // Handle relative paths (relative to workingDir)\n const resolved = resolve(this.config.workingDir, userPath);\n this.validateInProject(resolved);\n return resolved;\n }\n\n /**\n * Resolve paths relative to project root\n */\n resolveProjectPath(relativePath: string): string {\n const resolved = resolve(this.config.projectDir, relativePath);\n this.validateInProject(resolved);\n return resolved;\n }\n\n /**\n * Resolve paths relative to working directory\n */\n resolveWorkingPath(relativePath: string): string {\n const resolved = resolve(this.config.workingDir, relativePath);\n this.validateInProject(resolved);\n return resolved;\n }\n\n /**\n * Resolve agent workspace path\n * - Always within agent workspace\n * - Full read/write access\n */\n resolveWorkspacePath(agentPath: string): string {\n return resolve(this.config.agentWorkspace, agentPath);\n }\n\n /**\n * Validate path is within allowed base directory\n */\n validatePath(path: string, baseDir: string): boolean {\n const normalized = resolve(path);\n const base = resolve(baseDir);\n\n // Check if path starts with baseDir\n // Use platform-specific separator to ensure correct comparison\n const pathWithSep = normalized + sep;\n const baseWithSep = base + sep;\n\n return pathWithSep.startsWith(baseWithSep) || normalized === base;\n }\n\n /**\n * Check if path is within allowed boundaries\n */\n isPathAllowed(path: string): boolean {\n const boundary = this.checkBoundaries(path);\n return boundary === 'agent_workspace' || boundary === 'user_project';\n }\n\n /**\n * Check which boundary a path belongs to\n */\n checkBoundaries(path: string): PathType {\n const normalized = resolve(path);\n\n // Check agent workspace first (more specific)\n if (this.validatePath(normalized, this.config.agentWorkspace)) {\n return 'agent_workspace';\n }\n\n // Check user project\n if (this.validatePath(normalized, this.config.projectDir)) {\n return 'user_project';\n }\n\n // Check system directories (platform-specific)\n const systemDirs = this.getSystemDirs();\n for (const sysDir of systemDirs) {\n if (this.validatePath(normalized, sysDir)) {\n return 'system_restricted';\n }\n }\n\n return 'outside_boundaries';\n }\n\n /**\n * Get relative path from project root\n */\n getRelativeToProject(path: string): string {\n const normalized = resolve(path);\n return relative(this.config.projectDir, normalized);\n }\n\n /**\n * Get relative path from working directory\n */\n getRelativeToWorking(path: string): string {\n const normalized = resolve(path);\n return relative(this.config.workingDir, normalized);\n }\n\n /**\n * Get agents directory path\n */\n getAgentsDirectory(): string {\n return resolve(this.config.projectDir, '.automatosx', 'agents');\n }\n\n /**\n * Get abilities directory path\n */\n getAbilitiesDirectory(): string {\n return resolve(this.config.projectDir, '.automatosx', 'abilities');\n }\n\n /**\n * Validate path is within project boundaries\n * @throws PathError if outside project\n */\n private validateInProject(path: string): void {\n const boundary = this.checkBoundaries(path);\n\n if (boundary === 'outside_boundaries' || boundary === 'system_restricted') {\n throw new PathError('Path outside project directory', {\n path,\n projectDir: this.config.projectDir,\n boundary\n });\n }\n }\n\n /**\n * Get system directories (platform-specific)\n */\n private getSystemDirs(): string[] {\n const platform = process.platform;\n\n if (platform === 'win32') {\n return [\n 'C:\\\\Windows',\n 'C:\\\\Program Files',\n 'C:\\\\Program Files (x86)'\n ];\n } else {\n return ['/etc', '/proc', '/sys', '/var', '/usr'];\n }\n }\n}\n","/**\n * AutomatosX CLI Entry Point\n *\n * Provides command-line interface for AutomatosX agent orchestration platform.\n *\n * Global Options:\n * - --debug: Enable debug mode with verbose output\n * - --quiet: Suppress non-essential output\n * - --config: Path to custom config file\n */\n\nimport yargs from 'yargs';\nimport { hideBin } from 'yargs/helpers';\nimport { createRequire } from 'module';\nimport { logger, setLogLevel } from '../utils/logger.js';\nimport { globalTracker } from '../utils/performance.js';\n\n// Read version from version.json (single source of truth)\nconst require = createRequire(import.meta.url);\nlet VERSION = 'unknown';\ntry {\n // Try to load from same directory first (when built to dist/)\n const versionData = require('../version.json');\n VERSION = versionData.version || 'unknown';\n} catch (err) {\n // Fallback: try parent directory (development mode)\n try {\n const versionData = require('../../version.json');\n VERSION = versionData.version || 'unknown';\n } catch (err2) {\n // Final fallback: package.json\n try {\n const packageJson = require('../../package.json');\n VERSION = packageJson.version || 'unknown';\n } catch (err3) {\n logger.debug('Version file not found, using fallback');\n }\n }\n}\n\n// Import all commands directly (lazy loading broke command options)\nimport { configCommand } from './commands/config.js';\nimport { initCommand } from './commands/init.js';\nimport { listCommand } from './commands/list.js';\nimport { memoryCommand } from './commands/memory.js';\nimport { runCommand } from './commands/run.js';\nimport { sessionCommand } from './commands/session.js';\nimport { statusCommand } from './commands/status.js';\nimport { updateCommand } from './commands/update.js';\nimport { workspaceCommand } from './commands/workspace.js';\nimport { agentCommand } from './commands/agent/index.js';\n\n// Mark CLI startup\nglobalTracker.mark('cli_start');\n\n// Parse CLI arguments\nglobalTracker.mark('yargs_parse_start');\nconst argv = await yargs(hideBin(process.argv))\n .scriptName('automatosx')\n .usage('$0 <command> [options]')\n .usage('\\nAI Agent Orchestration Platform')\n .example('$0 init', 'Initialize project')\n .example('$0 agent create backend --template developer', 'Create agent from template')\n .example('$0 agent list', 'List all agents')\n .example('$0 run assistant \"Hello\"', 'Run assistant agent')\n .example('$0 session create \"Build API\" backend', 'Create multi-agent session')\n .example('$0 session list', 'List all sessions')\n .example('$0 workspace stats', 'Show workspace statistics')\n .example('$0 list agents', 'List available agents')\n .example('$0 memory search \"topic\"', 'Search memory')\n .example('$0 config --list', 'View configuration')\n .example('$0 update', 'Update to latest version')\n\n // Global options\n .option('debug', {\n alias: 'd',\n type: 'boolean',\n description: 'Enable debug mode with verbose output',\n global: true\n })\n .option('quiet', {\n alias: 'q',\n type: 'boolean',\n description: 'Suppress non-essential output',\n global: true\n })\n .option('config', {\n alias: 'c',\n type: 'string',\n description: 'Path to custom config file',\n global: true\n })\n\n // Commands\n .command(initCommand)\n .command(agentCommand)\n .command(listCommand)\n .command(runCommand)\n .command(sessionCommand)\n .command(workspaceCommand)\n .command(configCommand)\n .command(statusCommand)\n .command(memoryCommand)\n .command(updateCommand)\n\n // Configuration\n .demandCommand(1, 'You must provide a command. Run --help for usage.')\n .help()\n .version(VERSION)\n .alias('h', 'help')\n .alias('v', 'version')\n .strict()\n .wrap(Math.min(120, yargs().terminalWidth()))\n .parse();\n\nglobalTracker.mark('yargs_parse_end');\nglobalTracker.measure('yargs_parsing', 'yargs_parse_start', 'yargs_parse_end');\n\n// Apply global options\nglobalTracker.mark('options_setup_start');\n\nif (argv.debug) {\n setLogLevel('debug');\n process.env.AUTOMATOSX_DEBUG = 'true';\n logger.debug('Debug mode enabled', {\n node: process.version,\n platform: process.platform,\n arch: process.arch,\n cwd: process.cwd(),\n argv: process.argv.slice(2)\n });\n}\n\nif (argv.quiet) {\n setLogLevel('error');\n process.env.AUTOMATOSX_QUIET = 'true';\n}\n\n// Store global options in process.env for access by commands\nif (argv.config) {\n process.env.AUTOMATOSX_CONFIG_PATH = argv.config as string;\n logger.debug('Custom config path set', { path: argv.config });\n}\n\n// Log startup info in debug mode\nif (argv.debug) {\n logger.debug('AutomatosX CLI started', {\n version: VERSION,\n command: argv._[0],\n options: {\n debug: argv.debug,\n quiet: argv.quiet,\n config: argv.config\n }\n });\n}\n\nglobalTracker.mark('options_setup_end');\nglobalTracker.measure('options_setup', 'options_setup_start', 'options_setup_end');\n\n// Mark CLI ready\nglobalTracker.mark('cli_ready');\nglobalTracker.measure('cli_startup', 'cli_start', 'cli_ready');\n\n// Output profile report if enabled\nif (globalTracker.isEnabled() && argv.debug) {\n console.error('\\n' + globalTracker.generateReport() + '\\n');\n}\n","/**\n * Enhanced Logger for AutomatosX\n *\n * Features:\n * - Structured logging (JSON mode)\n * - File output with rotation\n * - Secrets sanitization\n * - Multiple log levels\n * - Performance profiling\n */\n\nimport type { Logger, LogEntry, LoggerConfig } from '../types/logger.js';\nimport { LogLevel } from '../types/logger.js';\nimport { writeFile, appendFile, mkdir } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { dirname } from 'path';\n\nconst LOG_LEVELS: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3\n};\n\nconst COLORS = {\n debug: '\\x1b[36m', // Cyan\n info: '\\x1b[32m', // Green\n warn: '\\x1b[33m', // Yellow\n error: '\\x1b[31m', // Red\n reset: '\\x1b[0m'\n};\n\n// Sensitive field names to redact\nconst SENSITIVE_KEYS = [\n 'password',\n 'passwd',\n 'secret',\n 'token',\n 'apiKey',\n 'api_key',\n 'apikey',\n 'accessToken',\n 'access_token',\n 'refreshToken',\n 'refresh_token',\n 'privateKey',\n 'private_key',\n 'credential',\n 'credentials',\n 'auth',\n 'authorization'\n];\n\n/**\n * Sanitize object by redacting sensitive fields\n */\nfunction sanitizeObject(obj: any, maxDepth = 5, currentDepth = 0): any {\n // Prevent infinite recursion\n if (currentDepth > maxDepth) {\n return '[Max Depth Reached]';\n }\n\n // Handle null/undefined\n if (obj === null || obj === undefined) {\n return obj;\n }\n\n // Handle primitive types\n if (typeof obj !== 'object') {\n return obj;\n }\n\n // Handle arrays\n if (Array.isArray(obj)) {\n return obj.map(item => sanitizeObject(item, maxDepth, currentDepth + 1));\n }\n\n // Handle objects\n const sanitized: Record<string, any> = {};\n\n for (const [key, value] of Object.entries(obj)) {\n const lowerKey = key.toLowerCase();\n\n // Check if key contains sensitive keywords\n const isSensitive = SENSITIVE_KEYS.some(sensitiveKey =>\n lowerKey.includes(sensitiveKey.toLowerCase())\n );\n\n if (isSensitive) {\n sanitized[key] = '[REDACTED]';\n } else if (value && typeof value === 'object') {\n // Recursively sanitize nested objects\n sanitized[key] = sanitizeObject(value, maxDepth, currentDepth + 1);\n } else {\n sanitized[key] = value;\n }\n }\n\n return sanitized;\n}\n\nexport class SimpleLogger implements Logger {\n private config: LoggerConfig;\n private jsonMode: boolean;\n\n constructor(config: Partial<LoggerConfig> = {}) {\n this.config = {\n level: config.level || 'info',\n console: config.console ?? true,\n file: config.file\n };\n this.jsonMode = false;\n }\n\n /**\n * Enable JSON output mode\n */\n enableJSONMode(): void {\n this.jsonMode = true;\n }\n\n /**\n * Disable JSON output mode\n */\n disableJSONMode(): void {\n this.jsonMode = false;\n }\n\n /**\n * Check if JSON mode is enabled\n */\n isJSONMode(): boolean {\n return this.jsonMode;\n }\n\n debug(message: string, context?: Record<string, unknown>): void {\n this.log('debug', message, context);\n }\n\n info(message: string, context?: Record<string, unknown>): void {\n this.log('info', message, context);\n }\n\n warn(message: string, context?: Record<string, unknown>): void {\n this.log('warn', message, context);\n }\n\n error(message: string, context?: Record<string, unknown>): void {\n this.log('error', message, context);\n }\n\n setLevel(level: LogLevel): void {\n this.config.level = level;\n }\n\n getLevel(): LogLevel {\n return this.config.level;\n }\n\n private log(level: LogLevel, message: string, context?: Record<string, unknown>): void {\n // Check if this log level should be output\n if (LOG_LEVELS[level] < LOG_LEVELS[this.config.level]) {\n return;\n }\n\n // Sanitize context to remove sensitive data\n const sanitizedContext = context ? sanitizeObject(context) : undefined;\n\n const entry: LogEntry = {\n level,\n message,\n timestamp: new Date(),\n context: sanitizedContext\n };\n\n // Console output\n if (this.config.console) {\n this.logToConsole(entry);\n }\n\n // File output\n if (this.config.file) {\n this.logToFile(entry).catch(err => {\n // Silently fail to avoid infinite loop\n if (this.config.console) {\n console.error(`Failed to write to log file: ${err.message}`);\n }\n });\n }\n }\n\n private logToConsole(entry: LogEntry): void {\n // JSON mode - output raw JSON\n if (this.jsonMode) {\n const json = JSON.stringify({\n timestamp: entry.timestamp.toISOString(),\n level: entry.level,\n message: entry.message,\n context: entry.context\n });\n\n if (entry.level === 'error') {\n console.error(json);\n } else {\n console.log(json);\n }\n return;\n }\n\n // Human-readable mode\n const timestamp = entry.timestamp.toISOString();\n const color = COLORS[entry.level];\n const reset = COLORS.reset;\n const levelStr = entry.level.toUpperCase().padEnd(5);\n\n let logMessage = `${color}[${timestamp}] ${levelStr}${reset} ${entry.message}`;\n\n if (entry.context) {\n logMessage += `\\n${JSON.stringify(entry.context, null, 2)}`;\n }\n\n // Output to stderr to avoid polluting stdout (especially for JSON output)\n // This ensures CLI commands can output clean JSON to stdout\n if (entry.level === 'error') {\n console.error(logMessage);\n } else if (entry.level === 'warn') {\n console.warn(logMessage);\n } else {\n // info and debug also go to stderr\n console.error(logMessage);\n }\n }\n\n /**\n * Write log entry to file\n */\n private async logToFile(entry: LogEntry): Promise<void> {\n if (!this.config.file) {\n return;\n }\n\n // Ensure directory exists\n const dir = dirname(this.config.file);\n if (!existsSync(dir)) {\n await mkdir(dir, { recursive: true });\n }\n\n // Format entry as JSON (one line per entry)\n const json = JSON.stringify({\n timestamp: entry.timestamp.toISOString(),\n level: entry.level,\n message: entry.message,\n context: entry.context\n });\n\n // Append to file\n await appendFile(this.config.file, json + '\\n', 'utf-8');\n }\n}\n\n// Default logger instance\nexport const logger = new SimpleLogger();\n\n// Create logger with custom config\nexport function createLogger(config: Partial<LoggerConfig>): Logger {\n return new SimpleLogger(config);\n}\n\n// Set log level on default logger\nexport function setLogLevel(level: LogLevel): void {\n logger.setLevel(level);\n}\n\n// Get current log level\nexport function getLogLevel(): LogLevel {\n return logger.getLevel();\n}\n\n// Re-export LogLevel for convenience\nexport type { LogLevel };\n","/**\n * Performance Tracking Utilities\n *\n * Provides lightweight performance measurement and profiling tools.\n */\n\nexport interface PerformanceMark {\n name: string;\n timestamp: number;\n duration?: number;\n}\n\nexport interface PerformanceMetrics {\n marks: PerformanceMark[];\n totalDuration: number;\n breakdown: Record<string, number>;\n}\n\n/**\n * Performance tracker for profiling application startup and operations\n */\nexport class PerformanceTracker {\n private marks: Map<string, number> = new Map();\n private measurements: PerformanceMark[] = [];\n private startTime: number;\n private enabled: boolean;\n\n constructor(enabled: boolean = false) {\n this.enabled = enabled || process.env.AUTOMATOSX_PROFILE === 'true';\n this.startTime = performance.now();\n }\n\n /**\n * Mark a point in time\n */\n mark(name: string): void {\n if (!this.enabled) return;\n\n const timestamp = performance.now() - this.startTime;\n this.marks.set(name, timestamp);\n }\n\n /**\n * Measure duration between two marks\n */\n measure(name: string, startMark: string, endMark?: string): number | undefined {\n if (!this.enabled) return undefined;\n\n const start = this.marks.get(startMark);\n if (!start) return undefined;\n\n const end = endMark ? this.marks.get(endMark) : performance.now() - this.startTime;\n if (end === undefined) return undefined;\n\n const duration = end - start;\n this.measurements.push({\n name,\n timestamp: start,\n duration\n });\n\n return duration;\n }\n\n /**\n * Get all measurements\n */\n getMeasurements(): PerformanceMark[] {\n return [...this.measurements];\n }\n\n /**\n * Get performance metrics summary\n */\n getMetrics(): PerformanceMetrics {\n const totalDuration = performance.now() - this.startTime;\n const breakdown: Record<string, number> = {};\n\n for (const measurement of this.measurements) {\n if (measurement.duration !== undefined) {\n breakdown[measurement.name] = measurement.duration;\n }\n }\n\n return {\n marks: this.getMeasurements(),\n totalDuration,\n breakdown\n };\n }\n\n /**\n * Generate formatted report\n */\n generateReport(): string {\n const metrics = this.getMetrics();\n const lines: string[] = [];\n\n lines.push('=== Performance Profile ===');\n lines.push(`Total Duration: ${metrics.totalDuration.toFixed(2)}ms`);\n lines.push('');\n lines.push('Breakdown:');\n\n // Sort by duration (descending)\n const sorted = Object.entries(metrics.breakdown)\n .sort(([, a], [, b]) => b - a);\n\n for (const [name, duration] of sorted) {\n const percentage = (duration / metrics.totalDuration * 100).toFixed(1);\n lines.push(` ${name.padEnd(40)} ${duration.toFixed(2)}ms (${percentage}%)`);\n }\n\n return lines.join('\\n');\n }\n\n /**\n * Clear all measurements\n */\n clear(): void {\n this.marks.clear();\n this.measurements = [];\n this.startTime = performance.now();\n }\n\n /**\n * Check if profiling is enabled\n */\n isEnabled(): boolean {\n return this.enabled;\n }\n}\n\n/**\n * Global performance tracker instance\n */\nexport const globalTracker = new PerformanceTracker(\n process.env.AUTOMATOSX_PROFILE === 'true'\n);\n\n/**\n * Measure async function execution time\n */\nexport async function measureAsync<T>(\n name: string,\n fn: () => Promise<T>\n): Promise<T> {\n if (!globalTracker.isEnabled()) {\n return fn();\n }\n\n const startMark = `${name}_start`;\n const endMark = `${name}_end`;\n\n globalTracker.mark(startMark);\n try {\n const result = await fn();\n globalTracker.mark(endMark);\n globalTracker.measure(name, startMark, endMark);\n return result;\n } catch (error) {\n globalTracker.mark(endMark);\n globalTracker.measure(`${name}_error`, startMark, endMark);\n throw error;\n }\n}\n\n/**\n * Measure sync function execution time\n */\nexport function measureSync<T>(\n name: string,\n fn: () => T\n): T {\n if (!globalTracker.isEnabled()) {\n return fn();\n }\n\n const startMark = `${name}_start`;\n const endMark = `${name}_end`;\n\n globalTracker.mark(startMark);\n try {\n const result = fn();\n globalTracker.mark(endMark);\n globalTracker.measure(name, startMark, endMark);\n return result;\n } catch (error) {\n globalTracker.mark(endMark);\n globalTracker.measure(`${name}_error`, startMark, endMark);\n throw error;\n }\n}\n","/**\n * Config Command - Manage AutomatosX configuration\n */\n\nimport type { CommandModule } from 'yargs';\nimport { access } from 'fs/promises';\nimport { resolve } from 'path';\nimport { constants } from 'fs';\nimport chalk from 'chalk';\nimport { DEFAULT_CONFIG } from '../../types/config.js';\nimport type { AutomatosXConfig } from '../../types/config.js';\nimport { logger } from '../../utils/logger.js';\nimport { printError } from '../../utils/error-formatter.js';\nimport { printSuccess, formatInfo, formatKeyValue, formatWarning } from '../../utils/message-formatter.js';\nimport { validateConfig, formatValidationErrors } from '../../utils/config-validator.js';\nimport { loadConfigFile, saveConfigFile } from '../../core/config.js';\n\ninterface ConfigOptions {\n get?: string;\n set?: string;\n value?: string;\n list?: boolean;\n reset?: boolean;\n validate?: boolean;\n verbose?: boolean;\n}\n\nexport const configCommand: CommandModule<Record<string, unknown>, ConfigOptions> = {\n command: 'config',\n describe: 'Manage AutomatosX configuration',\n\n builder: (yargs) => {\n return yargs\n .option('get', {\n alias: 'g',\n describe: 'Get configuration value',\n type: 'string'\n })\n .option('set', {\n alias: 's',\n describe: 'Set configuration key',\n type: 'string'\n })\n .option('value', {\n describe: 'Value to set',\n type: 'string'\n })\n .option('list', {\n alias: 'l',\n describe: 'List all configuration',\n type: 'boolean',\n default: false\n })\n .option('reset', {\n alias: 'r',\n describe: 'Reset to default configuration',\n type: 'boolean',\n default: false\n })\n .option('validate', {\n describe: 'Validate configuration',\n type: 'boolean',\n default: false\n })\n .option('verbose', {\n describe: 'Show detailed output',\n type: 'boolean',\n default: false\n })\n .example('$0 config --list', 'List all configuration')\n .example('$0 config --get logging.level', 'Get log level')\n .example('$0 config --set logging.level --value debug', 'Set log level to debug')\n .example('$0 config --validate', 'Validate configuration')\n .example('$0 config --reset', 'Reset to default configuration');\n },\n\n handler: async (argv) => {\n try {\n // Debug: Print received arguments (only in debug mode)\n if (process.env.AUTOMATOSX_DEBUG) {\n console.error('[DEBUG] Config handler argv:', {\n config: (argv as any).config,\n c: (argv as any).c,\n all: Object.keys(argv)\n });\n }\n\n // Support multiple config path sources (priority order)\n let configPath: string;\n\n if ((argv as any).config) {\n configPath = (argv as any).config;\n } else if ((argv as any).c) {\n configPath = (argv as any).c;\n } else if (process.env.AUTOMATOSX_CONFIG) {\n configPath = process.env.AUTOMATOSX_CONFIG;\n } else {\n // Check in priority order: project root config, then hidden dir config\n const projectConfig = resolve(process.cwd(), 'automatosx.config.json');\n const hiddenConfig = resolve(process.cwd(), '.automatosx', 'config.json');\n\n const fs = await import('fs');\n if (fs.existsSync(projectConfig)) {\n configPath = projectConfig;\n } else if (fs.existsSync(hiddenConfig)) {\n configPath = hiddenConfig;\n } else {\n // Default to project config (for error message)\n configPath = projectConfig;\n }\n }\n\n if (process.env.AUTOMATOSX_DEBUG) {\n console.error('[DEBUG] Resolved config path:', configPath);\n }\n\n // Check if config exists\n const exists = await checkExists(configPath);\n if (!exists) {\n console.log(chalk.yellow('⚠️ Configuration file not found'));\n console.log(chalk.gray(` Searched at: ${configPath}`));\n console.log(chalk.gray(' Run \"automatosx init\" to create configuration\\n'));\n process.exit(1);\n }\n\n // Load config (supports both YAML and JSON)\n const config = await loadConfigFile(configPath);\n\n // Handle operations\n if (argv.reset) {\n await resetConfig(configPath, argv.verbose || false);\n } else if (argv.validate) {\n await validateConfigFile(config, argv.verbose || false);\n } else if (argv.list) {\n await listConfig(config, argv.verbose || false);\n } else if (argv.get) {\n await getConfig(config, argv.get, argv.verbose || false);\n } else if (argv.set && argv.value !== undefined) {\n await setConfig(configPath, config, argv.set, argv.value, argv.verbose || false);\n } else if (argv.set && argv.value === undefined) {\n console.log(chalk.red('❌ Error: --value is required when using --set\\n'));\n process.exit(1);\n } else {\n // Default: show config path\n console.log(formatInfo('Configuration file:'));\n console.log(chalk.gray(` ${configPath}\\n`));\n }\n\n } catch (error) {\n printError(error, {\n verbose: argv.verbose || false,\n showCode: true,\n showSuggestions: true,\n colors: true\n });\n logger.error('Config command failed', { error: (error as Error).message });\n process.exit(1);\n }\n }\n};\n\n/**\n * Check if file exists\n */\nasync function checkExists(path: string): Promise<boolean> {\n try {\n await access(path, constants.F_OK);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Validate configuration file\n */\nasync function validateConfigFile(\n config: AutomatosXConfig,\n verbose: boolean\n): Promise<void> {\n console.log(chalk.cyan('\\n🔍 Validating configuration...\\n'));\n\n const result = validateConfig(config);\n\n if (result.valid) {\n printSuccess('Configuration is valid');\n\n if (verbose) {\n console.log(chalk.gray('\\nValidation checks passed:'));\n console.log(chalk.gray(' ✓ All required fields present'));\n console.log(chalk.gray(' ✓ All field types correct'));\n console.log(chalk.gray(' ✓ All values within valid ranges'));\n console.log(chalk.gray(' ✓ At least one provider enabled'));\n }\n } else {\n console.log(formatWarning(`Found ${result.errors.length} validation error(s)\\n`));\n console.log(formatValidationErrors(result.errors));\n console.log();\n\n logger.warn('Configuration validation failed', {\n errorCount: result.errors.length,\n errors: result.errors\n });\n\n process.exit(1);\n }\n\n console.log();\n}\n\n/**\n * Reset configuration to defaults\n */\nasync function resetConfig(path: string, verbose: boolean): Promise<void> {\n const config = {\n ...DEFAULT_CONFIG,\n $schema: './schema/config.json',\n version: '5.0.0' // v5.0+ with YAML support\n };\n\n await saveConfigFile(path, config);\n printSuccess('Configuration reset to defaults');\n\n if (verbose) {\n console.log(chalk.gray(`\\nConfig file: ${path}\\n`));\n }\n\n logger.info('Configuration reset', { path });\n}\n\n/**\n * List all configuration\n */\nasync function listConfig(config: AutomatosXConfig, verbose: boolean): Promise<void> {\n console.log(chalk.bold.cyan('\\n📋 AutomatosX Configuration\\n'));\n\n // Providers Section\n console.log(chalk.bold.white('┌─────────────────────────────────────────────────────'));\n console.log(chalk.bold.white('│ ') + chalk.bold.cyan('Providers'));\n console.log(chalk.bold.white('└─────────────────────────────────────────────────────\\n'));\n\n // Provider table\n const providers = Object.entries(config.providers);\n const maxNameLength = Math.max(...providers.map(([name]) => name.length));\n\n providers.forEach(([name, provider]) => {\n const status = provider.enabled ? chalk.green('✓ Enabled ') : chalk.gray('✗ Disabled');\n const paddedName = name.padEnd(maxNameLength + 2);\n console.log(` ${chalk.bold(paddedName)} ${status}`);\n\n if (verbose) {\n console.log(chalk.gray(` │ Priority: ${provider.priority.toString().padStart(2)} │ Timeout: ${provider.timeout}ms`));\n console.log(chalk.gray(` │ Command: ${provider.command}`));\n console.log(chalk.gray(' └─────────────────────────────────────────────────'));\n }\n });\n\n // Memory Section\n console.log(chalk.bold.white('\\n┌─────────────────────────────────────────────────────'));\n console.log(chalk.bold.white('│ ') + chalk.bold.cyan('Memory'));\n console.log(chalk.bold.white('└─────────────────────────────────────────────────────\\n'));\n\n console.log(formatKeyValue(' Max Entries ', chalk.yellow(config.memory.maxEntries.toString())));\n console.log(formatKeyValue(' Persist Path ', chalk.blue(config.memory.persistPath)));\n\n if (verbose) {\n console.log(formatKeyValue(' Auto Cleanup ', config.memory.autoCleanup ? chalk.green('✓ Enabled') : chalk.gray('✗ Disabled')));\n console.log(formatKeyValue(' Cleanup Days ', chalk.yellow(config.memory.cleanupDays.toString())));\n }\n\n // Workspace Section\n console.log(chalk.bold.white('\\n┌─────────────────────────────────────────────────────'));\n console.log(chalk.bold.white('│ ') + chalk.bold.cyan('Workspace'));\n console.log(chalk.bold.white('└─────────────────────────────────────────────────────\\n'));\n\n console.log(formatKeyValue(' Base Path ', chalk.blue(config.workspace.basePath)));\n console.log(formatKeyValue(' Auto Cleanup ', config.workspace.autoCleanup ? chalk.green('✓ Enabled') : chalk.gray('✗ Disabled')));\n\n if (verbose) {\n console.log(formatKeyValue(' Cleanup Days ', chalk.yellow(config.workspace.cleanupDays.toString())));\n console.log(formatKeyValue(' Max Files ', chalk.yellow(config.workspace.maxFiles.toString())));\n }\n\n // Logging Section\n console.log(chalk.bold.white('\\n┌─────────────────────────────────────────────────────'));\n console.log(chalk.bold.white('│ ') + chalk.bold.cyan('Logging'));\n console.log(chalk.bold.white('└─────────────────────────────────────────────────────\\n'));\n\n const levelColor = getLevelColor(config.logging.level);\n console.log(formatKeyValue(' Level ', levelColor(config.logging.level)));\n console.log(formatKeyValue(' Path ', chalk.blue(config.logging.path)));\n\n if (verbose) {\n console.log(formatKeyValue(' Console ', config.logging.console ? chalk.green('✓ Enabled') : chalk.gray('✗ Disabled')));\n }\n\n console.log();\n}\n\n/**\n * Get color for log level\n */\nfunction getLevelColor(level: string): (text: string) => string {\n switch (level) {\n case 'debug':\n return chalk.magenta;\n case 'info':\n return chalk.cyan;\n case 'warn':\n return chalk.yellow;\n case 'error':\n return chalk.red;\n default:\n return chalk.white;\n }\n}\n\n/**\n * Get configuration value\n */\nasync function getConfig(\n config: AutomatosXConfig,\n key: string,\n verbose: boolean\n): Promise<void> {\n const value = getNestedValue(config, key);\n\n if (value === undefined) {\n console.log(chalk.yellow(`⚠️ Configuration key not found: ${key}\\n`));\n process.exit(1);\n }\n\n if (verbose) {\n console.log(formatKeyValue(key, typeof value === 'object' ? JSON.stringify(value, null, 2) : String(value)));\n } else {\n if (typeof value === 'object') {\n console.log(JSON.stringify(value, null, 2));\n } else {\n console.log(value);\n }\n }\n}\n\n/**\n * Set configuration value\n */\nasync function setConfig(\n path: string,\n config: AutomatosXConfig,\n key: string,\n value: string,\n verbose: boolean\n): Promise<void> {\n // Parse value (try JSON first, then use as string)\n let parsedValue: any = value;\n try {\n parsedValue = JSON.parse(value);\n } catch {\n // Use as string if not valid JSON\n }\n\n // Set nested value\n const updated = setNestedValue(config, key, parsedValue);\n\n if (!updated) {\n console.log(chalk.yellow(`⚠️ Configuration key not found: ${key}\\n`));\n process.exit(1);\n }\n\n // Validate updated config\n const validationResult = validateConfig(config);\n if (!validationResult.valid) {\n console.log(chalk.red('\\n❌ Validation failed after update:\\n'));\n console.log(formatValidationErrors(validationResult.errors));\n console.log();\n process.exit(1);\n }\n\n // Save config (supports both YAML and JSON)\n await saveConfigFile(path, config);\n printSuccess(`Configuration updated: ${key} = ${value}`);\n\n if (verbose) {\n console.log(chalk.gray(`\\nConfig file: ${path}`));\n console.log(chalk.gray('Configuration validated successfully\\n'));\n }\n\n logger.info('Configuration updated', { key, value });\n}\n\n/**\n * Get nested object value by dot notation\n */\nfunction getNestedValue(obj: any, path: string): any {\n return path.split('.').reduce((current, key) => current?.[key], obj);\n}\n\n/**\n * Set nested object value by dot notation\n */\nfunction setNestedValue(obj: any, path: string, value: any): boolean {\n const keys = path.split('.');\n const lastKey = keys.pop();\n\n if (!lastKey) return false;\n\n const target = keys.reduce((current, key) => {\n if (current?.[key] === undefined) return undefined;\n return current[key];\n }, obj);\n\n if (target === undefined) return false;\n\n target[lastKey] = value;\n return true;\n}\n","/**\n * Configuration types for AutomatosX v5.0+\n *\n * Complete configuration system with YAML support.\n * All hardcoded values moved to configuration.\n */\n\nimport type { LogLevel } from './logger.js';\n\n// ========================================\n// Provider Configuration\n// ========================================\n\nexport interface ProviderHealthCheckConfig {\n enabled: boolean;\n interval: number; // milliseconds\n timeout: number; // milliseconds\n}\n\n/**\n * Provider default model parameters (v5.0+)\n */\nexport interface ProviderDefaultsConfig {\n maxTokens?: number; // Default max output tokens\n temperature?: number; // Default temperature (0-1)\n topP?: number; // Default top_p (0-1)\n}\n\nexport interface ProviderConfig {\n enabled: boolean;\n priority: number;\n timeout: number;\n command: string;\n healthCheck?: ProviderHealthCheckConfig;\n defaults?: ProviderDefaultsConfig; // v5.0: Default model parameters\n}\n\n// ========================================\n// Execution Configuration\n// ========================================\n\nexport interface RetryConfig {\n maxAttempts: number;\n initialDelay: number; // milliseconds\n maxDelay: number; // milliseconds\n backoffFactor: number; // exponential backoff multiplier\n retryableErrors?: string[]; // error codes/messages that trigger retry (optional, has defaults)\n}\n\nexport interface ExecutionProviderConfig {\n maxWaitMs: number; // max wait time for provider response\n fallbackDelay?: number; // v5.0: delay before trying fallback provider (ms)\n}\n\nexport interface ExecutionConfig {\n defaultTimeout: number; // default execution timeout (ms)\n retry: RetryConfig;\n provider: ExecutionProviderConfig;\n}\n\n// ========================================\n// Orchestration Configuration\n// ========================================\n\nexport interface SessionConfig {\n maxSessions: number; // max sessions in memory\n maxMetadataSize: number; // max metadata size (bytes)\n saveDebounce: number; // save debounce delay (ms)\n cleanupAfterDays: number; // cleanup old sessions after N days\n maxUuidAttempts: number; // max UUID generation attempts\n persistPath: string; // session persistence path\n}\n\nexport interface DelegationConfig {\n maxDepth: number; // max delegation chain depth\n timeout: number; // delegation timeout (ms)\n enableCycleDetection: boolean;\n}\n\nexport interface WorkspaceSystemConfig {\n maxFileSize: number; // max file size (bytes)\n maxFiles: number; // max files per workspace\n cleanupAfterDays: number; // cleanup old workspaces after N days\n autoCleanup: boolean;\n permissions: number; // Unix permissions (e.g., 0o700)\n basePath: string;\n}\n\nexport interface OrchestrationConfigSystem {\n session: SessionConfig;\n delegation: DelegationConfig;\n workspace: WorkspaceSystemConfig;\n}\n\n// ========================================\n// Memory Configuration\n// ========================================\n\nexport interface MemorySearchConfig {\n defaultLimit: number; // default search result limit\n maxLimit: number; // max search result limit\n timeout: number; // search timeout (ms)\n}\n\nexport interface MemoryConfig {\n maxEntries: number;\n persistPath: string;\n autoCleanup: boolean;\n cleanupDays: number;\n search?: MemorySearchConfig; // Optional for backward compatibility\n}\n\n// ========================================\n// Abilities Configuration\n// ========================================\n\nexport interface AbilitiesCacheConfig {\n enabled: boolean;\n maxEntries: number;\n ttl: number; // time to live (ms)\n maxSize: number; // max cache size (bytes)\n cleanupInterval: number; // cleanup interval (ms)\n}\n\nexport interface AbilitiesLimitsConfig {\n maxFileSize: number; // max ability file size (bytes)\n}\n\nexport interface AbilitiesConfig {\n basePath: string;\n fallbackPath: string;\n cache: AbilitiesCacheConfig;\n limits: AbilitiesLimitsConfig;\n}\n\n// ========================================\n// Logging Configuration\n// ========================================\n\nexport interface LoggingRetentionConfig {\n maxSizeBytes: number;\n maxAgeDays: number;\n compress: boolean;\n}\n\nexport interface LoggingConfig {\n level: LogLevel;\n path: string;\n console: boolean;\n retention?: LoggingRetentionConfig; // Optional for backward compatibility\n}\n\n// ========================================\n// Performance Configuration\n// ========================================\n\nexport interface CacheConfig {\n enabled: boolean;\n maxEntries: number;\n ttl: number; // time to live (ms)\n cleanupInterval: number; // cleanup interval (ms)\n}\n\nexport interface ProfileCacheConfig extends CacheConfig {}\n\nexport interface TeamCacheConfig extends CacheConfig {}\n\nexport interface ProviderCacheConfig extends CacheConfig {}\n\nexport interface RateLimitConfig {\n enabled: boolean;\n requestsPerMinute: number;\n burstSize: number;\n}\n\nexport interface PerformanceConfig {\n profileCache: ProfileCacheConfig;\n teamCache: TeamCacheConfig;\n providerCache: ProviderCacheConfig;\n rateLimit: RateLimitConfig;\n}\n\n// ========================================\n// Advanced Configuration\n// ========================================\n\nexport interface EmbeddingConfig {\n timeout: number;\n retryDelay: number;\n dimensions: number;\n maxRetries: number;\n}\n\nexport interface SecurityConfig {\n enablePathValidation: boolean;\n allowedExtensions: string[];\n}\n\nexport interface DevelopmentConfig {\n mockProviders: boolean;\n profileMode: boolean;\n}\n\nexport interface AdvancedConfig {\n embedding?: EmbeddingConfig;\n security: SecurityConfig;\n development: DevelopmentConfig;\n}\n\n// ========================================\n// Integration Configuration (v5.5+ VS Code)\n// ========================================\n\nexport interface VSCodeIntegrationConfig {\n enabled: boolean;\n apiPort: number;\n autoStart: boolean;\n outputPanel: boolean;\n notifications: boolean;\n}\n\nexport interface IntegrationConfig {\n vscode: VSCodeIntegrationConfig;\n}\n\n// ========================================\n// CLI Configuration (Optional)\n// ========================================\n\nexport interface CLIRunConfig {\n defaultMemory: boolean;\n defaultSaveMemory: boolean;\n defaultFormat: 'text' | 'json' | 'markdown';\n defaultVerbose: boolean;\n}\n\nexport interface CLISessionConfig {\n defaultShowAgents: boolean;\n}\n\nexport interface CLIMemoryConfig {\n defaultLimit: number;\n}\n\nexport interface CLIConfig {\n run: CLIRunConfig;\n session: CLISessionConfig;\n memory: CLIMemoryConfig;\n}\n\n// ========================================\n// Legacy (for backward compatibility)\n// ========================================\n\nexport interface WorkspaceConfig {\n basePath: string;\n autoCleanup: boolean;\n cleanupDays: number;\n maxFiles: number;\n}\n\nexport interface OpenAIConfig {\n apiKey?: string;\n model?: string;\n}\n\n// ========================================\n// Main Configuration\n// ========================================\n\nexport interface AutomatosXConfig {\n $schema?: string;\n version?: string;\n providers: Record<string, ProviderConfig>;\n execution?: ExecutionConfig;\n orchestration?: OrchestrationConfigSystem;\n memory: MemoryConfig;\n abilities?: AbilitiesConfig;\n workspace: WorkspaceConfig; // legacy, kept for backward compatibility\n logging: LoggingConfig;\n performance?: PerformanceConfig;\n advanced?: AdvancedConfig;\n integration?: IntegrationConfig;\n cli?: CLIConfig;\n openai?: OpenAIConfig; // legacy\n}\n\n// ========================================\n// Default Configuration\n// ========================================\n\nexport const DEFAULT_CONFIG: AutomatosXConfig = {\n providers: {\n 'claude-code': {\n enabled: true,\n priority: 3,\n timeout: 1500000, // 25 minutes (v5.0.13: increased from 15 min based on user feedback)\n command: 'claude',\n healthCheck: {\n enabled: true,\n interval: 300000, // 5 minutes (v5.0: reduced frequency from 1 min)\n timeout: 5000 // 5 seconds\n }\n // v5.0.5: Removed defaults - let provider CLI use optimal defaults\n // Users can still set provider.defaults in config for specific needs\n },\n 'gemini-cli': {\n enabled: true,\n priority: 2,\n timeout: 1500000, // 25 minutes (v5.0.13: increased from 15 min based on user feedback)\n command: 'gemini',\n healthCheck: {\n enabled: true,\n interval: 300000, // 5 minutes (v5.0: reduced frequency)\n timeout: 5000\n }\n // v5.0.5: Removed defaults - let provider CLI use optimal defaults\n },\n 'openai': {\n enabled: true,\n priority: 1,\n timeout: 1500000, // 25 minutes (v5.0.13: increased from 15 min based on user feedback)\n command: 'codex',\n healthCheck: {\n enabled: true,\n interval: 300000, // 5 minutes (v5.0: reduced frequency)\n timeout: 5000\n }\n // v5.0.5: Removed defaults - let provider CLI use optimal defaults\n }\n },\n\n execution: {\n defaultTimeout: 1500000, // 25 minutes (v5.0.13: increased from 15 min based on user feedback)\n retry: {\n maxAttempts: 3,\n initialDelay: 1000, // 1 second\n maxDelay: 10000, // 10 seconds\n backoffFactor: 2,\n retryableErrors: [\n 'ECONNREFUSED',\n 'ETIMEDOUT',\n 'ENOTFOUND',\n 'rate_limit',\n 'overloaded',\n 'timeout'\n ]\n },\n provider: {\n maxWaitMs: 60000, // 1 minute\n fallbackDelay: 5000 // v5.0: Wait 5s before trying fallback provider\n }\n },\n\n orchestration: {\n session: {\n maxSessions: 100,\n maxMetadataSize: 10240, // 10 KB\n saveDebounce: 1000, // 1 second (v5.0: increased from 100ms to reduce I/O)\n cleanupAfterDays: 7,\n maxUuidAttempts: 100,\n persistPath: '.automatosx/sessions'\n },\n delegation: {\n maxDepth: 2,\n timeout: 1500000, // 25 minutes (v5.0.13: increased from 15 min based on user feedback)\n enableCycleDetection: true\n },\n workspace: {\n maxFileSize: 10485760, // 10 MB\n maxFiles: 100,\n cleanupAfterDays: 7,\n autoCleanup: true,\n permissions: 0o700,\n basePath: '.automatosx/workspaces'\n }\n },\n\n memory: {\n maxEntries: 10000,\n persistPath: '.automatosx/memory',\n autoCleanup: true,\n cleanupDays: 30,\n search: {\n defaultLimit: 10,\n maxLimit: 100,\n timeout: 5000 // 5 seconds\n }\n },\n\n abilities: {\n basePath: '.automatosx/abilities',\n fallbackPath: 'examples/abilities',\n cache: {\n enabled: true,\n maxEntries: 50,\n ttl: 600000, // 10 minutes\n maxSize: 5242880, // 5 MB\n cleanupInterval: 120000 // 2 minutes\n },\n limits: {\n maxFileSize: 524288 // 500 KB\n }\n },\n\n workspace: {\n basePath: '.automatosx/workspaces',\n autoCleanup: true,\n cleanupDays: 7,\n maxFiles: 100\n },\n\n logging: {\n level: 'info',\n path: '.automatosx/logs',\n console: true,\n retention: {\n maxSizeBytes: 104857600, // 100 MB\n maxAgeDays: 30,\n compress: true\n }\n },\n\n performance: {\n profileCache: {\n enabled: true,\n maxEntries: 20,\n ttl: 600000, // 10 minutes (v5.0: standardized from 5 min)\n cleanupInterval: 120000 // 2 minutes (v5.0: standardized)\n },\n teamCache: {\n enabled: true,\n maxEntries: 10,\n ttl: 600000, // 10 minutes\n cleanupInterval: 120000 // 2 minutes\n },\n providerCache: {\n enabled: true, // v5.0: enabled by default (safe for deterministic responses)\n maxEntries: 100,\n ttl: 600000, // 10 minutes (v5.0: reduced from 1 hour)\n cleanupInterval: 120000 // 2 minutes (v5.0: standardized)\n },\n rateLimit: {\n enabled: false, // Keep disabled by default (opt-in)\n requestsPerMinute: 60,\n burstSize: 10\n }\n },\n\n advanced: {\n embedding: {\n timeout: 30000,\n retryDelay: 1000,\n dimensions: 1536,\n maxRetries: 3\n },\n security: {\n enablePathValidation: true,\n allowedExtensions: [\n '.ts', '.js', '.tsx', '.jsx',\n '.py', '.go', '.rs', '.java',\n '.yaml', '.yml', '.json', '.toml',\n '.md', '.txt', '.csv'\n ]\n },\n development: {\n mockProviders: false,\n profileMode: false\n }\n },\n\n integration: {\n vscode: {\n enabled: false, // v5.5+ will enable\n apiPort: 3000,\n autoStart: true,\n outputPanel: true,\n notifications: true\n }\n },\n\n cli: {\n run: {\n defaultMemory: true,\n defaultSaveMemory: true,\n defaultFormat: 'text',\n defaultVerbose: false\n },\n session: {\n defaultShowAgents: true\n },\n memory: {\n defaultLimit: 10\n }\n }\n};\n","/**\n * Error Formatter - Format errors for CLI display\n *\n * Provides consistent, user-friendly error formatting with:\n * - Color-coded output\n * - Error code display\n * - Actionable suggestions\n * - Context information (in debug mode)\n */\n\nimport chalk from 'chalk';\nimport type { BaseError } from './errors.js';\nimport { toBaseError } from './errors.js';\n\nexport interface FormatOptions {\n /**\n * Show verbose error details (stack trace, context)\n */\n verbose?: boolean;\n\n /**\n * Show error code\n */\n showCode?: boolean;\n\n /**\n * Show suggestions\n */\n showSuggestions?: boolean;\n\n /**\n * Use colors in output\n */\n colors?: boolean;\n}\n\n/**\n * Format error for CLI display\n */\nexport function formatError(error: unknown, options: FormatOptions = {}): string {\n const {\n verbose = false,\n showCode = true,\n showSuggestions = true,\n colors = true\n } = options;\n\n const baseError = toBaseError(error);\n const lines: string[] = [];\n\n // Header\n const header = colors\n ? chalk.red.bold('\\n❌ Error')\n : '\\n✗ Error';\n lines.push(header);\n\n // Error code\n if (showCode) {\n const codeText = colors\n ? chalk.gray(`[${baseError.code}]`)\n : `[${baseError.code}]`;\n lines.push(codeText);\n }\n\n // Error message\n const message = colors\n ? chalk.red(baseError.message)\n : baseError.message;\n lines.push('\\n' + message);\n\n // Suggestions\n if (showSuggestions && baseError.suggestions.length > 0) {\n lines.push('');\n const suggestionsHeader = colors\n ? chalk.cyan('💡 Suggestions:')\n : 'Suggestions:';\n lines.push(suggestionsHeader);\n\n baseError.suggestions.forEach((suggestion, i) => {\n const bullet = colors\n ? chalk.gray(` ${i + 1}.`)\n : ` ${i + 1}.`;\n lines.push(`${bullet} ${suggestion}`);\n });\n }\n\n // Context (verbose mode)\n if (verbose && baseError.context) {\n lines.push('');\n const contextHeader = colors\n ? chalk.gray('📋 Context:')\n : 'Context:';\n lines.push(contextHeader);\n\n const contextStr = JSON.stringify(baseError.context, null, 2);\n const formatted = colors\n ? chalk.gray(contextStr.split('\\n').map(line => ' ' + line).join('\\n'))\n : contextStr.split('\\n').map(line => ' ' + line).join('\\n');\n lines.push(formatted);\n }\n\n // Stack trace (verbose mode)\n if (verbose && baseError.stack) {\n lines.push('');\n const stackHeader = colors\n ? chalk.gray('🔍 Stack Trace:')\n : 'Stack Trace:';\n lines.push(stackHeader);\n\n const stack = baseError.stack.split('\\n').slice(1); // Skip first line (message)\n const formatted = colors\n ? chalk.gray(stack.map(line => ' ' + line).join('\\n'))\n : stack.map(line => ' ' + line).join('\\n');\n lines.push(formatted);\n }\n\n // Footer\n lines.push('');\n\n return lines.join('\\n');\n}\n\n/**\n * Format error for JSON output\n */\nexport function formatErrorJSON(error: unknown): string {\n const baseError = toBaseError(error);\n return JSON.stringify(baseError.toJSON(), null, 2);\n}\n\n/**\n * Format error summary (one line)\n */\nexport function formatErrorSummary(error: unknown, options: FormatOptions = {}): string {\n const { colors = true } = options;\n const baseError = toBaseError(error);\n\n const code = colors\n ? chalk.gray(`[${baseError.code}]`)\n : `[${baseError.code}]`;\n\n const message = colors\n ? chalk.red(baseError.message)\n : baseError.message;\n\n return `${code} ${message}`;\n}\n\n/**\n * Format multiple errors as a list\n */\nexport function formatErrorList(errors: unknown[], options: FormatOptions = {}): string {\n const { colors = true } = options;\n const lines: string[] = [];\n\n const header = colors\n ? chalk.red.bold(`\\n❌ ${errors.length} Error(s) Occurred\\n`)\n : `\\n✗ ${errors.length} Error(s) Occurred\\n`;\n lines.push(header);\n\n errors.forEach((error, i) => {\n const baseError = toBaseError(error);\n const num = colors\n ? chalk.gray(`${i + 1}.`)\n : `${i + 1}.`;\n const summary = formatErrorSummary(baseError, { colors });\n lines.push(`${num} ${summary}`);\n });\n\n lines.push('');\n return lines.join('\\n');\n}\n\n/**\n * Print error to console\n */\nexport function printError(error: unknown, options: FormatOptions = {}): void {\n const formatted = formatError(error, options);\n console.error(formatted);\n}\n\n/**\n * Print error summary to console\n */\nexport function printErrorSummary(error: unknown, options: FormatOptions = {}): void {\n const formatted = formatErrorSummary(error, options);\n console.error(formatted);\n}\n\n/**\n * Print multiple errors to console\n */\nexport function printErrorList(errors: unknown[], options: FormatOptions = {}): void {\n const formatted = formatErrorList(errors, options);\n console.error(formatted);\n}\n","/**\n * Error Hierarchy - Structured error classes with error codes\n *\n * All errors extend BaseError with:\n * - Error code (for programmatic handling)\n * - User-friendly message\n * - Actionable suggestions\n * - Additional context\n */\n\nexport enum ErrorCode {\n // Configuration Errors (1000-1099)\n CONFIG_NOT_FOUND = 'E1000',\n CONFIG_INVALID = 'E1001',\n CONFIG_PARSE_ERROR = 'E1002',\n CONFIG_VALIDATION_ERROR = 'E1003',\n\n // Path Errors (1100-1199)\n PATH_TRAVERSAL = 'E1100',\n PATH_NOT_FOUND = 'E1101',\n PATH_ACCESS_DENIED = 'E1102',\n PATH_INVALID = 'E1103',\n\n // Memory Errors (1200-1299)\n MEMORY_NOT_INITIALIZED = 'E1200',\n MEMORY_DATABASE_ERROR = 'E1201',\n MEMORY_EMBEDDING_ERROR = 'E1202',\n MEMORY_QUERY_ERROR = 'E1203',\n MEMORY_IMPORT_ERROR = 'E1204',\n MEMORY_EXPORT_ERROR = 'E1205',\n\n // Provider Errors (1300-1399)\n PROVIDER_NOT_FOUND = 'E1300',\n PROVIDER_UNAVAILABLE = 'E1301',\n PROVIDER_TIMEOUT = 'E1302',\n PROVIDER_RATE_LIMIT = 'E1303',\n PROVIDER_AUTH_ERROR = 'E1304',\n PROVIDER_EXEC_ERROR = 'E1305',\n PROVIDER_NO_AVAILABLE = 'E1306',\n\n // Agent Errors (1400-1499)\n AGENT_PROFILE_NOT_FOUND = 'E1400',\n AGENT_PROFILE_INVALID = 'E1401',\n AGENT_ABILITY_NOT_FOUND = 'E1402',\n AGENT_EXECUTION_ERROR = 'E1403',\n AGENT_CONTEXT_ERROR = 'E1404',\n\n // Validation Errors (1500-1599)\n VALIDATION_FAILED = 'E1500',\n VALIDATION_SCHEMA_ERROR = 'E1501',\n VALIDATION_TYPE_ERROR = 'E1502',\n VALIDATION_CONSTRAINT_ERROR = 'E1503',\n\n // File System Errors (1600-1699)\n FILE_NOT_FOUND = 'E1600',\n FILE_READ_ERROR = 'E1601',\n FILE_WRITE_ERROR = 'E1602',\n FILE_PERMISSION_ERROR = 'E1603',\n\n // CLI Errors (1700-1799)\n CLI_INVALID_COMMAND = 'E1700',\n CLI_INVALID_ARGUMENT = 'E1701',\n CLI_MISSING_ARGUMENT = 'E1702',\n CLI_UNKNOWN_ERROR = 'E1703',\n\n // Unknown/Generic (9999)\n UNKNOWN_ERROR = 'E9999'\n}\n\n/**\n * Base error class with error code and suggestions\n */\nexport class BaseError extends Error {\n public readonly code: ErrorCode;\n public readonly suggestions: string[];\n public readonly context?: Record<string, unknown>;\n public readonly isOperational: boolean;\n\n constructor(\n message: string,\n code: ErrorCode,\n suggestions: string[] = [],\n context?: Record<string, unknown>,\n isOperational: boolean = true\n ) {\n super(message);\n this.name = this.constructor.name;\n this.code = code;\n this.suggestions = suggestions;\n this.context = context;\n this.isOperational = isOperational;\n\n // Maintains proper stack trace\n Error.captureStackTrace(this, this.constructor);\n }\n\n /**\n * Get formatted error message for display\n */\n getFormattedMessage(): string {\n let formatted = `[${this.code}] ${this.message}`;\n\n if (this.suggestions.length > 0) {\n formatted += '\\n\\nSuggestions:';\n this.suggestions.forEach((suggestion, i) => {\n formatted += `\\n ${i + 1}. ${suggestion}`;\n });\n }\n\n return formatted;\n }\n\n /**\n * Get error details as object\n */\n toJSON(): Record<string, unknown> {\n return {\n name: this.name,\n code: this.code,\n message: this.message,\n suggestions: this.suggestions,\n context: this.context,\n isOperational: this.isOperational,\n stack: this.stack\n };\n }\n}\n\n/**\n * Configuration Errors\n */\nexport class ConfigError extends BaseError {\n constructor(\n message: string,\n code: ErrorCode = ErrorCode.CONFIG_INVALID,\n suggestions: string[] = [],\n context?: Record<string, unknown>\n ) {\n super(message, code, suggestions, context);\n }\n\n static notFound(path: string): ConfigError {\n return new ConfigError(\n `Configuration file not found: ${path}`,\n ErrorCode.CONFIG_NOT_FOUND,\n [\n 'Run \"automatosx init\" to create a new configuration',\n 'Specify a custom config path with --config option',\n 'Check that you are in a valid AutomatosX project directory'\n ],\n { path }\n );\n }\n\n static invalid(reason: string, context?: Record<string, unknown>): ConfigError {\n return new ConfigError(\n `Invalid configuration: ${reason}`,\n ErrorCode.CONFIG_INVALID,\n [\n 'Check your automatosx.config.json for syntax errors',\n 'Validate against the schema in documentation',\n 'Reset to default with \"automatosx init --force\"'\n ],\n context\n );\n }\n\n static parseError(error: Error, path: string): ConfigError {\n return new ConfigError(\n `Failed to parse configuration: ${error.message}`,\n ErrorCode.CONFIG_PARSE_ERROR,\n [\n 'Check JSON syntax in your config file',\n 'Use a JSON validator to find syntax errors',\n 'Reset to default with \"automatosx init --force\"'\n ],\n { path, originalError: error.message }\n );\n }\n}\n\n/**\n * Path Errors\n */\nexport class PathError extends BaseError {\n constructor(\n message: string,\n code: ErrorCode = ErrorCode.PATH_INVALID,\n suggestions: string[] = [],\n context?: Record<string, unknown>,\n isOperational: boolean = true\n ) {\n super(message, code, suggestions, context, isOperational);\n }\n\n static traversal(path: string): PathError {\n return new PathError(\n `Path traversal attempt detected: ${path}`,\n ErrorCode.PATH_TRAVERSAL,\n [\n 'Use relative paths within the project directory',\n 'Avoid using \"..\" in file paths',\n 'Check your file path for security issues'\n ],\n { path },\n false // Security error, not operational\n );\n }\n\n static notFound(path: string, type: string = 'Path'): PathError {\n return new PathError(\n `${type} not found: ${path}`,\n ErrorCode.PATH_NOT_FOUND,\n [\n 'Check that the path exists and is accessible',\n 'Verify you have the correct permissions',\n `Use \"automatosx list\" to see available ${type.toLowerCase()}s`\n ],\n { path, type }\n );\n }\n}\n\n/**\n * Memory Errors\n */\nexport class MemoryError extends BaseError {\n constructor(\n message: string,\n code: ErrorCode = ErrorCode.MEMORY_DATABASE_ERROR,\n suggestions: string[] = [],\n context?: Record<string, unknown>\n ) {\n super(message, code, suggestions, context);\n }\n\n static notInitialized(): MemoryError {\n return new MemoryError(\n 'Memory system not initialized',\n ErrorCode.MEMORY_NOT_INITIALIZED,\n [\n 'Run \"automatosx init\" to initialize the project',\n 'Check that .automatosx/memory directory exists',\n 'Verify file permissions on the memory database'\n ]\n );\n }\n\n static embeddingError(reason: string): MemoryError {\n return new MemoryError(\n `Embedding provider error: ${reason}`,\n ErrorCode.MEMORY_EMBEDDING_ERROR,\n [\n 'Set OPENAI_API_KEY environment variable',\n 'Configure embedding provider in automatosx.config.json',\n 'Check your API key is valid and has credits'\n ],\n { reason }\n );\n }\n\n static queryError(query: string, error: Error): MemoryError {\n return new MemoryError(\n `Memory query failed: ${error.message}`,\n ErrorCode.MEMORY_QUERY_ERROR,\n [\n 'Check your query syntax',\n 'Verify memory database is not corrupted',\n 'Try rebuilding memory index with \"automatosx memory rebuild\"'\n ],\n { query, originalError: error.message }\n );\n }\n}\n\n/**\n * Provider Errors\n */\nexport class ProviderError extends BaseError {\n constructor(\n message: string,\n code: ErrorCode = ErrorCode.PROVIDER_UNAVAILABLE,\n suggestions: string[] = [],\n context?: Record<string, unknown>\n ) {\n super(message, code, suggestions, context);\n }\n\n static notFound(providerName: string): ProviderError {\n return new ProviderError(\n `Provider \"${providerName}\" not found`,\n ErrorCode.PROVIDER_NOT_FOUND,\n [\n 'Check available providers with \"automatosx list providers\"',\n 'Verify provider is enabled in automatosx.config.json',\n 'Install the provider CLI if not already installed'\n ],\n { providerName }\n );\n }\n\n static unavailable(providerName: string, reason?: string): ProviderError {\n const msg = reason\n ? `Provider \"${providerName}\" unavailable: ${reason}`\n : `Provider \"${providerName}\" is unavailable`;\n\n return new ProviderError(\n msg,\n ErrorCode.PROVIDER_UNAVAILABLE,\n [\n 'Check that the provider CLI is installed and in your PATH',\n 'Verify provider configuration in automatosx.config.json',\n 'Try running the provider CLI directly to diagnose issues',\n 'Check system status with \"automatosx status --verbose\"'\n ],\n { providerName, reason }\n );\n }\n\n static timeout(providerName: string, timeoutMs: number): ProviderError {\n return new ProviderError(\n `Provider \"${providerName}\" timed out after ${timeoutMs}ms`,\n ErrorCode.PROVIDER_TIMEOUT,\n [\n 'Increase timeout in automatosx.config.json',\n 'Try a simpler prompt or reduce context size',\n 'Check your network connection',\n 'Verify the provider service is responsive'\n ],\n { providerName, timeoutMs }\n );\n }\n\n static noAvailableProviders(): ProviderError {\n return new ProviderError(\n 'No AI providers are available',\n ErrorCode.PROVIDER_NO_AVAILABLE,\n [\n 'Install at least one provider CLI (Claude or Gemini)',\n 'Enable providers in automatosx.config.json',\n 'Check provider status with \"automatosx status\"',\n 'Verify provider CLIs are in your PATH'\n ]\n );\n }\n\n static executionError(providerName: string, error: Error): ProviderError {\n return new ProviderError(\n `Provider \"${providerName}\" execution failed: ${error.message}`,\n ErrorCode.PROVIDER_EXEC_ERROR,\n [\n 'Check that the provider CLI is installed correctly',\n 'Verify you have necessary API keys configured',\n 'Try running the provider CLI directly to diagnose',\n 'Check error logs with --debug flag'\n ],\n { providerName, originalError: error.message }\n );\n }\n}\n\n/**\n * Agent Errors\n */\nexport class AgentError extends BaseError {\n constructor(\n message: string,\n code: ErrorCode = ErrorCode.AGENT_EXECUTION_ERROR,\n suggestions: string[] = [],\n context?: Record<string, unknown>\n ) {\n super(message, code, suggestions, context);\n }\n\n static profileNotFound(agentName: string): AgentError {\n return new AgentError(\n `Agent profile \"${agentName}\" not found`,\n ErrorCode.AGENT_PROFILE_NOT_FOUND,\n [\n 'List available agents with \"automatosx list agents\"',\n 'Create agent profile in .automatosx/agents/',\n 'Check spelling of agent name',\n 'Use example agents from examples/agents/ directory'\n ],\n { agentName }\n );\n }\n\n static profileInvalid(agentName: string, reason: string): AgentError {\n return new AgentError(\n `Agent profile \"${agentName}\" is invalid: ${reason}`,\n ErrorCode.AGENT_PROFILE_INVALID,\n [\n 'Check YAML syntax in agent profile',\n 'Validate required fields (name, provider, abilities)',\n 'Refer to example agents in examples/agents/',\n 'See documentation for agent profile schema'\n ],\n { agentName, reason }\n );\n }\n\n static abilityNotFound(abilityName: string, agentName: string): AgentError {\n return new AgentError(\n `Ability \"${abilityName}\" not found for agent \"${agentName}\"`,\n ErrorCode.AGENT_ABILITY_NOT_FOUND,\n [\n 'List available abilities with \"automatosx list abilities\"',\n 'Create ability file in .automatosx/abilities/',\n 'Check spelling of ability name in agent profile',\n 'Use example abilities from examples/abilities/'\n ],\n { abilityName, agentName }\n );\n }\n\n static executionError(agentName: string, error: Error): AgentError {\n return new AgentError(\n `Agent \"${agentName}\" execution failed: ${error.message}`,\n ErrorCode.AGENT_EXECUTION_ERROR,\n [\n 'Check provider is available and configured',\n 'Verify agent profile is valid',\n 'Try simpler task to isolate the issue',\n 'Run with --debug flag for detailed logs'\n ],\n { agentName, originalError: error.message }\n );\n }\n}\n\n/**\n * Validation Errors\n */\nexport class ValidationError extends BaseError {\n constructor(\n message: string,\n code: ErrorCode = ErrorCode.VALIDATION_FAILED,\n suggestions: string[] = [],\n context?: Record<string, unknown>\n ) {\n super(message, code, suggestions, context);\n }\n\n static failed(field: string, reason: string): ValidationError {\n return new ValidationError(\n `Validation failed for \"${field}\": ${reason}`,\n ErrorCode.VALIDATION_FAILED,\n [\n 'Check the value meets required constraints',\n 'Refer to documentation for valid formats',\n 'Use --help to see expected formats'\n ],\n { field, reason }\n );\n }\n\n static typeError(field: string, expected: string, actual: string): ValidationError {\n return new ValidationError(\n `Type error for \"${field}\": expected ${expected}, got ${actual}`,\n ErrorCode.VALIDATION_TYPE_ERROR,\n [\n `Provide a valid ${expected} value`,\n 'Check your input format',\n 'Use --help for usage examples'\n ],\n { field, expected, actual }\n );\n }\n}\n\n/**\n * Helper function to convert unknown errors to BaseError\n */\nexport function toBaseError(error: unknown): BaseError {\n if (error instanceof BaseError) {\n return error;\n }\n\n if (error instanceof Error) {\n return new BaseError(\n error.message,\n ErrorCode.UNKNOWN_ERROR,\n ['Check error details for more information'],\n { originalError: error.name, stack: error.stack }\n );\n }\n\n return new BaseError(\n String(error),\n ErrorCode.UNKNOWN_ERROR,\n ['An unexpected error occurred']\n );\n}\n\n/**\n * Check if error is operational (expected) or programming error\n */\nexport function isOperationalError(error: unknown): boolean {\n if (error instanceof BaseError) {\n return error.isOperational;\n }\n return false;\n}\n","/**\n * Message Formatter - Standardized CLI messages\n *\n * Provides consistent success/failure/info message formatting\n */\n\nimport chalk from 'chalk';\n\nexport interface MessageOptions {\n /**\n * Use colors\n */\n colors?: boolean;\n\n /**\n * Prefix with icon\n */\n icon?: boolean;\n}\n\n/**\n * Format success message\n */\nexport function formatSuccess(message: string, options: MessageOptions = {}): string {\n const { colors = true, icon = true } = options;\n\n const iconStr = icon ? '✓ ' : '';\n\n return colors\n ? chalk.green(`${iconStr}${message}`)\n : `${iconStr}${message}`;\n}\n\n/**\n * Format failure message\n */\nexport function formatFailure(message: string, options: MessageOptions = {}): string {\n const { colors = true, icon = true } = options;\n\n const iconStr = icon ? '✗ ' : '';\n\n return colors\n ? chalk.red(`${iconStr}${message}`)\n : `${iconStr}${message}`;\n}\n\n/**\n * Format warning message\n */\nexport function formatWarning(message: string, options: MessageOptions = {}): string {\n const { colors = true, icon = true } = options;\n\n const iconStr = icon ? '⚠ ' : '';\n\n return colors\n ? chalk.yellow(`${iconStr}${message}`)\n : `${iconStr}${message}`;\n}\n\n/**\n * Format info message\n */\nexport function formatInfo(message: string, options: MessageOptions = {}): string {\n const { colors = true, icon = true } = options;\n\n const iconStr = icon ? 'ℹ ' : '';\n\n return colors\n ? chalk.blue(`${iconStr}${message}`)\n : `${iconStr}${message}`;\n}\n\n/**\n * Print success message\n */\nexport function printSuccess(message: string, options: MessageOptions = {}): void {\n console.log(formatSuccess(message, options));\n}\n\n/**\n * Print failure message\n */\nexport function printFailure(message: string, options: MessageOptions = {}): void {\n console.log(formatFailure(message, options));\n}\n\n/**\n * Print warning message\n */\nexport function printWarning(message: string, options: MessageOptions = {}): void {\n console.log(formatWarning(message, options));\n}\n\n/**\n * Print info message\n */\nexport function printInfo(message: string, options: MessageOptions = {}): void {\n console.log(formatInfo(message, options));\n}\n\n/**\n * Format step message (for multi-step operations)\n */\nexport function formatStep(step: string, options: MessageOptions = {}): string {\n const { colors = true } = options;\n\n return colors\n ? chalk.gray(` ${step}`)\n : ` ${step}`;\n}\n\n/**\n * Format section header\n */\nexport function formatHeader(header: string, options: MessageOptions = {}): string {\n const { colors = true } = options;\n\n return colors\n ? chalk.bold.cyan(`\\n${header}`)\n : `\\n${header}`;\n}\n\n/**\n * Format key-value pair\n */\nexport function formatKeyValue(key: string, value: string, options: MessageOptions = {}): string {\n const { colors = true } = options;\n\n const formattedKey = colors ? chalk.gray(`${key}:`) : `${key}:`;\n const formattedValue = colors ? chalk.white(value) : value;\n\n return `${formattedKey} ${formattedValue}`;\n}\n\n/**\n * Print completion message with stats\n */\nexport function printCompletion(\n message: string,\n stats: Record<string, string | number>,\n options: MessageOptions = {}\n): void {\n printSuccess(message, options);\n\n Object.entries(stats).forEach(([key, value]) => {\n console.log(`- ${key}: ${value}`);\n });\n}\n","/**\n * Configuration Validator\n *\n * Validates AutomatosX configuration against schema\n */\n\nimport type { AutomatosXConfig, ProviderConfig, MemoryConfig, WorkspaceConfig, LoggingConfig } from '../types/config.js';\nimport type { LogLevel } from '../types/logger.js';\n\nexport interface ValidationError {\n path: string;\n message: string;\n value?: any;\n}\n\nexport interface ValidationResult {\n valid: boolean;\n errors: ValidationError[];\n}\n\n/**\n * Validate entire configuration\n */\nexport function validateConfig(config: any): ValidationResult {\n const errors: ValidationError[] = [];\n\n // Check required top-level fields\n if (!config.providers) {\n errors.push({\n path: 'providers',\n message: 'Required field \"providers\" is missing'\n });\n } else {\n errors.push(...validateProviders(config.providers));\n }\n\n if (!config.memory) {\n errors.push({\n path: 'memory',\n message: 'Required field \"memory\" is missing'\n });\n } else {\n errors.push(...validateMemory(config.memory));\n }\n\n if (!config.workspace) {\n errors.push({\n path: 'workspace',\n message: 'Required field \"workspace\" is missing'\n });\n } else {\n errors.push(...validateWorkspace(config.workspace));\n }\n\n if (!config.logging) {\n errors.push({\n path: 'logging',\n message: 'Required field \"logging\" is missing'\n });\n } else {\n errors.push(...validateLogging(config.logging));\n }\n\n return {\n valid: errors.length === 0,\n errors\n };\n}\n\n/**\n * Validate providers configuration\n */\nfunction validateProviders(providers: any): ValidationError[] {\n const errors: ValidationError[] = [];\n\n if (typeof providers !== 'object' || providers === null) {\n errors.push({\n path: 'providers',\n message: 'Providers must be an object',\n value: providers\n });\n return errors;\n }\n\n const providerNames = Object.keys(providers);\n if (providerNames.length === 0) {\n errors.push({\n path: 'providers',\n message: 'At least one provider must be configured'\n });\n }\n\n // Validate each provider\n for (const [name, provider] of Object.entries(providers)) {\n errors.push(...validateProvider(name, provider as any));\n }\n\n // Check for at least one enabled provider\n const hasEnabledProvider = providerNames.some(name => providers[name]?.enabled === true);\n if (!hasEnabledProvider) {\n errors.push({\n path: 'providers',\n message: 'At least one provider must be enabled'\n });\n }\n\n return errors;\n}\n\n/**\n * Validate single provider configuration\n */\nfunction validateProvider(name: string, provider: any): ValidationError[] {\n const errors: ValidationError[] = [];\n const basePath = `providers.${name}`;\n\n if (typeof provider !== 'object' || provider === null) {\n errors.push({\n path: basePath,\n message: 'Provider must be an object',\n value: provider\n });\n return errors;\n }\n\n // Required fields\n if (typeof provider.enabled !== 'boolean') {\n errors.push({\n path: `${basePath}.enabled`,\n message: 'enabled must be a boolean',\n value: provider.enabled\n });\n }\n\n if (typeof provider.priority !== 'number') {\n errors.push({\n path: `${basePath}.priority`,\n message: 'priority must be a number',\n value: provider.priority\n });\n } else if (provider.priority < 1) {\n errors.push({\n path: `${basePath}.priority`,\n message: 'priority must be >= 1',\n value: provider.priority\n });\n }\n\n if (typeof provider.timeout !== 'number') {\n errors.push({\n path: `${basePath}.timeout`,\n message: 'timeout must be a number',\n value: provider.timeout\n });\n } else if (provider.timeout < 1000) {\n errors.push({\n path: `${basePath}.timeout`,\n message: 'timeout must be >= 1000ms',\n value: provider.timeout\n });\n }\n\n if (typeof provider.command !== 'string') {\n errors.push({\n path: `${basePath}.command`,\n message: 'command must be a string',\n value: provider.command\n });\n } else if (provider.command.trim() === '') {\n errors.push({\n path: `${basePath}.command`,\n message: 'command cannot be empty',\n value: provider.command\n });\n }\n\n return errors;\n}\n\n/**\n * Validate memory configuration\n */\nfunction validateMemory(memory: any): ValidationError[] {\n const errors: ValidationError[] = [];\n const basePath = 'memory';\n\n if (typeof memory !== 'object' || memory === null) {\n errors.push({\n path: basePath,\n message: 'Memory must be an object',\n value: memory\n });\n return errors;\n }\n\n // maxEntries\n if (typeof memory.maxEntries !== 'number') {\n errors.push({\n path: `${basePath}.maxEntries`,\n message: 'maxEntries must be a number',\n value: memory.maxEntries\n });\n } else if (memory.maxEntries < 100) {\n errors.push({\n path: `${basePath}.maxEntries`,\n message: 'maxEntries must be >= 100',\n value: memory.maxEntries\n });\n }\n\n // persistPath\n if (typeof memory.persistPath !== 'string') {\n errors.push({\n path: `${basePath}.persistPath`,\n message: 'persistPath must be a string',\n value: memory.persistPath\n });\n } else if (memory.persistPath.trim() === '') {\n errors.push({\n path: `${basePath}.persistPath`,\n message: 'persistPath cannot be empty',\n value: memory.persistPath\n });\n }\n\n // autoCleanup\n if (typeof memory.autoCleanup !== 'boolean') {\n errors.push({\n path: `${basePath}.autoCleanup`,\n message: 'autoCleanup must be a boolean',\n value: memory.autoCleanup\n });\n }\n\n // cleanupDays\n if (typeof memory.cleanupDays !== 'number') {\n errors.push({\n path: `${basePath}.cleanupDays`,\n message: 'cleanupDays must be a number',\n value: memory.cleanupDays\n });\n } else if (memory.cleanupDays < 1) {\n errors.push({\n path: `${basePath}.cleanupDays`,\n message: 'cleanupDays must be >= 1',\n value: memory.cleanupDays\n });\n }\n\n return errors;\n}\n\n/**\n * Validate workspace configuration\n */\nfunction validateWorkspace(workspace: any): ValidationError[] {\n const errors: ValidationError[] = [];\n const basePath = 'workspace';\n\n if (typeof workspace !== 'object' || workspace === null) {\n errors.push({\n path: basePath,\n message: 'Workspace must be an object',\n value: workspace\n });\n return errors;\n }\n\n // basePath\n if (typeof workspace.basePath !== 'string') {\n errors.push({\n path: `${basePath}.basePath`,\n message: 'basePath must be a string',\n value: workspace.basePath\n });\n } else if (workspace.basePath.trim() === '') {\n errors.push({\n path: `${basePath}.basePath`,\n message: 'basePath cannot be empty',\n value: workspace.basePath\n });\n }\n\n // autoCleanup\n if (typeof workspace.autoCleanup !== 'boolean') {\n errors.push({\n path: `${basePath}.autoCleanup`,\n message: 'autoCleanup must be a boolean',\n value: workspace.autoCleanup\n });\n }\n\n // cleanupDays\n if (typeof workspace.cleanupDays !== 'number') {\n errors.push({\n path: `${basePath}.cleanupDays`,\n message: 'cleanupDays must be a number',\n value: workspace.cleanupDays\n });\n } else if (workspace.cleanupDays < 1) {\n errors.push({\n path: `${basePath}.cleanupDays`,\n message: 'cleanupDays must be >= 1',\n value: workspace.cleanupDays\n });\n }\n\n // maxFiles\n if (typeof workspace.maxFiles !== 'number') {\n errors.push({\n path: `${basePath}.maxFiles`,\n message: 'maxFiles must be a number',\n value: workspace.maxFiles\n });\n } else if (workspace.maxFiles < 1) {\n errors.push({\n path: `${basePath}.maxFiles`,\n message: 'maxFiles must be >= 1',\n value: workspace.maxFiles\n });\n }\n\n return errors;\n}\n\n/**\n * Validate logging configuration\n */\nfunction validateLogging(logging: any): ValidationError[] {\n const errors: ValidationError[] = [];\n const basePath = 'logging';\n\n if (typeof logging !== 'object' || logging === null) {\n errors.push({\n path: basePath,\n message: 'Logging must be an object',\n value: logging\n });\n return errors;\n }\n\n // level\n const validLevels: LogLevel[] = ['debug', 'info', 'warn', 'error'];\n if (typeof logging.level !== 'string') {\n errors.push({\n path: `${basePath}.level`,\n message: 'level must be a string',\n value: logging.level\n });\n } else if (!validLevels.includes(logging.level as LogLevel)) {\n errors.push({\n path: `${basePath}.level`,\n message: `level must be one of: ${validLevels.join(', ')}`,\n value: logging.level\n });\n }\n\n // path\n if (typeof logging.path !== 'string') {\n errors.push({\n path: `${basePath}.path`,\n message: 'path must be a string',\n value: logging.path\n });\n } else if (logging.path.trim() === '') {\n errors.push({\n path: `${basePath}.path`,\n message: 'path cannot be empty',\n value: logging.path\n });\n }\n\n // console\n if (typeof logging.console !== 'boolean') {\n errors.push({\n path: `${basePath}.console`,\n message: 'console must be a boolean',\n value: logging.console\n });\n }\n\n return errors;\n}\n\n/**\n * Format validation errors for display\n */\nexport function formatValidationErrors(errors: ValidationError[]): string {\n if (errors.length === 0) {\n return 'No validation errors';\n }\n\n const lines: string[] = ['Configuration validation failed:\\n'];\n\n errors.forEach((error, index) => {\n lines.push(` ${index + 1}. ${error.path}: ${error.message}`);\n if (error.value !== undefined) {\n lines.push(` Current value: ${JSON.stringify(error.value)}`);\n }\n });\n\n return lines.join('\\n');\n}\n","/**\n * Configuration Management - v5.0+\n *\n * Supports both YAML and JSON configuration files.\n * Priority: .automatosx/config.yaml > automatosx.config.yaml >\n * .automatosx/config.json > automatosx.config.json >\n * ~/.automatosx/config.yaml > ~/.automatosx/config.json >\n * DEFAULT_CONFIG\n */\n\nimport { readFile, writeFile } from 'fs/promises';\nimport { resolve, join, extname } from 'path';\nimport { existsSync } from 'fs';\nimport { load as loadYaml, dump as dumpYaml } from 'js-yaml';\nimport type {\n AutomatosXConfig,\n MemorySearchConfig,\n LoggingRetentionConfig\n} from '../types/config.js';\nimport { DEFAULT_CONFIG } from '../types/config.js';\nimport { ConfigError, ErrorCode } from '../utils/errors.js';\nimport { logger } from '../utils/logger.js';\nimport { deepMerge } from '../utils/deep-merge.js';\nimport {\n VALIDATION_LIMITS,\n isValidRelativePath,\n isValidCommand,\n isValidName,\n isValidExtension,\n isPositiveInteger,\n isNonNegativeInteger,\n inRange\n} from './validation-limits.js';\nimport { TTLCache } from './cache.js';\n\n/**\n * Configuration cache (process-level)\n *\n * Caches loaded configurations by project directory to avoid\n * repeated file system access and parsing on every execution.\n *\n * TTL: 60 seconds (config rarely changes during execution)\n * Max entries: 10 (one per project directory)\n */\nconst configCache = new TTLCache<AutomatosXConfig>({\n ttl: 60000, // 60 seconds\n maxEntries: 10 // Support multiple project directories\n});\n\n/**\n * Load configuration from file with caching\n *\n * Checks cache first to avoid repeated file system access and parsing.\n * Cache TTL: 60 seconds.\n *\n * Priority:\n * 1. .automatosx/config.yaml (highest)\n * 2. .automatosx/config.json\n * 3. automatosx.config.yaml\n * 4. automatosx.config.json\n * 5. ~/.automatosx/config.yaml\n * 6. ~/.automatosx/config.json\n * 7. DEFAULT_CONFIG (fallback)\n */\nexport async function loadConfig(projectDir: string): Promise<AutomatosXConfig> {\n // Check cache first\n const cached = configCache.get(projectDir);\n if (cached) {\n logger.debug('Config loaded from cache', { projectDir });\n return cached;\n }\n\n // Load from file system\n const config = await loadConfigUncached(projectDir);\n\n // Cache the result\n configCache.set(projectDir, config);\n logger.debug('Config cached', { projectDir, ttl: 60000 });\n\n return config;\n}\n\n/**\n * Load configuration from file without caching\n *\n * Internal function used by loadConfig(). Do not call directly unless\n * you specifically need to bypass the cache.\n */\nasync function loadConfigUncached(projectDir: string): Promise<AutomatosXConfig> {\n // Try project configs in priority order\n const projectConfigs = [\n resolve(projectDir, '.automatosx', 'config.yaml'),\n resolve(projectDir, '.automatosx', 'config.json'),\n resolve(projectDir, 'automatosx.config.yaml'),\n resolve(projectDir, 'automatosx.config.json')\n ];\n\n for (const configPath of projectConfigs) {\n if (existsSync(configPath)) {\n logger.debug('Loading config from path', { path: configPath });\n return await loadConfigFile(configPath);\n }\n }\n\n // Try user home config\n const homeDir = process.env.HOME || process.env.USERPROFILE || '';\n const userConfigs = [\n resolve(homeDir, '.automatosx', 'config.yaml'),\n resolve(homeDir, '.automatosx', 'config.json')\n ];\n\n for (const configPath of userConfigs) {\n if (existsSync(configPath)) {\n logger.debug('Loading config from path', { path: configPath });\n return await loadConfigFile(configPath);\n }\n }\n\n // Default config\n logger.debug('Using DEFAULT_CONFIG');\n return DEFAULT_CONFIG;\n}\n\n/**\n * Load and parse config file (supports both YAML and JSON)\n *\n * @param path - Path to config file\n * @returns Parsed and validated configuration\n *\n * @throws {ConfigError} If file not found, parse fails, or validation fails\n */\nexport async function loadConfigFile(path: string): Promise<AutomatosXConfig> {\n try {\n const content = await readFile(path, 'utf-8');\n\n // Security: File size limit (prevent DoS)\n if (content.length > VALIDATION_LIMITS.MAX_CONFIG_FILE_SIZE) {\n throw ConfigError.parseError(\n new Error(`Config file too large (max ${VALIDATION_LIMITS.MAX_CONFIG_FILE_SIZE / 1024}KB, got ${Math.ceil(content.length / 1024)}KB)`),\n path\n );\n }\n\n const ext = extname(path).toLowerCase();\n\n let userConfig: any;\n try {\n if (ext === '.yaml' || ext === '.yml') {\n // Parse YAML\n userConfig = loadYaml(content);\n } else {\n // Parse JSON\n userConfig = JSON.parse(content);\n }\n } catch (parseError) {\n throw ConfigError.parseError(parseError as Error, path);\n }\n\n // Merge with defaults (deep merge)\n const config = mergeConfig(DEFAULT_CONFIG, userConfig);\n\n // Validate merged config\n const validationErrors = validateConfig(config);\n if (validationErrors.length > 0) {\n throw ConfigError.invalid(\n validationErrors.join('; '),\n { path, errors: validationErrors }\n );\n }\n\n logger.info('Config loaded successfully', { path, format: ext });\n return config;\n } catch (error) {\n // Re-throw ConfigError as-is\n if (error instanceof ConfigError) {\n throw error;\n }\n\n // Handle file system errors\n if ((error as any).code === 'ENOENT') {\n throw ConfigError.notFound(path);\n }\n\n if ((error as any).code === 'EACCES') {\n throw new ConfigError(\n `Permission denied reading config: ${path}`,\n ErrorCode.CONFIG_PARSE_ERROR,\n [\n 'Check file permissions',\n 'Run with appropriate user privileges',\n 'Verify the file is accessible'\n ],\n { path, error: (error as Error).message }\n );\n }\n\n // Unknown error\n throw new ConfigError(\n `Failed to load config: ${(error as Error).message}`,\n ErrorCode.CONFIG_PARSE_ERROR,\n ['Check file format and permissions'],\n { path, originalError: (error as Error).message }\n );\n }\n}\n\n/**\n * Deep merge configs (handles all v5.0+ config sections)\n *\n * Uses generic deepMerge utility for consistent, type-safe merging.\n *\n * Merge behavior:\n * - null = explicitly disable feature\n * - undefined = use default value\n * - objects = recursively merge\n * - arrays/primitives = replace\n */\nfunction mergeConfig(\n defaults: AutomatosXConfig,\n user: Partial<AutomatosXConfig>\n): AutomatosXConfig {\n return deepMerge(defaults, user);\n}\n\n/**\n * Validate config (comprehensive validation for v5.0+)\n *\n * Validates all configuration values with:\n * - Security checks (path traversal, command injection, name injection)\n * - Resource limits (prevent DoS attacks)\n * - Type validation (prevent type confusion)\n * - Range validation (min/max values)\n */\nexport function validateConfig(config: AutomatosXConfig): string[] {\n const errors: string[] = [];\n\n // Validate providers\n for (const [name, provider] of Object.entries(config.providers)) {\n // NEW: Validate provider name (prevent name injection)\n if (!isValidName(name)) {\n errors.push(`Provider \"${name}\": name invalid (use alphanumeric, dash, underscore only, max 50 chars)`);\n }\n\n // NEW: Validate command (prevent command injection)\n if (!provider.command) {\n errors.push(`Provider ${name}: command is required`);\n } else if (!isValidCommand(provider.command)) {\n errors.push(`Provider ${name}: command invalid (alphanumeric, dash, underscore only, max 100 chars, no shell metacharacters)`);\n }\n\n // Existing: Min validation + NEW: Max validation\n if (!isPositiveInteger(provider.priority)) {\n errors.push(`Provider ${name}: priority must be a positive integer`);\n }\n\n if (!isPositiveInteger(provider.timeout)) {\n errors.push(`Provider ${name}: timeout must be a positive integer`);\n } else {\n if (provider.timeout < VALIDATION_LIMITS.MIN_TIMEOUT) {\n errors.push(`Provider ${name}: timeout must be >= ${VALIDATION_LIMITS.MIN_TIMEOUT}ms`);\n }\n if (provider.timeout > VALIDATION_LIMITS.MAX_TIMEOUT) {\n errors.push(`Provider ${name}: timeout must be <= ${VALIDATION_LIMITS.MAX_TIMEOUT}ms (1 hour max)`);\n }\n }\n\n if (provider.healthCheck) {\n if (!isPositiveInteger(provider.healthCheck.interval)) {\n errors.push(`Provider ${name}: healthCheck.interval must be a positive integer`);\n } else {\n if (provider.healthCheck.interval < VALIDATION_LIMITS.MIN_INTERVAL) {\n errors.push(`Provider ${name}: healthCheck.interval must be >= ${VALIDATION_LIMITS.MIN_INTERVAL}ms`);\n }\n if (provider.healthCheck.interval > VALIDATION_LIMITS.MAX_TIMEOUT) {\n errors.push(`Provider ${name}: healthCheck.interval must be <= ${VALIDATION_LIMITS.MAX_TIMEOUT}ms`);\n }\n }\n\n if (!isPositiveInteger(provider.healthCheck.timeout)) {\n errors.push(`Provider ${name}: healthCheck.timeout must be a positive integer`);\n } else {\n if (provider.healthCheck.timeout < 100) {\n errors.push(`Provider ${name}: healthCheck.timeout must be >= 100ms`);\n }\n if (provider.healthCheck.timeout > VALIDATION_LIMITS.MAX_TIMEOUT) {\n errors.push(`Provider ${name}: healthCheck.timeout must be <= ${VALIDATION_LIMITS.MAX_TIMEOUT}ms`);\n }\n }\n }\n }\n\n // Validate execution\n if (config.execution) {\n // defaultTimeout\n if (!isPositiveInteger(config.execution.defaultTimeout)) {\n errors.push('Execution: defaultTimeout must be a positive integer');\n } else {\n if (config.execution.defaultTimeout < VALIDATION_LIMITS.MIN_TIMEOUT) {\n errors.push(`Execution: defaultTimeout must be >= ${VALIDATION_LIMITS.MIN_TIMEOUT}ms`);\n }\n if (config.execution.defaultTimeout > VALIDATION_LIMITS.MAX_TIMEOUT) {\n errors.push(`Execution: defaultTimeout must be <= ${VALIDATION_LIMITS.MAX_TIMEOUT}ms (1 hour max)`);\n }\n }\n\n // retry.maxAttempts\n if (!isPositiveInteger(config.execution.retry.maxAttempts)) {\n errors.push('Execution: retry.maxAttempts must be a positive integer');\n } else if (config.execution.retry.maxAttempts > 10) {\n errors.push('Execution: retry.maxAttempts must be <= 10 (reasonable retry limit)');\n }\n\n // retry.initialDelay\n if (!isNonNegativeInteger(config.execution.retry.initialDelay)) {\n errors.push('Execution: retry.initialDelay must be a non-negative integer');\n } else if (config.execution.retry.initialDelay > VALIDATION_LIMITS.MAX_TIMEOUT) {\n errors.push(`Execution: retry.initialDelay must be <= ${VALIDATION_LIMITS.MAX_TIMEOUT}ms`);\n }\n\n // retry.maxDelay\n if (!isPositiveInteger(config.execution.retry.maxDelay)) {\n errors.push('Execution: retry.maxDelay must be a positive integer');\n } else {\n if (config.execution.retry.maxDelay < config.execution.retry.initialDelay) {\n errors.push('Execution: retry.maxDelay must be >= initialDelay');\n }\n if (config.execution.retry.maxDelay > VALIDATION_LIMITS.MAX_TIMEOUT) {\n errors.push(`Execution: retry.maxDelay must be <= ${VALIDATION_LIMITS.MAX_TIMEOUT}ms`);\n }\n }\n\n // retry.backoffFactor\n if (typeof config.execution.retry.backoffFactor !== 'number' || config.execution.retry.backoffFactor < VALIDATION_LIMITS.MIN_BACKOFF_FACTOR) {\n errors.push(`Execution: retry.backoffFactor must be >= ${VALIDATION_LIMITS.MIN_BACKOFF_FACTOR}`);\n } else if (config.execution.retry.backoffFactor > VALIDATION_LIMITS.MAX_BACKOFF_FACTOR) {\n errors.push(`Execution: retry.backoffFactor must be <= ${VALIDATION_LIMITS.MAX_BACKOFF_FACTOR}`);\n }\n\n // provider.maxWaitMs\n if (!isPositiveInteger(config.execution.provider.maxWaitMs)) {\n errors.push('Execution: provider.maxWaitMs must be a positive integer');\n } else {\n if (config.execution.provider.maxWaitMs < VALIDATION_LIMITS.MIN_TIMEOUT) {\n errors.push(`Execution: provider.maxWaitMs must be >= ${VALIDATION_LIMITS.MIN_TIMEOUT}ms`);\n }\n if (config.execution.provider.maxWaitMs > VALIDATION_LIMITS.MAX_TIMEOUT) {\n errors.push(`Execution: provider.maxWaitMs must be <= ${VALIDATION_LIMITS.MAX_TIMEOUT}ms`);\n }\n }\n }\n\n // Validate orchestration\n if (config.orchestration) {\n // session.maxSessions\n if (!isPositiveInteger(config.orchestration.session.maxSessions)) {\n errors.push('Orchestration: session.maxSessions must be a positive integer');\n } else {\n if (config.orchestration.session.maxSessions > VALIDATION_LIMITS.MAX_SESSIONS) {\n errors.push(`Orchestration: session.maxSessions must be <= ${VALIDATION_LIMITS.MAX_SESSIONS}`);\n }\n }\n\n // session.maxMetadataSize\n if (!isPositiveInteger(config.orchestration.session.maxMetadataSize)) {\n errors.push('Orchestration: session.maxMetadataSize must be a positive integer');\n } else {\n if (config.orchestration.session.maxMetadataSize < VALIDATION_LIMITS.MIN_BYTES) {\n errors.push(`Orchestration: session.maxMetadataSize must be >= ${VALIDATION_LIMITS.MIN_BYTES} bytes`);\n }\n if (config.orchestration.session.maxMetadataSize > VALIDATION_LIMITS.MAX_FILE_SIZE) {\n errors.push(`Orchestration: session.maxMetadataSize must be <= ${VALIDATION_LIMITS.MAX_FILE_SIZE} bytes`);\n }\n }\n\n // session.saveDebounce\n if (!isNonNegativeInteger(config.orchestration.session.saveDebounce)) {\n errors.push('Orchestration: session.saveDebounce must be a non-negative integer');\n } else if (config.orchestration.session.saveDebounce > VALIDATION_LIMITS.MAX_TIMEOUT) {\n errors.push(`Orchestration: session.saveDebounce must be <= ${VALIDATION_LIMITS.MAX_TIMEOUT}ms`);\n }\n\n // session.cleanupAfterDays\n if (!isPositiveInteger(config.orchestration.session.cleanupAfterDays)) {\n errors.push('Orchestration: session.cleanupAfterDays must be a positive integer');\n } else if (config.orchestration.session.cleanupAfterDays > 365) {\n errors.push('Orchestration: session.cleanupAfterDays must be <= 365 days');\n }\n\n // session.maxUuidAttempts\n if (!isPositiveInteger(config.orchestration.session.maxUuidAttempts)) {\n errors.push('Orchestration: session.maxUuidAttempts must be a positive integer');\n } else if (config.orchestration.session.maxUuidAttempts > 1000) {\n errors.push('Orchestration: session.maxUuidAttempts must be <= 1000');\n }\n\n // delegation.maxDepth\n if (!isPositiveInteger(config.orchestration.delegation.maxDepth)) {\n errors.push('Orchestration: delegation.maxDepth must be a positive integer');\n } else if (config.orchestration.delegation.maxDepth > 5) {\n errors.push('Orchestration: delegation.maxDepth must be <= 5 (prevent deep chains)');\n }\n\n // delegation.timeout\n if (!isPositiveInteger(config.orchestration.delegation.timeout)) {\n errors.push('Orchestration: delegation.timeout must be a positive integer');\n } else {\n if (config.orchestration.delegation.timeout < VALIDATION_LIMITS.MIN_TIMEOUT) {\n errors.push(`Orchestration: delegation.timeout must be >= ${VALIDATION_LIMITS.MIN_TIMEOUT}ms`);\n }\n if (config.orchestration.delegation.timeout > VALIDATION_LIMITS.MAX_TIMEOUT) {\n errors.push(`Orchestration: delegation.timeout must be <= ${VALIDATION_LIMITS.MAX_TIMEOUT}ms`);\n }\n }\n\n // workspace.maxFileSize\n if (!isPositiveInteger(config.orchestration.workspace.maxFileSize)) {\n errors.push('Orchestration: workspace.maxFileSize must be a positive integer');\n } else {\n if (config.orchestration.workspace.maxFileSize < VALIDATION_LIMITS.MIN_FILE_SIZE) {\n errors.push(`Orchestration: workspace.maxFileSize must be >= ${VALIDATION_LIMITS.MIN_FILE_SIZE} bytes`);\n }\n if (config.orchestration.workspace.maxFileSize > VALIDATION_LIMITS.MAX_FILE_SIZE) {\n errors.push(`Orchestration: workspace.maxFileSize must be <= ${VALIDATION_LIMITS.MAX_FILE_SIZE} bytes (100MB max)`);\n }\n }\n\n // workspace.maxFiles\n if (!isPositiveInteger(config.orchestration.workspace.maxFiles)) {\n errors.push('Orchestration: workspace.maxFiles must be a positive integer');\n } else if (config.orchestration.workspace.maxFiles > 10000) {\n errors.push('Orchestration: workspace.maxFiles must be <= 10000');\n }\n\n // workspace.cleanupAfterDays\n if (!isPositiveInteger(config.orchestration.workspace.cleanupAfterDays)) {\n errors.push('Orchestration: workspace.cleanupAfterDays must be a positive integer');\n } else if (config.orchestration.workspace.cleanupAfterDays > 365) {\n errors.push('Orchestration: workspace.cleanupAfterDays must be <= 365 days');\n }\n }\n\n // Validate memory\n if (!isPositiveInteger(config.memory.maxEntries)) {\n errors.push('Memory: maxEntries must be a positive integer');\n } else {\n if (config.memory.maxEntries > VALIDATION_LIMITS.MAX_ENTRIES) {\n errors.push(`Memory: maxEntries must be <= ${VALIDATION_LIMITS.MAX_ENTRIES} (1 million max)`);\n }\n }\n\n if (!isPositiveInteger(config.memory.cleanupDays)) {\n errors.push('Memory: cleanupDays must be a positive integer');\n } else if (config.memory.cleanupDays > 365) {\n errors.push('Memory: cleanupDays must be <= 365 days');\n }\n\n if (config.memory.search) {\n if (!isPositiveInteger(config.memory.search.defaultLimit)) {\n errors.push('Memory: search.defaultLimit must be a positive integer');\n } else if (config.memory.search.defaultLimit > 1000) {\n errors.push('Memory: search.defaultLimit must be <= 1000');\n }\n\n if (!isPositiveInteger(config.memory.search.maxLimit)) {\n errors.push('Memory: search.maxLimit must be a positive integer');\n } else {\n if (config.memory.search.maxLimit < config.memory.search.defaultLimit) {\n errors.push('Memory: search.maxLimit must be >= defaultLimit');\n }\n if (config.memory.search.maxLimit > 10000) {\n errors.push('Memory: search.maxLimit must be <= 10000');\n }\n }\n\n if (!isPositiveInteger(config.memory.search.timeout)) {\n errors.push('Memory: search.timeout must be a positive integer');\n } else {\n if (config.memory.search.timeout < 100) {\n errors.push('Memory: search.timeout must be >= 100ms');\n }\n if (config.memory.search.timeout > VALIDATION_LIMITS.MAX_TIMEOUT) {\n errors.push(`Memory: search.timeout must be <= ${VALIDATION_LIMITS.MAX_TIMEOUT}ms`);\n }\n }\n }\n\n // Validate abilities\n if (config.abilities) {\n if (!isPositiveInteger(config.abilities.cache.maxEntries)) {\n errors.push('Abilities: cache.maxEntries must be a positive integer');\n } else if (config.abilities.cache.maxEntries > 1000) {\n errors.push('Abilities: cache.maxEntries must be <= 1000');\n }\n\n if (!isPositiveInteger(config.abilities.cache.ttl)) {\n errors.push('Abilities: cache.ttl must be a positive integer');\n } else {\n if (config.abilities.cache.ttl < VALIDATION_LIMITS.MIN_INTERVAL) {\n errors.push(`Abilities: cache.ttl must be >= ${VALIDATION_LIMITS.MIN_INTERVAL}ms`);\n }\n if (config.abilities.cache.ttl > VALIDATION_LIMITS.MAX_TTL) {\n errors.push(`Abilities: cache.ttl must be <= ${VALIDATION_LIMITS.MAX_TTL}ms (24 hours max)`);\n }\n }\n\n if (!isPositiveInteger(config.abilities.cache.maxSize)) {\n errors.push('Abilities: cache.maxSize must be a positive integer');\n } else {\n if (config.abilities.cache.maxSize < VALIDATION_LIMITS.MIN_BYTES) {\n errors.push(`Abilities: cache.maxSize must be >= ${VALIDATION_LIMITS.MIN_BYTES} bytes`);\n }\n if (config.abilities.cache.maxSize > VALIDATION_LIMITS.MAX_CACHE_SIZE) {\n errors.push(`Abilities: cache.maxSize must be <= ${VALIDATION_LIMITS.MAX_CACHE_SIZE} bytes (500MB max)`);\n }\n }\n\n if (!isPositiveInteger(config.abilities.limits.maxFileSize)) {\n errors.push('Abilities: limits.maxFileSize must be a positive integer');\n } else {\n if (config.abilities.limits.maxFileSize < VALIDATION_LIMITS.MIN_FILE_SIZE) {\n errors.push(`Abilities: limits.maxFileSize must be >= ${VALIDATION_LIMITS.MIN_FILE_SIZE} bytes`);\n }\n if (config.abilities.limits.maxFileSize > VALIDATION_LIMITS.MAX_FILE_SIZE) {\n errors.push(`Abilities: limits.maxFileSize must be <= ${VALIDATION_LIMITS.MAX_FILE_SIZE} bytes (100MB max)`);\n }\n }\n }\n\n // Validate workspace (legacy)\n if (!isPositiveInteger(config.workspace.cleanupDays)) {\n errors.push('Workspace: cleanupDays must be a positive integer');\n } else if (config.workspace.cleanupDays > 365) {\n errors.push('Workspace: cleanupDays must be <= 365 days');\n }\n\n if (!isPositiveInteger(config.workspace.maxFiles)) {\n errors.push('Workspace: maxFiles must be a positive integer');\n } else if (config.workspace.maxFiles > 10000) {\n errors.push('Workspace: maxFiles must be <= 10000');\n }\n\n // Validate logging\n if (config.logging?.retention) {\n if (!isPositiveInteger(config.logging.retention.maxSizeBytes)) {\n errors.push('Logging: retention.maxSizeBytes must be a positive integer');\n } else {\n if (config.logging.retention.maxSizeBytes < VALIDATION_LIMITS.MIN_BYTES) {\n errors.push(`Logging: retention.maxSizeBytes must be >= ${VALIDATION_LIMITS.MIN_BYTES} bytes`);\n }\n if (config.logging.retention.maxSizeBytes > VALIDATION_LIMITS.MAX_FILE_SIZE * 10) {\n errors.push('Logging: retention.maxSizeBytes must be <= 1GB');\n }\n }\n\n if (!isPositiveInteger(config.logging.retention.maxAgeDays)) {\n errors.push('Logging: retention.maxAgeDays must be a positive integer');\n } else if (config.logging.retention.maxAgeDays > 365) {\n errors.push('Logging: retention.maxAgeDays must be <= 365 days');\n }\n }\n\n // Validate performance\n if (config.performance) {\n const validateCache = (name: string, cache: any) => {\n if (!isPositiveInteger(cache.maxEntries)) {\n errors.push(`Performance: ${name}.maxEntries must be a positive integer`);\n } else if (cache.maxEntries > 10000) {\n errors.push(`Performance: ${name}.maxEntries must be <= 10000`);\n }\n\n if (!isPositiveInteger(cache.ttl)) {\n errors.push(`Performance: ${name}.ttl must be a positive integer`);\n } else {\n if (cache.ttl < VALIDATION_LIMITS.MIN_INTERVAL) {\n errors.push(`Performance: ${name}.ttl must be >= ${VALIDATION_LIMITS.MIN_INTERVAL}ms`);\n }\n if (cache.ttl > VALIDATION_LIMITS.MAX_TTL) {\n errors.push(`Performance: ${name}.ttl must be <= ${VALIDATION_LIMITS.MAX_TTL}ms (24 hours max)`);\n }\n }\n\n if (!isPositiveInteger(cache.cleanupInterval)) {\n errors.push(`Performance: ${name}.cleanupInterval must be a positive integer`);\n } else {\n if (cache.cleanupInterval < VALIDATION_LIMITS.MIN_INTERVAL) {\n errors.push(`Performance: ${name}.cleanupInterval must be >= ${VALIDATION_LIMITS.MIN_INTERVAL}ms`);\n }\n if (cache.cleanupInterval > VALIDATION_LIMITS.MAX_TIMEOUT) {\n errors.push(`Performance: ${name}.cleanupInterval must be <= ${VALIDATION_LIMITS.MAX_TIMEOUT}ms`);\n }\n }\n };\n\n validateCache('profileCache', config.performance.profileCache);\n validateCache('teamCache', config.performance.teamCache);\n validateCache('providerCache', config.performance.providerCache);\n\n if (config.performance.rateLimit.enabled) {\n if (!isPositiveInteger(config.performance.rateLimit.requestsPerMinute)) {\n errors.push('Performance: rateLimit.requestsPerMinute must be a positive integer');\n } else if (config.performance.rateLimit.requestsPerMinute > 1000) {\n errors.push('Performance: rateLimit.requestsPerMinute must be <= 1000');\n }\n\n if (!isPositiveInteger(config.performance.rateLimit.burstSize)) {\n errors.push('Performance: rateLimit.burstSize must be a positive integer');\n } else if (config.performance.rateLimit.burstSize > 100) {\n errors.push('Performance: rateLimit.burstSize must be <= 100');\n }\n }\n }\n\n // Validate advanced\n if (config.advanced) {\n if (config.advanced.embedding) {\n if (!isPositiveInteger(config.advanced.embedding.timeout)) {\n errors.push('Advanced: embedding.timeout must be a positive integer');\n } else {\n if (config.advanced.embedding.timeout < VALIDATION_LIMITS.MIN_TIMEOUT) {\n errors.push(`Advanced: embedding.timeout must be >= ${VALIDATION_LIMITS.MIN_TIMEOUT}ms`);\n }\n if (config.advanced.embedding.timeout > VALIDATION_LIMITS.MAX_TIMEOUT) {\n errors.push(`Advanced: embedding.timeout must be <= ${VALIDATION_LIMITS.MAX_TIMEOUT}ms`);\n }\n }\n\n if (!isPositiveInteger(config.advanced.embedding.dimensions)) {\n errors.push('Advanced: embedding.dimensions must be a positive integer');\n } else if (config.advanced.embedding.dimensions > 10000) {\n errors.push('Advanced: embedding.dimensions must be <= 10000');\n }\n\n if (!isNonNegativeInteger(config.advanced.embedding.maxRetries)) {\n errors.push('Advanced: embedding.maxRetries must be a non-negative integer');\n } else if (config.advanced.embedding.maxRetries > 10) {\n errors.push('Advanced: embedding.maxRetries must be <= 10');\n }\n }\n }\n\n // Validate integration\n if (config.integration) {\n if (config.integration.vscode.enabled) {\n if (config.integration.vscode.apiPort < VALIDATION_LIMITS.MIN_PORT || config.integration.vscode.apiPort > VALIDATION_LIMITS.MAX_PORT) {\n errors.push(`Integration: vscode.apiPort must be between ${VALIDATION_LIMITS.MIN_PORT} and ${VALIDATION_LIMITS.MAX_PORT}`);\n }\n }\n }\n\n // NEW: Validate all path fields (prevent path traversal)\n const pathFields = [\n { name: 'Memory: persistPath', value: config.memory.persistPath },\n { name: 'Logging: path', value: config.logging.path },\n { name: 'Abilities: basePath', value: config.abilities?.basePath },\n { name: 'Abilities: fallbackPath', value: config.abilities?.fallbackPath },\n { name: 'Orchestration: session.persistPath', value: config.orchestration?.session.persistPath },\n { name: 'Orchestration: workspace.basePath', value: config.orchestration?.workspace.basePath },\n { name: 'Workspace: basePath', value: config.workspace.basePath }\n ];\n\n for (const { name, value } of pathFields) {\n if (value && typeof value === 'string' && !isValidRelativePath(value)) {\n errors.push(`${name} must be a relative path within project (no ../, no absolute paths)`);\n }\n }\n\n // NEW: Validate security.allowedExtensions\n if (config.advanced?.security?.allowedExtensions) {\n if (!Array.isArray(config.advanced.security.allowedExtensions)) {\n errors.push('Security: allowedExtensions must be an array');\n } else {\n if (config.advanced.security.allowedExtensions.length > VALIDATION_LIMITS.MAX_ARRAY_LENGTH) {\n errors.push(`Security: allowedExtensions too many items (max ${VALIDATION_LIMITS.MAX_ARRAY_LENGTH})`);\n }\n\n for (const ext of config.advanced.security.allowedExtensions) {\n if (typeof ext !== 'string') {\n errors.push(`Security: allowedExtensions must contain only strings`);\n break;\n }\n if (!isValidExtension(ext)) {\n errors.push(`Security: invalid extension \"${ext}\" (must be alphanumeric with leading dot, max 10 chars)`);\n }\n }\n }\n }\n\n // NEW: Validate execution.retry.retryableErrors (type and length)\n if (config.execution?.retry?.retryableErrors) {\n if (!Array.isArray(config.execution.retry.retryableErrors)) {\n errors.push('Execution: retry.retryableErrors must be an array');\n } else if (config.execution.retry.retryableErrors.length > VALIDATION_LIMITS.MAX_ARRAY_LENGTH) {\n errors.push(`Execution: retry.retryableErrors too many items (max ${VALIDATION_LIMITS.MAX_ARRAY_LENGTH})`);\n }\n }\n\n return errors;\n}\n\n/**\n * Save configuration to file (supports both YAML and JSON)\n *\n * Format is auto-detected from file extension:\n * - .yaml or .yml → YAML format\n * - .json or other → JSON format\n *\n * @param path - Path to config file\n * @param config - Configuration object to save\n *\n * @throws {ConfigError} If validation fails or write fails\n */\nexport async function saveConfigFile(\n path: string,\n config: AutomatosXConfig\n): Promise<void> {\n try {\n // Validate config before saving\n const validationErrors = validateConfig(config);\n if (validationErrors.length > 0) {\n throw ConfigError.invalid(\n validationErrors.join('; '),\n { path, errors: validationErrors }\n );\n }\n\n const ext = extname(path).toLowerCase();\n let content: string;\n\n if (ext === '.yaml' || ext === '.yml') {\n // Serialize to YAML with comments\n content = dumpYaml(config, {\n indent: 2,\n lineWidth: 120,\n noRefs: true,\n sortKeys: false\n });\n } else {\n // Serialize to JSON with indentation\n content = JSON.stringify(config, null, 2);\n }\n\n // Write to file\n await writeFile(path, content, 'utf-8');\n\n logger.info('Config saved successfully', { path, format: ext });\n } catch (error) {\n // Re-throw ConfigError as-is\n if (error instanceof ConfigError) {\n throw error;\n }\n\n // Handle file system errors\n if ((error as any).code === 'EACCES') {\n throw new ConfigError(\n `Permission denied writing config: ${path}`,\n ErrorCode.CONFIG_PARSE_ERROR,\n [\n 'Check file permissions',\n 'Run with appropriate user privileges',\n 'Verify the directory is writable'\n ],\n { path, error: (error as Error).message }\n );\n }\n\n // Unknown error\n throw new ConfigError(\n `Failed to save config: ${(error as Error).message}`,\n ErrorCode.CONFIG_PARSE_ERROR,\n ['Check file path and permissions'],\n { path, originalError: (error as Error).message }\n );\n }\n}\n","/**\n * Deep Merge Utility\n *\n * Provides type-safe deep merging of configuration objects with proper handling\n * of null values (explicit disable), undefined values (use defaults), and arrays (replace).\n */\n\n/**\n * Deep merge two objects with proper null/undefined handling\n *\n * Behavior:\n * - `user === null` or `user === undefined` → returns defaults\n * - `user.key === null` → feature disabled (result.key = undefined)\n * - `user.key === undefined` → use default (result.key = defaults.key)\n * - `user.key === object` → recursively merge with defaults.key\n * - `user.key === primitive/array` → replace defaults.key\n *\n * @param defaults - Default configuration object\n * @param user - User-provided partial configuration\n * @returns Merged configuration with user overrides\n *\n * @example\n * ```typescript\n * const defaults = {\n * memory: {\n * maxEntries: 10000,\n * search: { defaultLimit: 10 }\n * }\n * };\n *\n * const user = {\n * memory: {\n * maxEntries: 5000,\n * search: null // Disable search\n * }\n * };\n *\n * const result = deepMerge(defaults, user);\n * // {\n * // memory: {\n * // maxEntries: 5000,\n * // search: undefined // Disabled\n * // }\n * // }\n * ```\n */\nexport function deepMerge<T extends object>(\n defaults: T,\n user: Partial<T> | undefined | null\n): T {\n // Handle null/undefined user config\n if (user === null || user === undefined) {\n return defaults;\n }\n\n // Start with shallow copy of defaults\n const result = { ...defaults };\n\n // Merge user values\n for (const key in user) {\n const userValue = user[key];\n\n // Explicit null = disable feature (set to undefined)\n if (userValue === null) {\n result[key] = undefined as any;\n continue;\n }\n\n // Skip undefined (use default)\n if (userValue === undefined) {\n continue;\n }\n\n const defaultValue = defaults[key];\n\n // Recursively merge nested objects\n if (\n typeof userValue === 'object' &&\n typeof defaultValue === 'object' &&\n !Array.isArray(userValue) &&\n !Array.isArray(defaultValue) &&\n userValue !== null &&\n defaultValue !== null\n ) {\n result[key] = deepMerge(defaultValue, userValue as any);\n } else {\n // Replace primitives and arrays\n result[key] = userValue as any;\n }\n }\n\n return result;\n}\n\n/**\n * Type-safe helper to check if a value is a plain object\n */\nfunction isPlainObject(value: unknown): value is object {\n return (\n typeof value === 'object' &&\n value !== null &&\n !Array.isArray(value) &&\n Object.getPrototypeOf(value) === Object.prototype\n );\n}\n","/**\n * Configuration Validation Limits and Helpers\n *\n * Defines security limits and validation functions to prevent:\n * - Resource exhaustion (DoS)\n * - Path traversal attacks\n * - Command injection\n * - Name injection\n */\n\n/**\n * Security and resource limits for configuration validation\n */\nexport const VALIDATION_LIMITS = {\n // Resource limits (prevent DoS)\n MAX_ENTRIES: 1000000, // 1 million entries (memory, cache)\n MAX_TIMEOUT: 3600000, // 1 hour (execution, delegation)\n MAX_FILE_SIZE: 104857600, // 100 MB (workspace, abilities)\n MAX_CACHE_SIZE: 524288000, // 500 MB (cache storage)\n MAX_SESSIONS: 10000, // 10k concurrent sessions\n MAX_TTL: 86400000, // 24 hours (cache TTL)\n\n // String/array limits (prevent memory exhaustion)\n MAX_STRING_LENGTH: 1000, // Max length for string fields\n MAX_ARRAY_LENGTH: 100, // Max array items\n MAX_COMMAND_LENGTH: 100, // Max command string length\n MAX_NAME_LENGTH: 50, // Max name length (providers, agents)\n\n // Config file limits\n MAX_CONFIG_FILE_SIZE: 1024 * 1024, // 1 MB config file\n\n // Port ranges (security)\n MIN_PORT: 1024, // Avoid privileged ports\n MAX_PORT: 65535, // Max valid port\n\n // Minimum values (sanity checks)\n MIN_TIMEOUT: 1000, // 1 second\n MIN_INTERVAL: 1000, // 1 second\n MIN_DELAY: 0, // Can be 0\n MIN_FILE_SIZE: 1024, // 1 KB\n MIN_ENTRIES: 1, // At least 1\n MIN_DAYS: 1, // At least 1 day\n MIN_BYTES: 1024, // 1 KB\n\n // Ratio limits\n MIN_BACKOFF_FACTOR: 1, // Linear at minimum\n MAX_BACKOFF_FACTOR: 10 // Reasonable exponential growth\n} as const;\n\n/**\n * Validate relative path (prevent path traversal)\n *\n * Security checks:\n * - No absolute paths (/)\n * - No parent directory references (../)\n * - No Windows absolute paths (C:\\)\n *\n * @param path - Path to validate\n * @returns true if path is safe relative path\n *\n * @example\n * ```typescript\n * isValidRelativePath('.automatosx/config.yaml') // ✅ true\n * isValidRelativePath('/etc/passwd') // ❌ false\n * isValidRelativePath('../../../etc/passwd') // ❌ false\n * ```\n */\nexport function isValidRelativePath(path: string): boolean {\n if (!path || typeof path !== 'string') {\n return false;\n }\n\n // No absolute Unix paths\n if (path.startsWith('/')) {\n return false;\n }\n\n // No parent directory traversal\n if (path.includes('..')) {\n return false;\n }\n\n // No absolute Windows paths (C:, D:, etc.)\n if (/^[a-zA-Z]:/.test(path)) {\n return false;\n }\n\n // No UNC paths (\\\\server\\share)\n if (path.startsWith('\\\\\\\\')) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Validate command string (prevent command injection)\n *\n * Security checks:\n * - Only alphanumeric, dash, underscore\n * - No shell metacharacters (; & | $ etc.)\n * - Reasonable length limit\n *\n * @param command - Command to validate\n * @returns true if command is safe\n *\n * @example\n * ```typescript\n * isValidCommand('claude') // ✅ true\n * isValidCommand('my-provider_v2') // ✅ true\n * isValidCommand('claude; rm -rf /') // ❌ false\n * isValidCommand('claude & backdoor') // ❌ false\n * ```\n */\nexport function isValidCommand(command: string): boolean {\n if (!command || typeof command !== 'string') {\n return false;\n }\n\n // Length check\n if (command.length > VALIDATION_LIMITS.MAX_COMMAND_LENGTH) {\n return false;\n }\n\n // Only alphanumeric, dash, underscore (no shell metacharacters)\n if (!/^[a-z0-9_-]+$/i.test(command)) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Validate provider/agent name (prevent name injection)\n *\n * Security checks:\n * - Only alphanumeric, dash, underscore\n * - Must start with alphanumeric\n * - Reasonable length limit\n *\n * @param name - Name to validate\n * @returns true if name is valid\n *\n * @example\n * ```typescript\n * isValidName('backend') // ✅ true\n * isValidName('my-agent_v2') // ✅ true\n * isValidName('../../malicious') // ❌ false\n * isValidName('agent\\nmalicious: true') // ❌ false\n * ```\n */\nexport function isValidName(name: string): boolean {\n if (!name || typeof name !== 'string') {\n return false;\n }\n\n // Length check\n if (name.length > VALIDATION_LIMITS.MAX_NAME_LENGTH) {\n return false;\n }\n\n // Must start with alphanumeric, then can have dash/underscore\n if (!/^[a-z0-9][a-z0-9-_]*$/i.test(name)) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Validate file extension\n *\n * @param ext - Extension to validate (with or without leading dot)\n * @returns true if extension is valid\n */\nexport function isValidExtension(ext: string): boolean {\n if (!ext || typeof ext !== 'string') {\n return false;\n }\n\n // Ensure starts with dot\n const normalized = ext.startsWith('.') ? ext : `.${ext}`;\n\n // Reasonable length (e.g., .json, .yaml, .tsx)\n if (normalized.length > 10 || normalized.length < 2) {\n return false;\n }\n\n // Only alphanumeric after dot\n if (!/^\\.[a-z0-9]+$/i.test(normalized)) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Check if a number is a positive integer\n */\nexport function isPositiveInteger(value: any): value is number {\n return typeof value === 'number' &&\n Number.isInteger(value) &&\n value > 0;\n}\n\n/**\n * Check if a number is a non-negative integer (can be 0)\n */\nexport function isNonNegativeInteger(value: any): value is number {\n return typeof value === 'number' &&\n Number.isInteger(value) &&\n value >= 0;\n}\n\n/**\n * Check if value is within range (inclusive)\n */\nexport function inRange(value: number, min: number, max: number): boolean {\n return value >= min && value <= max;\n}\n\n/**\n * Sanitize error message for production (remove sensitive paths)\n *\n * @param message - Error message to sanitize\n * @param isProduction - Whether in production mode\n * @returns Sanitized message\n */\nexport function sanitizeErrorMessage(message: string, isProduction: boolean): string {\n if (!isProduction) {\n return message;\n }\n\n // Remove absolute paths\n message = message.replace(/\\/[^\\s]+\\//g, '<path>/');\n\n // Remove usernames\n message = message.replace(/\\/Users\\/[^/]+\\//g, '/Users/<user>/');\n message = message.replace(/\\/home\\/[^/]+\\//g, '/home/<user>/');\n message = message.replace(/C:\\\\Users\\\\[^\\\\]+\\\\/g, 'C:\\\\Users\\\\<user>\\\\');\n\n return message;\n}\n","/**\n * Advanced Caching System with TTL-based LRU eviction\n *\n * Features:\n * - Time-To-Live (TTL) expiration\n * - Least Recently Used (LRU) eviction\n * - Size limits\n * - Statistics tracking\n * - Automatic cleanup\n *\n * @module core/cache\n */\n\nimport { logger } from '../utils/logger.js';\n\n/**\n * Cache entry with metadata\n */\ninterface CacheEntry<T> {\n value: T;\n timestamp: number;\n hits: number;\n size: number; // Estimated size in bytes\n}\n\n/**\n * Cache statistics\n */\nexport interface CacheStats {\n hits: number;\n misses: number;\n sets: number;\n evictions: number;\n size: number;\n entries: number;\n hitRate: number;\n avgEntrySize: number;\n}\n\n/**\n * Cache configuration\n */\nexport interface CacheConfig {\n /** Maximum number of entries */\n maxEntries: number;\n /** Time-to-live in milliseconds (0 = no expiration) */\n ttl: number;\n /** Maximum cache size in bytes (0 = no limit) */\n maxSize?: number;\n /** Cleanup interval in milliseconds */\n cleanupInterval?: number;\n /** Enable debug logging */\n debug?: boolean;\n}\n\n/**\n * TTL-based LRU Cache\n *\n * Thread-safe caching with automatic expiration and eviction.\n *\n * @example\n * ```typescript\n * const cache = new TTLCache<string>({\n * maxEntries: 100,\n * ttl: 60000, // 1 minute\n * maxSize: 1024 * 1024 // 1MB\n * });\n *\n * cache.set('key', 'value');\n * const value = cache.get('key'); // 'value'\n *\n * // After 1 minute\n * cache.get('key'); // undefined (expired)\n * ```\n */\nexport class TTLCache<T> {\n private cache = new Map<string, CacheEntry<T>>();\n private config: Required<CacheConfig>;\n private stats = {\n hits: 0,\n misses: 0,\n sets: 0,\n evictions: 0\n };\n private cleanupTimer?: NodeJS.Timeout;\n private totalSize = 0;\n\n constructor(config: CacheConfig) {\n this.config = {\n maxEntries: config.maxEntries,\n ttl: config.ttl,\n maxSize: config.maxSize ?? 0,\n cleanupInterval: config.cleanupInterval ?? 60000, // 1 minute default\n debug: config.debug ?? false\n };\n\n // Start automatic cleanup\n if (this.config.cleanupInterval > 0) {\n this.startCleanup();\n }\n\n if (this.config.debug) {\n logger.debug('TTLCache initialized', {\n maxEntries: this.config.maxEntries,\n ttl: this.config.ttl,\n maxSize: this.config.maxSize,\n cleanupInterval: this.config.cleanupInterval\n });\n }\n }\n\n /**\n * Get value from cache\n *\n * @param key Cache key\n * @returns Cached value or undefined if not found/expired\n */\n get(key: string): T | undefined {\n const entry = this.cache.get(key);\n\n if (!entry) {\n this.stats.misses++;\n if (this.config.debug) {\n logger.debug('Cache miss', { key });\n }\n return undefined;\n }\n\n // Check if expired\n if (this.isExpired(entry)) {\n this.delete(key);\n this.stats.misses++;\n if (this.config.debug) {\n logger.debug('Cache expired', { key, age: Date.now() - entry.timestamp });\n }\n return undefined;\n }\n\n // Update LRU order (move to end)\n this.cache.delete(key);\n entry.hits++;\n this.cache.set(key, entry);\n\n this.stats.hits++;\n if (this.config.debug) {\n logger.debug('Cache hit', { key, hits: entry.hits });\n }\n\n return entry.value;\n }\n\n /**\n * Set value in cache\n *\n * @param key Cache key\n * @param value Value to cache\n * @param customTTL Optional custom TTL for this entry (ms)\n */\n set(key: string, value: T, customTTL?: number): void {\n const size = this.estimateSize(value);\n\n // Check size limit\n if (this.config.maxSize > 0 && size > this.config.maxSize) {\n logger.warn('Entry too large for cache', {\n key,\n size,\n maxSize: this.config.maxSize\n });\n return;\n }\n\n // Remove existing entry if present\n const existing = this.cache.get(key);\n if (existing) {\n this.totalSize -= existing.size;\n }\n\n // Evict entries if needed\n this.evictIfNeeded(size);\n\n // Create entry\n const entry: CacheEntry<T> = {\n value,\n timestamp: Date.now(),\n hits: 0,\n size\n };\n\n this.cache.set(key, entry);\n this.totalSize += size;\n this.stats.sets++;\n\n if (this.config.debug) {\n logger.debug('Cache set', {\n key,\n size,\n totalSize: this.totalSize,\n entries: this.cache.size\n });\n }\n }\n\n /**\n * Check if key exists and is not expired\n */\n has(key: string): boolean {\n const entry = this.cache.get(key);\n if (!entry) return false;\n if (this.isExpired(entry)) {\n this.delete(key);\n return false;\n }\n return true;\n }\n\n /**\n * Delete entry from cache\n */\n delete(key: string): boolean {\n const entry = this.cache.get(key);\n if (entry) {\n this.totalSize -= entry.size;\n this.cache.delete(key);\n return true;\n }\n return false;\n }\n\n /**\n * Clear all entries\n */\n clear(): void {\n this.cache.clear();\n this.totalSize = 0;\n if (this.config.debug) {\n logger.debug('Cache cleared');\n }\n }\n\n /**\n * Get cache statistics\n */\n getStats(): CacheStats {\n const total = this.stats.hits + this.stats.misses;\n return {\n hits: this.stats.hits,\n misses: this.stats.misses,\n sets: this.stats.sets,\n evictions: this.stats.evictions,\n size: this.totalSize,\n entries: this.cache.size,\n hitRate: total > 0 ? this.stats.hits / total : 0,\n avgEntrySize: this.cache.size > 0 ? this.totalSize / this.cache.size : 0\n };\n }\n\n /**\n * Reset statistics\n */\n resetStats(): void {\n this.stats = {\n hits: 0,\n misses: 0,\n sets: 0,\n evictions: 0\n };\n }\n\n /**\n * Get all keys\n */\n keys(): string[] {\n return Array.from(this.cache.keys());\n }\n\n /**\n * Get number of entries\n */\n get size(): number {\n return this.cache.size;\n }\n\n /**\n * Destroy cache and stop cleanup\n */\n destroy(): void {\n this.stopCleanup();\n this.clear();\n }\n\n /**\n * Check if entry is expired\n */\n private isExpired(entry: CacheEntry<T>): boolean {\n if (this.config.ttl === 0) return false;\n return Date.now() - entry.timestamp > this.config.ttl;\n }\n\n /**\n * Evict entries if needed to make room\n */\n private evictIfNeeded(newEntrySize: number): void {\n // Evict by entry count\n while (this.cache.size >= this.config.maxEntries) {\n this.evictOldest();\n }\n\n // Evict by size\n if (this.config.maxSize > 0) {\n while (\n this.totalSize + newEntrySize > this.config.maxSize &&\n this.cache.size > 0\n ) {\n this.evictOldest();\n }\n }\n }\n\n /**\n * Evict the oldest (LRU) entry\n */\n private evictOldest(): void {\n const firstKey = this.cache.keys().next().value;\n if (firstKey) {\n const entry = this.cache.get(firstKey);\n if (entry) {\n this.totalSize -= entry.size;\n }\n this.cache.delete(firstKey);\n this.stats.evictions++;\n\n if (this.config.debug) {\n logger.debug('Cache eviction (LRU)', {\n key: firstKey,\n entries: this.cache.size,\n totalSize: this.totalSize\n });\n }\n }\n }\n\n /**\n * Estimate size of value in bytes\n */\n private estimateSize(value: T): number {\n // Simple estimation based on JSON serialization\n // This is approximate but good enough for cache management\n try {\n const json = JSON.stringify(value);\n return json.length * 2; // ~2 bytes per character (UTF-16)\n } catch {\n // Fallback for non-serializable objects\n return 1024; // 1KB default\n }\n }\n\n /**\n * Start automatic cleanup timer\n */\n private startCleanup(): void {\n this.cleanupTimer = setInterval(() => {\n this.cleanup();\n }, this.config.cleanupInterval);\n\n // Don't prevent process exit\n if (this.cleanupTimer.unref) {\n this.cleanupTimer.unref();\n }\n }\n\n /**\n * Stop automatic cleanup timer\n */\n private stopCleanup(): void {\n if (this.cleanupTimer) {\n clearInterval(this.cleanupTimer);\n this.cleanupTimer = undefined;\n }\n }\n\n /**\n * Clean up expired entries\n */\n private cleanup(): void {\n const before = this.cache.size;\n let expired = 0;\n\n for (const [key, entry] of this.cache.entries()) {\n if (this.isExpired(entry)) {\n this.delete(key);\n expired++;\n }\n }\n\n if (this.config.debug && expired > 0) {\n logger.debug('Cache cleanup', {\n expired,\n before,\n after: this.cache.size,\n totalSize: this.totalSize\n });\n }\n }\n}\n\n/**\n * Provider response cache with intelligent invalidation\n *\n * Caches provider responses based on content hash to avoid\n * redundant API calls for identical requests.\n */\nexport class ProviderResponseCache {\n private cache: TTLCache<{\n response: string;\n usage?: {\n inputTokens: number;\n outputTokens: number;\n totalTokens: number;\n };\n }>;\n\n constructor(config?: Partial<CacheConfig>) {\n this.cache = new TTLCache({\n maxEntries: config?.maxEntries ?? 100,\n ttl: config?.ttl ?? 300000, // 5 minutes default\n maxSize: config?.maxSize ?? 10 * 1024 * 1024, // 10MB default\n cleanupInterval: config?.cleanupInterval ?? 60000,\n debug: config?.debug ?? false\n });\n }\n\n /**\n * Generate cache key from request parameters\n */\n private getCacheKey(\n provider: string,\n model: string,\n messages: any[],\n options?: Record<string, any>\n ): string {\n const payload = {\n provider,\n model,\n messages,\n options: options ?? {}\n };\n // Use JSON stringify for content-based hashing\n return this.hashString(JSON.stringify(payload));\n }\n\n /**\n * Simple string hash function\n */\n private hashString(str: string): string {\n let hash = 0;\n for (let i = 0; i < str.length; i++) {\n const char = str.charCodeAt(i);\n hash = (hash << 5) - hash + char;\n hash = hash & hash; // Convert to 32bit integer\n }\n return `cache_${Math.abs(hash).toString(36)}`;\n }\n\n /**\n * Get cached response\n */\n get(\n provider: string,\n model: string,\n messages: any[],\n options?: Record<string, any>\n ): { response: string; usage?: any } | undefined {\n const key = this.getCacheKey(provider, model, messages, options);\n return this.cache.get(key);\n }\n\n /**\n * Cache provider response\n */\n set(\n provider: string,\n model: string,\n messages: any[],\n response: string,\n options?: Record<string, any>,\n usage?: any\n ): void {\n const key = this.getCacheKey(provider, model, messages, options);\n this.cache.set(key, { response, usage });\n }\n\n /**\n * Get cache statistics\n */\n getStats(): CacheStats {\n return this.cache.getStats();\n }\n\n /**\n * Clear cache\n */\n clear(): void {\n this.cache.clear();\n }\n\n /**\n * Destroy cache\n */\n destroy(): void {\n this.cache.destroy();\n }\n}\n","/**\n * Init Command - Initialize AutomatosX project\n */\n\nimport type { CommandModule } from 'yargs';\nimport { mkdir, writeFile, access } from 'fs/promises';\nimport { resolve, join, dirname } from 'path';\nimport { fileURLToPath } from 'url';\nimport { constants } from 'fs';\nimport chalk from 'chalk';\nimport { DEFAULT_CONFIG } from '../../types/config.js';\nimport type { AutomatosXConfig } from '../../types/config.js';\nimport { logger } from '../../utils/logger.js';\nimport { printError } from '../../utils/error-formatter.js';\n\n// Get the directory of this file for locating examples\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\n// Get package root - handle both dev (src/) and prod (dist/) scenarios\nfunction getPackageRoot(): string {\n const currentDir = __dirname;\n if (currentDir.includes('/dist')) {\n // Production: dist/index.js -> go up one level to package root\n return join(currentDir, '..');\n } else {\n // Development: src/cli/commands/init.ts -> go up three levels to package root\n return join(currentDir, '../../..');\n }\n}\n\ninterface InitOptions {\n force?: boolean;\n path?: string;\n}\n\nexport const initCommand: CommandModule<Record<string, unknown>, InitOptions> = {\n command: 'init [path]',\n describe: 'Initialize AutomatosX in current or specified directory',\n\n builder: (yargs) => {\n return yargs\n .positional('path', {\n describe: 'Project directory (defaults to current directory)',\n type: 'string',\n default: '.'\n })\n .option('force', {\n alias: 'f',\n describe: 'Force initialization even if .automatosx already exists',\n type: 'boolean',\n default: false\n });\n },\n\n handler: async (argv) => {\n const projectDir = resolve(argv.path || '.');\n const automatosxDir = join(projectDir, '.automatosx');\n\n console.log(chalk.blue.bold('\\n🤖 AutomatosX v4.0 - Project Initialization\\n'));\n\n try {\n // Check if already initialized\n const exists = await checkExists(automatosxDir);\n if (exists && !argv.force) {\n console.log(chalk.yellow('⚠️ AutomatosX is already initialized in this directory'));\n console.log(chalk.gray(` ${automatosxDir}`));\n console.log(chalk.gray('\\n Use --force to reinitialize\\n'));\n process.exit(1);\n }\n\n if (exists && argv.force) {\n console.log(chalk.yellow('⚠️ Reinitializing (--force flag detected)'));\n }\n\n // Create directory structure\n console.log(chalk.cyan('📁 Creating directory structure...'));\n await createDirectoryStructure(automatosxDir);\n console.log(chalk.green(' ✓ Directories created'));\n\n // Copy example agents\n console.log(chalk.cyan('🤖 Installing example agents...'));\n await copyExampleAgents(automatosxDir);\n console.log(chalk.green(' ✓ 5 example agents installed'));\n\n // Copy example abilities\n console.log(chalk.cyan('⚡ Installing example abilities...'));\n await copyExampleAbilities(automatosxDir);\n console.log(chalk.green(' ✓ 15 example abilities installed'));\n\n // Copy agent templates (v5.0+)\n console.log(chalk.cyan('📋 Installing agent templates...'));\n await copyExampleTemplates(automatosxDir);\n console.log(chalk.green(' ✓ 5 agent templates installed'));\n\n // Create default config\n console.log(chalk.cyan('⚙️ Generating configuration...'));\n const configPath = join(projectDir, 'automatosx.config.json');\n await createDefaultConfig(configPath, argv.force ?? false);\n console.log(chalk.green(' ✓ Configuration created'));\n\n // Setup Claude Code integration\n console.log(chalk.cyan('🔌 Setting up Claude Code integration...'));\n await setupClaudeIntegration(projectDir);\n console.log(chalk.green(' ✓ Claude Code integration configured'));\n\n // Create .gitignore entry\n console.log(chalk.cyan('📝 Updating .gitignore...'));\n await updateGitignore(projectDir);\n console.log(chalk.green(' ✓ .gitignore updated'));\n\n // Success message\n console.log(chalk.green.bold('\\n✅ AutomatosX initialized successfully!\\n'));\n console.log(chalk.gray('Next steps:'));\n console.log(chalk.gray(' 1. Review automatosx.config.json'));\n console.log(chalk.gray(' 2. Explore example agents: automatosx list agents'));\n console.log(chalk.gray(' 3. Run an agent: automatosx run assistant \"Hello!\"\\n'));\n console.log(chalk.cyan('Available example agents:'));\n console.log(chalk.gray(' • assistant - General purpose helper'));\n console.log(chalk.gray(' • coder - Code generation specialist'));\n console.log(chalk.gray(' • reviewer - Code review expert'));\n console.log(chalk.gray(' • debugger - Debug assistance'));\n console.log(chalk.gray(' • writer - Content creation\\n'));\n console.log(chalk.cyan('Claude Code Integration:'));\n console.log(chalk.gray(' • Use /ax command in Claude Code'));\n console.log(chalk.gray(' • Example: /ax assistant \"Explain this code\"'));\n console.log(chalk.gray(' • MCP tools available in .claude/mcp/\\n'));\n\n logger.info('AutomatosX initialized', { projectDir, automatosxDir });\n\n } catch (error) {\n printError(error, {\n verbose: false,\n showCode: true,\n showSuggestions: true,\n colors: true\n });\n logger.error('Initialization failed', { error: (error as Error).message });\n process.exit(1);\n }\n }\n};\n\n/**\n * Check if path exists\n */\nasync function checkExists(path: string): Promise<boolean> {\n try {\n await access(path, constants.F_OK);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Create AutomatosX directory structure\n */\nasync function createDirectoryStructure(baseDir: string): Promise<void> {\n const dirs = [\n baseDir,\n join(baseDir, 'agents'),\n join(baseDir, 'teams'),\n join(baseDir, 'abilities'),\n join(baseDir, 'templates'), // v5.0: Agent templates\n join(baseDir, 'memory'),\n join(baseDir, 'workspaces'),\n join(baseDir, 'logs')\n ];\n\n for (const dir of dirs) {\n await mkdir(dir, { recursive: true });\n }\n}\n\n/**\n * Copy example agents to user's .automatosx directory\n */\nasync function copyExampleAgents(baseDir: string): Promise<void> {\n const { readdir, copyFile } = await import('fs/promises');\n\n const examplesDir = join(getPackageRoot(), 'examples/agents');\n const targetDir = join(baseDir, 'agents');\n\n try {\n const files = await readdir(examplesDir);\n for (const file of files) {\n if (file.endsWith('.yaml')) {\n await copyFile(join(examplesDir, file), join(targetDir, file));\n }\n }\n } catch (error) {\n logger.warn('Could not copy example agents', { error: (error as Error).message });\n }\n}\n\n/**\n * Copy example abilities to user's .automatosx directory\n */\nasync function copyExampleAbilities(baseDir: string): Promise<void> {\n const { readdir, copyFile } = await import('fs/promises');\n\n const examplesDir = join(getPackageRoot(), 'examples/abilities');\n const targetDir = join(baseDir, 'abilities');\n\n try {\n const files = await readdir(examplesDir);\n for (const file of files) {\n if (file.endsWith('.md')) {\n await copyFile(join(examplesDir, file), join(targetDir, file));\n }\n }\n } catch (error) {\n logger.warn('Could not copy example abilities', { error: (error as Error).message });\n }\n}\n\n/**\n * Copy agent templates to user's .automatosx directory (v5.0+)\n */\nasync function copyExampleTemplates(baseDir: string): Promise<void> {\n const { readdir, copyFile } = await import('fs/promises');\n\n const examplesDir = join(getPackageRoot(), 'examples/templates');\n const targetDir = join(baseDir, 'templates');\n\n try {\n const files = await readdir(examplesDir);\n for (const file of files) {\n if (file.endsWith('.yaml')) {\n await copyFile(join(examplesDir, file), join(targetDir, file));\n }\n }\n } catch (error) {\n logger.warn('Could not copy agent templates', { error: (error as Error).message });\n }\n}\n\n/**\n * Create default configuration file\n */\nasync function createDefaultConfig(\n configPath: string,\n force: boolean\n): Promise<void> {\n const exists = await checkExists(configPath);\n\n if (exists && !force) {\n return; // Don't overwrite existing config unless forced\n }\n\n const config = {\n ...DEFAULT_CONFIG,\n // Add metadata\n $schema: './schema/config.json',\n version: '5.0.0'\n };\n\n const content = JSON.stringify(config, null, 2);\n await writeFile(configPath, content, 'utf-8');\n}\n\n/**\n * Setup Claude Code integration files\n */\nasync function setupClaudeIntegration(projectDir: string): Promise<void> {\n const { readdir, copyFile } = await import('fs/promises');\n\n const examplesBaseDir = join(getPackageRoot(), 'examples/claude');\n\n // Create .claude directory structure\n const claudeDir = join(projectDir, '.claude');\n const commandsDir = join(claudeDir, 'commands');\n const mcpDir = join(claudeDir, 'mcp');\n\n await mkdir(commandsDir, { recursive: true });\n await mkdir(mcpDir, { recursive: true });\n\n try {\n // Copy slash command\n const commandsSourceDir = join(examplesBaseDir, 'commands');\n const commandFiles = await readdir(commandsSourceDir);\n for (const file of commandFiles) {\n if (file.endsWith('.md')) {\n await copyFile(join(commandsSourceDir, file), join(commandsDir, file));\n }\n }\n\n // Copy MCP configuration\n const mcpSourceDir = join(examplesBaseDir, 'mcp');\n const mcpFiles = await readdir(mcpSourceDir);\n for (const file of mcpFiles) {\n if (file.endsWith('.json')) {\n await copyFile(join(mcpSourceDir, file), join(mcpDir, file));\n }\n }\n } catch (error) {\n logger.warn('Could not copy Claude integration files', { error: (error as Error).message });\n }\n}\n\n/**\n * Update .gitignore with AutomatosX entries\n */\nasync function updateGitignore(projectDir: string): Promise<void> {\n const gitignorePath = join(projectDir, '.gitignore');\n\n const automatosxEntries = [\n '',\n '# AutomatosX',\n '.automatosx/memory/',\n '.automatosx/workspaces/',\n '.automatosx/logs/',\n 'automatosx.config.json # Optional: remove to track config',\n ''\n ].join('\\n');\n\n try {\n const exists = await checkExists(gitignorePath);\n\n if (exists) {\n // Append to existing .gitignore\n const { readFile } = await import('fs/promises');\n const content = await readFile(gitignorePath, 'utf-8');\n\n // Check if AutomatosX entries already exist\n if (content.includes('# AutomatosX')) {\n return; // Already exists\n }\n\n await writeFile(gitignorePath, content + automatosxEntries, 'utf-8');\n } else {\n // Create new .gitignore\n await writeFile(gitignorePath, automatosxEntries, 'utf-8');\n }\n } catch (error) {\n // Non-critical error, just log it\n logger.warn('Failed to update .gitignore', { error: (error as Error).message });\n }\n}\n","/**\n * List Command - List agents, abilities, or providers\n */\n\nimport type { CommandModule } from 'yargs';\nimport { readdir } from 'fs/promises';\nimport { join } from 'path';\nimport chalk from 'chalk';\nimport { logger } from '../../utils/logger.js';\nimport { PathResolver, detectProjectRoot } from '../../core/path-resolver.js';\n\ninterface ListOptions {\n type: 'agents' | 'abilities' | 'providers';\n}\n\nexport const listCommand: CommandModule<Record<string, unknown>, ListOptions> = {\n command: 'list <type>',\n describe: 'List available agents, abilities, or providers',\n\n builder: (yargs) => {\n return yargs\n .positional('type', {\n describe: 'What to list',\n type: 'string',\n choices: ['agents', 'abilities', 'providers'] as const,\n demandOption: true\n }) as any;\n },\n\n handler: async (argv) => {\n try {\n const projectDir = await detectProjectRoot();\n const pathResolver = new PathResolver({\n projectDir,\n workingDir: process.cwd(),\n agentWorkspace: join(projectDir, '.automatosx', 'workspaces')\n });\n\n switch (argv.type) {\n case 'agents':\n await listAgents(pathResolver);\n break;\n case 'abilities':\n await listAbilities(pathResolver);\n break;\n case 'providers':\n await listProviders();\n break;\n }\n\n } catch (error) {\n console.log(chalk.red.bold('\\n❌ Failed to list ' + argv.type + '\\n'));\n console.log(chalk.red((error as Error).message));\n logger.error('List command failed', { type: argv.type, error: (error as Error).message });\n process.exit(1);\n }\n }\n};\n\n/**\n * List available agents\n */\nasync function listAgents(pathResolver: PathResolver): Promise<void> {\n const agentsDir = pathResolver.getAgentsDirectory();\n const { existsSync } = await import('fs');\n const projectDir = await detectProjectRoot();\n const examplesDir = join(projectDir, 'examples', 'agents');\n\n try {\n // Collect agent files from both directories\n const agentFiles: Array<{ file: string; path: string; source: string }> = [];\n\n // Load from .automatosx/agents/\n if (existsSync(agentsDir)) {\n const files = await readdir(agentsDir);\n for (const file of files) {\n if (file.endsWith('.yaml') || file.endsWith('.yml')) {\n agentFiles.push({\n file,\n path: join(agentsDir, file),\n source: '.automatosx'\n });\n }\n }\n }\n\n // Load from examples/agents/\n if (existsSync(examplesDir)) {\n const files = await readdir(examplesDir);\n for (const file of files) {\n if (file.endsWith('.yaml') || file.endsWith('.yml')) {\n // Skip if already loaded from .automatosx (avoid duplicates)\n const alreadyLoaded = agentFiles.some(a => a.file === file);\n if (!alreadyLoaded) {\n agentFiles.push({\n file,\n path: join(examplesDir, file),\n source: 'examples'\n });\n }\n }\n }\n }\n\n if (agentFiles.length === 0) {\n console.log(chalk.yellow('\\n⚠️ No agents found\\n'));\n console.log(chalk.gray('Create agents in: ' + agentsDir));\n console.log(chalk.gray('Or run: automatosx init\\n'));\n return;\n }\n\n console.log(chalk.blue.bold('\\n🤖 Available Agents:\\n'));\n\n // Load and display each agent's info\n const { load } = await import('js-yaml');\n const { readFile } = await import('fs/promises');\n\n // Sort by name\n agentFiles.sort((a, b) => a.file.localeCompare(b.file));\n\n for (const { file, path: agentPath, source } of agentFiles) {\n try {\n const content = await readFile(agentPath, 'utf-8');\n const agent = load(content) as any;\n\n const name = agent.displayName || agent.name || file.replace(/\\.(yaml|yml)$/, '');\n const description = agent.description || 'No description';\n\n console.log(chalk.cyan(` • ${name}`) + chalk.gray(` (${source})`));\n console.log(chalk.gray(` ${description}`));\n\n if (agent.abilities && agent.abilities.length > 0) {\n console.log(chalk.gray(` Abilities: ${agent.abilities.join(', ')}`));\n }\n console.log();\n } catch (error) {\n console.log(chalk.yellow(` • ${file} (error loading)`) + chalk.gray(` (${source})`));\n console.log();\n }\n }\n\n console.log(chalk.gray(`Total: ${agentFiles.length} agent(s)\\n`));\n\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n console.log(chalk.yellow('\\n⚠️ Agents directory not found\\n'));\n console.log(chalk.gray('Run: automatosx init\\n'));\n } else {\n throw error;\n }\n }\n}\n\n/**\n * List available abilities\n */\nasync function listAbilities(pathResolver: PathResolver): Promise<void> {\n const abilitiesDir = pathResolver.getAbilitiesDirectory();\n\n try {\n const files = await readdir(abilitiesDir);\n const abilityFiles = files.filter(f => f.endsWith('.md'));\n\n if (abilityFiles.length === 0) {\n console.log(chalk.yellow('\\n⚠️ No abilities found\\n'));\n console.log(chalk.gray('Create abilities in: ' + abilitiesDir));\n console.log(chalk.gray('Or run: automatosx init\\n'));\n return;\n }\n\n console.log(chalk.blue.bold('\\n⚡ Available Abilities:\\n'));\n\n const { readFile } = await import('fs/promises');\n\n for (const file of abilityFiles.sort()) {\n const abilityPath = join(abilitiesDir, file);\n try {\n const content = await readFile(abilityPath, 'utf-8');\n\n // Extract title and description from markdown\n const lines = content.split('\\n');\n const titleLine = lines.find(l => l.startsWith('# '));\n const descLine = lines.find(l => l.startsWith('## Description'));\n const descIndex = lines.indexOf(descLine || '');\n\n const name = titleLine?.replace('# ', '') || file.replace('.md', '');\n const description = descIndex >= 0 ? lines[descIndex + 1]?.trim() || 'No description' : 'No description';\n\n console.log(chalk.cyan(` • ${name}`));\n console.log(chalk.gray(` ${description}`));\n console.log();\n } catch (error) {\n console.log(chalk.yellow(` • ${file} (error loading)`));\n console.log();\n }\n }\n\n console.log(chalk.gray(`Total: ${abilityFiles.length} ability(ies)\\n`));\n\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n console.log(chalk.yellow('\\n⚠️ Abilities directory not found\\n'));\n console.log(chalk.gray('Run: automatosx init\\n'));\n } else {\n throw error;\n }\n }\n}\n\n/**\n * List available providers\n */\nasync function listProviders(): Promise<void> {\n console.log(chalk.blue.bold('\\n🔌 Available Providers:\\n'));\n\n const providers = [\n {\n name: 'claude',\n description: 'Anthropic Claude (via CLI)',\n status: 'Available',\n capabilities: ['text-generation', 'conversation']\n },\n {\n name: 'gemini',\n description: 'Google Gemini (via CLI)',\n status: 'Available',\n capabilities: ['text-generation', 'conversation']\n },\n {\n name: 'openai-embed',\n description: 'OpenAI Embeddings (via CLI)',\n status: 'Available',\n capabilities: ['embeddings']\n }\n ];\n\n for (const provider of providers) {\n console.log(chalk.cyan(` • ${provider.name}`));\n console.log(chalk.gray(` ${provider.description}`));\n console.log(chalk.gray(` Status: ${provider.status}`));\n console.log(chalk.gray(` Capabilities: ${provider.capabilities.join(', ')}`));\n console.log();\n }\n\n console.log(chalk.gray(`Total: ${providers.length} provider(s)\\n`));\n}\n","/**\n * Memory CLI Commands\n */\n\nimport type { CommandModule } from 'yargs';\nimport { resolve } from 'path';\nimport { MemoryManager } from '../../core/memory-manager.js';\nimport chalk from 'chalk';\nimport Table from 'cli-table3';\nimport { printError } from '../../utils/error-formatter.js';\nimport { ProgressIndicator } from '../../utils/progress.js';\nimport { printSuccess } from '../../utils/message-formatter.js';\n\ninterface BaseMemoryArgs {\n db?: string;\n}\n\ninterface SearchArgs extends BaseMemoryArgs {\n query: string; // v4.11.0: Required, no vector file support\n limit?: number;\n threshold?: number;\n type?: string;\n tags?: string;\n output?: 'json' | 'table';\n}\n\ninterface ExportArgs extends BaseMemoryArgs {\n output: string;\n type?: string;\n from?: string;\n to?: string;\n // v4.11.0: includeEmbeddings removed (no embeddings in FTS5 mode)\n}\n\ninterface ImportArgs extends BaseMemoryArgs {\n input: string;\n validate?: boolean;\n batchSize?: number;\n skipDuplicates?: boolean;\n}\n\ninterface StatsArgs extends BaseMemoryArgs {\n output?: 'json' | 'table';\n}\n\ninterface ClearArgs extends BaseMemoryArgs {\n all?: boolean;\n type?: string;\n olderThan?: number;\n confirm?: boolean;\n}\n\nconst DEFAULT_DB_PATH = '.automatosx/memory/memory.db';\n\n/**\n * Get memory manager instance\n *\n * v4.11.0: No embedding provider needed (uses FTS5)\n */\nasync function getMemoryManager(dbPath?: string): Promise<MemoryManager> {\n const path = dbPath || DEFAULT_DB_PATH;\n\n return await MemoryManager.create({\n dbPath: resolve(path),\n maxEntries: 100000,\n autoCleanup: false,\n trackAccess: true\n });\n}\n\n/**\n * Memory search command\n *\n * v4.11.0: FTS5 full-text search only (no vector file support)\n */\nexport const searchCommand: CommandModule = {\n command: 'search <query>',\n describe: 'Search memory entries using full-text search',\n builder: (yargs) => {\n return (yargs as any).positional('query', {\n describe: 'Search query text (required)',\n type: 'string',\n demandOption: true\n })\n .option('limit', {\n alias: 'l',\n describe: 'Maximum number of results',\n type: 'number',\n default: 10\n })\n .option('threshold', {\n alias: 't',\n describe: 'Minimum similarity threshold (0-1)',\n type: 'number',\n default: 0\n })\n .option('type', {\n describe: 'Filter by entry type',\n type: 'string',\n choices: ['conversation', 'code', 'document', 'task', 'other']\n })\n .option('tags', {\n describe: 'Filter by tags (comma-separated)',\n type: 'string'\n })\n .option('output', {\n alias: 'o',\n describe: 'Output format',\n type: 'string',\n choices: ['json', 'table'],\n default: 'table'\n })\n .option('db', {\n describe: 'Database path',\n type: 'string'\n });\n },\n handler: async (argv: any) => {\n try {\n const manager = await getMemoryManager(argv.db);\n\n // Build search query (v4.11.0: FTS5 text search only)\n const searchQuery: any = {\n text: argv.query,\n limit: argv.limit,\n threshold: argv.threshold\n };\n\n // Add filters\n if (argv.type || argv.tags) {\n searchQuery.filters = {};\n if (argv.type) {\n searchQuery.filters.type = argv.type;\n }\n if (argv.tags) {\n searchQuery.filters.tags = argv.tags.split(',').map((t: string) => t.trim());\n }\n }\n\n // Execute search\n const results = await manager.search(searchQuery);\n\n // Output results\n if (argv.output === 'json') {\n console.log(JSON.stringify(results, null, 2));\n } else {\n if (results.length === 0) {\n console.log(chalk.yellow('\\n⚠ No matching entries found.'));\n } else {\n console.log(chalk.bold(`\\n🔍 Found ${results.length} matching entries:\\n`));\n\n const table = new Table({\n head: [\n chalk.cyan('ID'),\n chalk.cyan('Similarity'),\n chalk.cyan('Type'),\n chalk.cyan('Content'),\n chalk.cyan('Created')\n ],\n colWidths: [6, 12, 12, 60, 20],\n wordWrap: true\n });\n\n for (const result of results) {\n const content = result.entry.content.length > 57\n ? `${result.entry.content.substring(0, 57)}...`\n : result.entry.content;\n\n const similarity = `${(result.similarity * 100).toFixed(1)}%`;\n const similarityColored = result.similarity > 0.8 ? chalk.green(similarity) :\n result.similarity > 0.5 ? chalk.yellow(similarity) :\n chalk.red(similarity);\n\n table.push([\n chalk.white(result.entry.id.toString()),\n similarityColored,\n chalk.magenta(result.entry.metadata.type),\n chalk.white(content),\n chalk.gray(new Date(result.entry.createdAt).toLocaleString())\n ]);\n }\n\n console.log(table.toString());\n console.log();\n }\n }\n\n await manager.close();\n } catch (error) {\n printError(error, { verbose: false, showCode: true, showSuggestions: true, colors: true });\n process.exit(1);\n }\n }\n};\n\n/**\n * Memory export command\n */\nexport const exportCommand: CommandModule = {\n command: 'export <output>',\n describe: 'Export memory to JSON file',\n builder: (yargs) => {\n return yargs\n .positional('output', {\n describe: 'Output file path',\n type: 'string',\n demandOption: true\n })\n .option('type', {\n describe: 'Filter by entry type',\n type: 'string',\n choices: ['conversation', 'code', 'document', 'task', 'other']\n })\n .option('from', {\n describe: 'Start date (ISO format)',\n type: 'string'\n })\n .option('to', {\n describe: 'End date (ISO format)',\n type: 'string'\n })\n .option('db', {\n describe: 'Database path',\n type: 'string'\n });\n },\n handler: async (argv: any) => {\n try {\n const manager = await getMemoryManager(argv.db);\n\n // Build export options (v4.11.0: no embeddings in FTS5 mode)\n const exportOptions: any = {\n includeEmbeddings: false,\n pretty: true\n };\n\n // Add filters\n if (argv.type || argv.from || argv.to) {\n exportOptions.filters = {};\n\n if (argv.type) {\n exportOptions.filters.type = argv.type;\n }\n\n if (argv.from || argv.to) {\n exportOptions.filters.dateRange = {};\n if (argv.from) {\n exportOptions.filters.dateRange.from = new Date(argv.from);\n }\n if (argv.to) {\n exportOptions.filters.dateRange.to = new Date(argv.to);\n }\n }\n }\n\n // Execute export with progress\n const progress = new ProgressIndicator();\n progress.start('Exporting memory...');\n\n const result = await manager.exportToJSON(argv.output, exportOptions);\n\n progress.succeed('Export complete');\n\n console.log(`- Entries exported: ${result.entriesExported}`);\n console.log(`- File size: ${(result.sizeBytes / 1024).toFixed(2)} KB`);\n console.log(`- Output: ${result.filePath}`);\n\n await manager.close();\n } catch (error) {\n printError(error, { verbose: false, showCode: true, showSuggestions: true, colors: true });\n process.exit(1);\n }\n }\n};\n\n/**\n * Memory import command\n */\nexport const importCommand: CommandModule = {\n command: 'import <input>',\n describe: 'Import memory from JSON file',\n builder: (yargs) => {\n return yargs\n .positional('input', {\n describe: 'Input file path',\n type: 'string',\n demandOption: true\n })\n .option('validate', {\n describe: 'Validate entries before import',\n type: 'boolean',\n default: true\n })\n .option('batch-size', {\n describe: 'Batch size for processing',\n type: 'number',\n default: 100\n })\n .option('skip-duplicates', {\n describe: 'Skip duplicate entries',\n type: 'boolean',\n default: true\n })\n .option('db', {\n describe: 'Database path',\n type: 'string'\n });\n },\n handler: async (argv: any) => {\n try {\n const manager = await getMemoryManager(argv.db);\n\n const progress = new ProgressIndicator();\n progress.start('Importing memory...');\n\n const result = await manager.importFromJSON(argv.input, {\n skipDuplicates: argv.skipDuplicates,\n batchSize: argv.batchSize,\n validate: argv.validate\n });\n\n progress.succeed('Import complete');\n\n console.log(`- Entries imported: ${result.entriesImported}`);\n console.log(`- Entries skipped: ${result.entriesSkipped}`);\n console.log(`- Entries failed: ${result.entriesFailed}`);\n\n if (result.errors.length > 0) {\n console.log(`\\nErrors (${result.errors.length}):`);\n result.errors.slice(0, 5).forEach(e => {\n console.log(` - ${e.error}`);\n });\n }\n\n await manager.close();\n } catch (error) {\n printError(error, { verbose: false, showCode: true, showSuggestions: true, colors: true });\n process.exit(1);\n }\n }\n};\n\n/**\n * Memory add command\n */\nexport const addCommand: CommandModule = {\n command: 'add <content>',\n describe: 'Add a new memory entry',\n builder: (yargs) => {\n return yargs\n .positional('content', {\n describe: 'Content to store',\n type: 'string',\n demandOption: true\n })\n .option('type', {\n alias: 't',\n describe: 'Entry type',\n type: 'string',\n choices: ['conversation', 'code', 'document', 'task', 'other'],\n default: 'other'\n })\n .option('tags', {\n describe: 'Tags (comma-separated)',\n type: 'string'\n })\n .option('metadata', {\n alias: 'm',\n describe: 'Custom metadata as JSON string',\n type: 'string'\n })\n .option('db', {\n describe: 'Database path',\n type: 'string'\n });\n },\n handler: async (argv: any) => {\n try {\n const manager = await getMemoryManager(argv.db);\n\n // Build metadata\n const metadata: any = {\n type: argv.type,\n source: 'cli',\n timestamp: new Date().toISOString()\n };\n\n if (argv.tags) {\n metadata.tags = argv.tags.split(',').map((t: string) => t.trim());\n }\n\n // Parse custom metadata if provided\n if (argv.metadata) {\n try {\n const customMetadata = JSON.parse(argv.metadata);\n // Merge custom metadata, preserving required fields\n Object.assign(metadata, customMetadata);\n } catch (error) {\n throw new Error(`Invalid metadata JSON: ${(error as Error).message}`);\n }\n }\n\n // For CLI, we don't have an embedding provider by default\n // Use a zero vector as placeholder (will be updated later if needed)\n const embedding = new Array(1536).fill(0);\n\n const entry = await manager.add(argv.content, embedding, metadata);\n\n printSuccess('\\nMemory entry added successfully\\n');\n console.log(`${chalk.bold('ID:')} ${chalk.white(entry.id)}`);\n console.log(`${chalk.bold('Type:')} ${chalk.magenta(entry.metadata.type)}`);\n const content = entry.content.length > 100 ? `${entry.content.substring(0, 100)}...` : entry.content;\n console.log(`${chalk.bold('Content:')} ${chalk.white(content)}`);\n if (entry.metadata.tags && entry.metadata.tags.length > 0) {\n console.log(`${chalk.bold('Tags:')} ${chalk.yellow(entry.metadata.tags.join(', '))}`);\n }\n console.log();\n\n await manager.close();\n } catch (error) {\n printError(error, { verbose: false, showCode: true, showSuggestions: true, colors: true });\n process.exit(1);\n }\n }\n};\n\n/**\n * Memory delete command\n */\nexport const deleteCommand: CommandModule = {\n command: 'delete <id>',\n describe: 'Delete a memory entry by ID',\n builder: (yargs) => {\n return yargs\n .positional('id', {\n describe: 'Entry ID to delete',\n type: 'number',\n demandOption: true\n })\n .option('confirm', {\n alias: 'y',\n describe: 'Skip confirmation prompt',\n type: 'boolean',\n default: false\n })\n .option('db', {\n describe: 'Database path',\n type: 'string'\n });\n },\n handler: async (argv: any) => {\n try {\n const manager = await getMemoryManager(argv.db);\n\n // Get entry to show details\n const entry = await manager.get(argv.id);\n if (!entry) {\n console.error(chalk.red(`\\n✗ Entry not found: ${argv.id}\\n`));\n process.exit(1);\n }\n\n // Show entry details\n console.log(chalk.bold('\\n🗑️ Entry to delete:\\n'));\n console.log(`${chalk.bold('ID:')} ${chalk.white(entry.id)}`);\n console.log(`${chalk.bold('Type:')} ${chalk.magenta(entry.metadata.type)}`);\n const content = entry.content.length > 100 ? `${entry.content.substring(0, 100)}...` : entry.content;\n console.log(`${chalk.bold('Content:')} ${chalk.white(content)}`);\n\n // Confirm deletion (unless --confirm flag is used)\n if (!argv.confirm) {\n const { createInterface } = await import('readline');\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout\n });\n\n const answer = await new Promise<string>((resolve) => {\n rl.question(chalk.yellow('\\nAre you sure you want to delete this entry? (y/N): '), resolve);\n });\n rl.close();\n\n if (answer.toLowerCase() !== 'y' && answer.toLowerCase() !== 'yes') {\n console.log(chalk.gray('\\nDeletion cancelled.\\n'));\n await manager.close();\n return;\n }\n }\n\n await manager.delete(argv.id);\n printSuccess('\\nMemory entry deleted successfully\\n');\n\n await manager.close();\n } catch (error) {\n printError(error, { verbose: false, showCode: true, showSuggestions: true, colors: true });\n process.exit(1);\n }\n }\n};\n\n/**\n * Memory list command\n */\nexport const listCommand: CommandModule = {\n command: 'list',\n describe: 'List all memory entries',\n builder: (yargs) => {\n return (yargs as any).option('type', {\n describe: 'Filter by entry type',\n type: 'string',\n choices: ['conversation', 'code', 'document', 'task', 'other']\n })\n .option('tags', {\n describe: 'Filter by tags (comma-separated)',\n type: 'string'\n })\n .option('limit', {\n alias: 'l',\n describe: 'Maximum number of entries',\n type: 'number',\n default: 50\n })\n .option('offset', {\n describe: 'Number of entries to skip',\n type: 'number',\n default: 0\n })\n .option('order-by', {\n describe: 'Sort by field',\n type: 'string',\n choices: ['created', 'accessed', 'count'],\n default: 'created'\n })\n .option('order', {\n describe: 'Sort direction',\n type: 'string',\n choices: ['asc', 'desc'],\n default: 'desc'\n })\n .option('output', {\n alias: 'o',\n describe: 'Output format',\n type: 'string',\n choices: ['json', 'table'],\n default: 'table'\n })\n .option('db', {\n describe: 'Database path',\n type: 'string'\n });\n },\n handler: async (argv: any) => {\n try {\n const manager = await getMemoryManager(argv.db);\n\n const options: any = {\n limit: argv.limit,\n offset: argv.offset,\n orderBy: argv.orderBy,\n order: argv.order\n };\n\n if (argv.type) {\n options.type = argv.type;\n }\n\n if (argv.tags) {\n options.tags = argv.tags.split(',').map((t: string) => t.trim());\n }\n\n const entries = await manager.getAll(options);\n\n if (argv.output === 'json') {\n console.log(JSON.stringify(entries, null, 2));\n } else {\n if (entries.length === 0) {\n console.log(chalk.yellow('\\n⚠ No entries found.'));\n } else {\n console.log(chalk.bold(`\\n📚 Found ${entries.length} entries:\\n`));\n\n const table = new Table({\n head: [\n chalk.cyan('ID'),\n chalk.cyan('Type'),\n chalk.cyan('Content'),\n chalk.cyan('Tags'),\n chalk.cyan('Created'),\n chalk.cyan('Accessed')\n ],\n colWidths: [6, 12, 50, 20, 20, 10],\n wordWrap: true\n });\n\n for (const entry of entries) {\n const content = entry.content.length > 47\n ? `${entry.content.substring(0, 47)}...`\n : entry.content;\n\n const tags = entry.metadata.tags && entry.metadata.tags.length > 0\n ? entry.metadata.tags.join(', ')\n : chalk.gray('-');\n\n const created = new Date(entry.createdAt).toLocaleString();\n const accessCount = `${entry.accessCount || 0}x`;\n\n table.push([\n chalk.white(entry.id.toString()),\n chalk.magenta(entry.metadata.type),\n chalk.white(content),\n chalk.yellow(tags),\n chalk.gray(created),\n chalk.blue(accessCount)\n ]);\n }\n\n console.log(table.toString());\n\n // Show pagination info\n if (entries.length === argv.limit) {\n console.log(chalk.gray(`\\n💡 Showing ${argv.limit} entries. Use --offset to see more.\\n`));\n }\n }\n }\n\n await manager.close();\n } catch (error) {\n printError(error, { verbose: false, showCode: true, showSuggestions: true, colors: true });\n process.exit(1);\n }\n }\n};\n\n/**\n * Memory stats command\n */\nexport const statsCommand: CommandModule = {\n command: 'stats',\n describe: 'Show memory statistics',\n builder: (yargs) => {\n return (yargs as any).option('output', {\n alias: 'o',\n describe: 'Output format',\n type: 'string',\n choices: ['json', 'table'],\n default: 'table'\n })\n .option('db', {\n describe: 'Database path',\n type: 'string'\n });\n },\n handler: async (argv: any) => {\n try {\n const manager = await getMemoryManager(argv.db);\n const stats = await manager.getStats();\n\n if (argv.output === 'json') {\n console.log(JSON.stringify(stats, null, 2));\n } else {\n console.log('\\nMemory Statistics:');\n console.log(`- Total entries: ${stats.totalEntries}`);\n console.log(`- Database size: ${(stats.dbSize / 1024).toFixed(2)} KB`);\n console.log(`- Index size: ${(stats.indexSize / 1024).toFixed(2)} KB`);\n console.log(`- Memory usage: ${(stats.memoryUsage / 1024 / 1024).toFixed(2)} MB`);\n }\n\n await manager.close();\n } catch (error) {\n console.error('Stats failed:', (error as Error).message);\n process.exit(1);\n }\n }\n};\n\n/**\n * Memory clear command\n */\nexport const clearCommand: CommandModule = {\n command: 'clear',\n describe: 'Clear memory entries',\n builder: (yargs) => {\n return yargs\n .option('all', {\n describe: 'Clear all entries',\n type: 'boolean',\n default: false\n })\n .option('type', {\n describe: 'Clear specific entry type',\n type: 'string',\n choices: ['conversation', 'code', 'document', 'task', 'other']\n })\n .option('older-than', {\n describe: 'Clear entries older than N days',\n type: 'number'\n })\n .option('confirm', {\n alias: 'y',\n describe: 'Skip confirmation prompt',\n type: 'boolean',\n default: false\n })\n .option('db', {\n describe: 'Database path',\n type: 'string'\n })\n .check((argv) => {\n if (!argv.all && !argv.type && !argv.olderThan) {\n throw new Error('Must specify --all, --type, or --older-than');\n }\n return true;\n });\n },\n handler: async (argv: any) => {\n try {\n const manager = await getMemoryManager(argv.db);\n\n // Get stats before clearing\n const statsBefore = await manager.getStats();\n\n // Confirm deletion\n if (!argv.confirm) {\n console.log(`\\nThis will delete entries from the memory database.`);\n console.log(`Current total: ${statsBefore.totalEntries} entries`);\n\n if (argv.all) {\n console.log('Action: Delete ALL entries');\n } else if (argv.type) {\n console.log(`Action: Delete entries of type \"${argv.type}\"`);\n } else if (argv.olderThan) {\n console.log(`Action: Delete entries older than ${argv.olderThan} days`);\n }\n\n console.log('\\nPress Ctrl+C to cancel, or use --confirm to skip this prompt');\n process.exit(0);\n }\n\n // Execute clear operation\n if (argv.all) {\n await manager.clear();\n console.log('\\n✓ All entries cleared');\n } else if (argv.olderThan) {\n const deleted = await manager.cleanup(argv.olderThan);\n console.log(`\\n✓ Deleted ${deleted} entries older than ${argv.olderThan} days`);\n } else {\n // Type-specific deletion (not implemented in current MemoryManager)\n console.error('Type-specific deletion not yet implemented');\n process.exit(1);\n }\n\n const statsAfter = await manager.getStats();\n console.log(`Remaining entries: ${statsAfter.totalEntries}`);\n\n await manager.close();\n } catch (error) {\n console.error('Clear failed:', (error as Error).message);\n process.exit(1);\n }\n }\n};\n\n/**\n * Main memory command\n */\nexport const memoryCommand: CommandModule = {\n command: 'memory <command>',\n describe: 'Memory management commands',\n builder: (yargs) => {\n return yargs\n .command(searchCommand)\n .command(listCommand)\n .command(addCommand)\n .command(deleteCommand)\n .command(exportCommand)\n .command(importCommand)\n .command(statsCommand)\n .command(clearCommand)\n .demandCommand(1, 'You must provide a memory command');\n },\n handler: () => {\n // Will be handled by sub-commands\n }\n};\n","/**\n * Memory Manager - SQLite + vec extension implementation\n *\n * This replaces the HNSW implementation with pure SQLite vector search\n * using the sqlite-vec extension for better portability and simpler deployment.\n */\n\nimport Database from 'better-sqlite3';\nimport * as sqliteVec from 'sqlite-vec';\nimport { existsSync, mkdirSync } from 'fs';\nimport { dirname } from 'path';\nimport type {\n IMemoryManager,\n MemoryEntry,\n MemoryMetadata,\n MemorySearchQuery,\n MemorySearchResult,\n MemoryManagerConfig,\n MemoryStats\n} from '../types/memory.js';\nimport { MemoryError } from '../types/memory.js';\nimport { logger } from '../utils/logger.js';\n\n// v4.11.0: VECTOR_DIMENSIONS removed (FTS5 only, no vector search)\n\n/**\n * Memory Manager using SQLite + FTS5 for full-text search\n *\n * Features:\n * - FTS5 full-text search (keyword matching)\n * - Optional vector search support (for Plus version)\n * - No embedding provider required\n * - Simple deployment\n * - Cross-platform compatibility\n *\n * v4.11.0: Removed embedding dependency, added FTS5 support\n */\nexport class MemoryManager implements IMemoryManager {\n private db: Database.Database;\n private config: Required<Omit<MemoryManagerConfig, 'embeddingProvider' | 'hnsw' | 'cleanup'>> & {\n embeddingProvider?: unknown;\n };\n private embeddingProvider?: any;\n private initialized: boolean = false;\n private useFTS: boolean = true; // Use FTS5 by default\n\n // Phase 1: Performance optimization\n private entryCount: number = 0; // Internal counter to avoid repeated COUNT(*)\n private statements: {\n countAll?: Database.Statement;\n insert?: Database.Statement;\n deleteById?: Database.Statement;\n deleteOldest?: Database.Statement;\n deleteBeforeCutoff?: Database.Statement;\n updateAccessCount?: Database.Statement;\n } = {}\n\n // Phase 2: Smart cleanup configuration\n private cleanupConfig: {\n enabled: boolean;\n strategy: 'oldest' | 'least_accessed' | 'hybrid';\n triggerThreshold: number;\n targetThreshold: number;\n minCleanupCount: number;\n maxCleanupCount: number;\n retentionDays: number;\n }\n\n private constructor(config: MemoryManagerConfig) {\n // Set default config\n this.config = {\n dbPath: config.dbPath,\n maxEntries: config.maxEntries ?? 10000,\n autoCleanup: config.autoCleanup ?? true,\n cleanupDays: config.cleanupDays ?? 30,\n trackAccess: config.trackAccess ?? true,\n embeddingProvider: config.embeddingProvider\n };\n\n this.embeddingProvider = config.embeddingProvider;\n\n // Phase 2: Initialize smart cleanup configuration with defaults\n const cleanupCfg = config.cleanup || {};\n\n // Handle backward compatibility: autoCleanup → cleanup.enabled\n const enabled = cleanupCfg.enabled ?? config.autoCleanup ?? true;\n\n // Handle backward compatibility: cleanupDays → cleanup.retentionDays\n const retentionDays = cleanupCfg.retentionDays ?? config.cleanupDays ?? 30;\n\n this.cleanupConfig = {\n enabled,\n strategy: cleanupCfg.strategy ?? 'oldest',\n triggerThreshold: cleanupCfg.triggerThreshold ?? 0.9,\n targetThreshold: cleanupCfg.targetThreshold ?? 0.7,\n minCleanupCount: cleanupCfg.minCleanupCount ?? 10,\n maxCleanupCount: cleanupCfg.maxCleanupCount ?? 1000,\n retentionDays\n };\n\n // Validate cleanup configuration\n this.validateCleanupConfig();\n\n // Ensure directory exists\n const dir = dirname(this.config.dbPath);\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n }\n\n // Initialize database\n this.db = new Database(this.config.dbPath);\n this.db.pragma('journal_mode = WAL');\n this.db.pragma('busy_timeout = 5000'); // Wait up to 5 seconds for locks\n }\n\n /**\n * Create MemoryManager instance (async factory)\n */\n static async create(config: MemoryManagerConfig): Promise<MemoryManager> {\n const manager = new MemoryManager(config);\n await manager.initialize();\n return manager;\n }\n\n /**\n * Initialize database and load FTS5 extension\n *\n * v4.11.0: Added FTS5 full-text search support\n */\n private async initialize(): Promise<void> {\n if (this.initialized) return;\n\n try {\n // Load sqlite-vec extension (for Plus version compatibility)\n try {\n sqliteVec.load(this.db);\n } catch (error) {\n // vec extension is optional (only needed for Plus version)\n logger.debug('sqlite-vec extension not loaded (not required for FTS5)', {\n error: (error as Error).message\n });\n }\n\n // Create tables\n // v4.11.0: Removed memory_vectors table (FTS5 only, no vector search)\n this.db.exec(`\n CREATE TABLE IF NOT EXISTS memory_entries (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n content TEXT NOT NULL,\n metadata TEXT NOT NULL,\n created_at INTEGER NOT NULL,\n last_accessed_at INTEGER,\n access_count INTEGER DEFAULT 0\n );\n\n CREATE INDEX IF NOT EXISTS idx_created_at ON memory_entries(created_at);\n CREATE INDEX IF NOT EXISTS idx_access_count ON memory_entries(access_count);\n `);\n\n // Create FTS5 virtual table for full-text search\n // v4.11.0: Removed external content to avoid trigger issues\n this.db.exec(`\n CREATE VIRTUAL TABLE IF NOT EXISTS memory_fts USING fts5(\n content,\n metadata\n );\n\n -- Triggers to keep FTS index in sync\n CREATE TRIGGER IF NOT EXISTS memory_fts_insert AFTER INSERT ON memory_entries BEGIN\n INSERT INTO memory_fts(rowid, content, metadata)\n VALUES (new.id, new.content, new.metadata);\n END;\n\n CREATE TRIGGER IF NOT EXISTS memory_fts_delete AFTER DELETE ON memory_entries BEGIN\n DELETE FROM memory_fts WHERE rowid = old.id;\n END;\n\n CREATE TRIGGER IF NOT EXISTS memory_fts_update AFTER UPDATE ON memory_entries BEGIN\n UPDATE memory_fts\n SET content = new.content, metadata = new.metadata\n WHERE rowid = old.id;\n END;\n `);\n\n // Phase 1: Prepare frequently-used statements for better performance\n this.statements.countAll = this.db.prepare('SELECT COUNT(*) as count FROM memory_entries');\n this.statements.insert = this.db.prepare(`\n INSERT INTO memory_entries (content, metadata, created_at, last_accessed_at, access_count)\n VALUES (?, ?, ?, ?, 0)\n `);\n this.statements.deleteById = this.db.prepare('DELETE FROM memory_entries WHERE id = ?');\n this.statements.deleteOldest = this.db.prepare(`\n DELETE FROM memory_entries\n WHERE id IN (\n SELECT id FROM memory_entries\n ORDER BY created_at ASC\n LIMIT ?\n )\n `);\n this.statements.deleteBeforeCutoff = this.db.prepare(`\n DELETE FROM memory_entries\n WHERE created_at < ?\n `);\n this.statements.updateAccessCount = this.db.prepare(`\n UPDATE memory_entries\n SET access_count = access_count + 1, last_accessed_at = ?\n WHERE id = ?\n `);\n\n // Initialize internal entry counter\n const countResult = this.statements.countAll.get() as { count: number };\n this.entryCount = countResult.count;\n\n this.initialized = true;\n logger.info('MemoryManager initialized successfully', {\n dbPath: this.config.dbPath,\n searchMethod: 'FTS5',\n hasEmbeddingProvider: !!this.embeddingProvider,\n entryCount: this.entryCount\n });\n } catch (error) {\n logger.error('Failed to initialize MemoryManager', { error: (error as Error).message });\n throw new MemoryError(\n `Failed to initialize memory system: ${(error as Error).message}`,\n 'DATABASE_ERROR'\n );\n }\n }\n\n /**\n * Add a new memory entry\n *\n * v4.11.0: Embedding is now optional (only needed for Plus version)\n * v5.0.9: Phase 1 - Transaction atomicity with prepared statements\n */\n async add(content: string, embedding: number[] | null, metadata: MemoryMetadata): Promise<MemoryEntry> {\n if (!this.initialized) {\n throw new MemoryError('Memory manager not initialized', 'DATABASE_ERROR');\n }\n\n // v4.11.0: Embedding validation removed (FTS5 only, no vector search)\n // Note: embedding parameter deprecated but kept for backward compatibility\n\n // Phase 2: Smart cleanup - check threshold before add\n if (this.shouldTriggerCleanup()) {\n try {\n const removed = await this.executeSmartCleanup();\n logger.info('Smart cleanup triggered', {\n removed,\n currentCount: this.entryCount,\n usage: (this.entryCount / this.config.maxEntries * 100).toFixed(1) + '%',\n threshold: (this.cleanupConfig.triggerThreshold * 100).toFixed(0) + '%',\n strategy: this.cleanupConfig.strategy\n });\n } catch (error) {\n logger.warn('Smart cleanup failed', {\n error: (error as Error).message\n });\n }\n }\n\n try {\n const now = Date.now();\n const metadataStr = JSON.stringify(metadata);\n\n // Phase 1.1: Transaction with proper counter synchronization\n // Return deletion count and ID, update counter AFTER transaction succeeds\n const insertTxn = this.db.transaction(() => {\n let deletedCount = 0;\n\n // v5.0.8: Enforce maxEntries limit inside transaction\n if (this.entryCount >= this.config.maxEntries) {\n // Auto-cleanup oldest entries to make room\n const entriesToRemove = Math.min(100, Math.floor(this.config.maxEntries * 0.1));\n const deleteInfo = this.statements.deleteOldest!.run(entriesToRemove);\n deletedCount = deleteInfo.changes;\n\n logger.warn('Memory limit approaching, auto-cleanup triggered', {\n currentCount: this.entryCount,\n maxEntries: this.config.maxEntries,\n removed: deletedCount\n });\n\n // Check if cleanup freed enough space\n if (this.entryCount - deletedCount >= this.config.maxEntries) {\n throw new MemoryError(\n `Memory limit reached (${this.config.maxEntries} entries). Run 'ax memory clear' or increase maxEntries in config.`,\n 'MEMORY_LIMIT'\n );\n }\n }\n\n // Insert entry using prepared statement (FTS5 index is automatically updated via trigger)\n const insertResult = this.statements.insert!.run(content, metadataStr, now, now);\n\n logger.debug('Memory entry added', {\n id: insertResult.lastInsertRowid,\n contentLength: content.length,\n searchMethod: 'FTS5',\n deletedCount\n });\n\n return { id: Number(insertResult.lastInsertRowid), deletedCount };\n });\n\n // Execute transaction and update counter ONLY on success\n const { id, deletedCount } = insertTxn();\n this.entryCount = this.entryCount - deletedCount + 1;\n\n // v4.11.0: No vector storage (FTS5 only)\n\n return {\n id,\n content,\n embedding: [], // v4.11.0: Always empty (FTS5 only)\n metadata,\n createdAt: new Date(now),\n accessCount: 0\n };\n } catch (error) {\n throw new MemoryError(\n `Failed to add memory entry: ${(error as Error).message}`,\n 'DATABASE_ERROR'\n );\n }\n }\n\n /**\n * Search for memories using FTS5 full-text search\n *\n * v4.11.0: Changed from vector search to FTS5 keyword search\n */\n async search(query: MemorySearchQuery): Promise<MemorySearchResult[]> {\n if (!this.initialized) {\n throw new MemoryError('Memory manager not initialized', 'DATABASE_ERROR');\n }\n\n // Use FTS5 for text search (no embedding needed)\n if (!query.text) {\n throw new MemoryError(\n 'Search query must provide text for FTS5 search',\n 'QUERY_ERROR'\n );\n }\n\n try {\n const limit = query.limit || 10;\n\n // Build metadata filter conditions\n const conditions: string[] = [];\n const params: unknown[] = [];\n\n // Apply metadata filters\n if (query.filters) {\n if (query.filters.type) {\n const types = Array.isArray(query.filters.type) ? query.filters.type : [query.filters.type];\n conditions.push(`json_extract(e.metadata, '$.type') IN (${types.map(() => '?').join(',')})`);\n params.push(...types);\n }\n\n if (query.filters.source) {\n const sources = Array.isArray(query.filters.source) ? query.filters.source : [query.filters.source];\n conditions.push(`json_extract(e.metadata, '$.source') IN (${sources.map(() => '?').join(',')})`);\n params.push(...sources);\n }\n\n if (query.filters.agentId) {\n conditions.push(`json_extract(e.metadata, '$.agentId') = ?`);\n params.push(query.filters.agentId);\n }\n\n if (query.filters.sessionId) {\n conditions.push(`json_extract(e.metadata, '$.sessionId') = ?`);\n params.push(query.filters.sessionId);\n }\n\n if (query.filters.tags && query.filters.tags.length > 0) {\n // Check if all required tags are present (AND logic)\n query.filters.tags.forEach(tag => {\n conditions.push(`EXISTS (SELECT 1 FROM json_each(e.metadata, '$.tags') WHERE value = ?)`);\n params.push(tag);\n });\n }\n\n if (query.filters.dateRange?.from) {\n conditions.push('e.created_at >= ?');\n params.push(query.filters.dateRange.from.getTime());\n }\n\n if (query.filters.dateRange?.to) {\n conditions.push('e.created_at <= ?');\n params.push(query.filters.dateRange.to.getTime());\n }\n\n if (query.filters.minImportance !== undefined) {\n conditions.push(`CAST(json_extract(e.metadata, '$.importance') AS REAL) >= ?`);\n params.push(query.filters.minImportance);\n }\n }\n\n // Build WHERE clause for metadata filters\n const metadataWhere = conditions.length > 0 ? ` AND ${conditions.join(' AND ')}` : '';\n\n // Use FTS5 MATCH for full-text search\n // FTS5 returns results sorted by relevance (rank)\n const sql = `\n SELECT\n e.id,\n e.content,\n e.metadata,\n e.created_at,\n e.last_accessed_at,\n e.access_count,\n bm25(memory_fts) as relevance\n FROM memory_fts\n JOIN memory_entries e ON memory_fts.rowid = e.id\n WHERE memory_fts MATCH ?${metadataWhere}\n ORDER BY bm25(memory_fts)\n LIMIT ?\n `;\n\n // FTS5 query syntax: escape special characters and use simple query\n // Remove FTS5 special characters that can cause syntax errors\n // Special chars: . : \" * ( ) [ ] { } ^ $ + | \\ - % < > ~ / @ # & = ? ! ; ' ` , AND OR NOT\n const ftsQuery = query.text\n .replace(/[.:\"*()[\\]{}^$+|\\\\%<>~\\-/@#&=?!;'`,]/g, ' ') // Replace special chars with spaces\n .replace(/\\b(AND|OR|NOT)\\b/gi, ' ') // Remove boolean operators\n .replace(/\\s+/g, ' ') // Normalize whitespace\n .trim();\n\n // If query becomes empty after sanitization, return empty results\n if (!ftsQuery) {\n logger.debug('FTS5 query empty after sanitization', { originalQuery: query.text });\n return [];\n }\n\n const finalParams = [ftsQuery, ...params, limit];\n\n const results = this.db.prepare(sql).all(...finalParams) as any[];\n\n // Phase 1.1: Update access tracking with batch UPDATE for atomicity and performance\n // Note: Cannot use prepared statement here due to dynamic IN (?) clause\n if (this.config.trackAccess && results.length > 0) {\n const now = Date.now();\n const ids = results.map(r => r.id);\n const placeholders = ids.map(() => '?').join(',');\n\n // Batch update: all succeed or all fail (atomic), much faster than N individual updates\n this.db.prepare(`\n UPDATE memory_entries\n SET last_accessed_at = ?, access_count = access_count + 1\n WHERE id IN (${placeholders})\n `).run(now, ...ids);\n }\n\n return results.map(row => {\n // FTS5 rank is negative (higher rank = more relevant)\n // Convert to similarity score (0-1, higher is better)\n const similarity = Math.max(0, Math.min(1, 1 + (row.relevance / 10)));\n\n return {\n entry: {\n id: row.id,\n content: row.content,\n embedding: [], // No embedding in FTS5 mode\n metadata: JSON.parse(row.metadata),\n createdAt: new Date(row.created_at),\n lastAccessedAt: row.last_accessed_at ? new Date(row.last_accessed_at) : undefined,\n accessCount: row.access_count\n },\n similarity,\n distance: 1 - similarity\n };\n });\n } catch (error) {\n throw new MemoryError(\n `Search failed: ${(error as Error).message}`,\n 'QUERY_ERROR'\n );\n }\n }\n\n /**\n * Get memory by ID\n *\n * v4.11.0: No vector loading (FTS5 only)\n */\n async get(id: number): Promise<MemoryEntry | null> {\n if (!this.initialized) {\n throw new MemoryError('Memory manager not initialized', 'DATABASE_ERROR');\n }\n\n try {\n // v4.11.0: No JOIN with memory_vectors (FTS5 only)\n const row = this.db.prepare(`\n SELECT *\n FROM memory_entries\n WHERE id = ?\n `).get(id) as any;\n\n if (!row) return null;\n\n return {\n id: row.id,\n content: row.content,\n embedding: [], // No embedding in FTS5 mode\n metadata: JSON.parse(row.metadata),\n createdAt: new Date(row.created_at),\n lastAccessedAt: row.last_accessed_at ? new Date(row.last_accessed_at) : undefined,\n accessCount: row.access_count\n };\n } catch (error) {\n throw new MemoryError(\n `Failed to get entry: ${(error as Error).message}`,\n 'DATABASE_ERROR'\n );\n }\n }\n\n /**\n * Update memory metadata\n */\n async update(id: number, metadata: Partial<MemoryMetadata>): Promise<void> {\n if (!this.initialized) {\n throw new MemoryError('Memory manager not initialized', 'DATABASE_ERROR');\n }\n\n try {\n // Get existing entry\n const existing = await this.get(id);\n if (!existing) {\n throw new MemoryError(`Memory entry not found: ${id}`, 'ENTRY_NOT_FOUND');\n }\n\n // Merge metadata\n const newMetadata = { ...existing.metadata, ...metadata };\n\n this.db.prepare(`\n UPDATE memory_entries\n SET metadata = ?\n WHERE id = ?\n `).run(JSON.stringify(newMetadata), id);\n\n logger.debug('Memory entry updated', { id });\n } catch (error) {\n if (error instanceof MemoryError) throw error;\n throw new MemoryError(\n `Failed to update entry: ${(error as Error).message}`,\n 'DATABASE_ERROR'\n );\n }\n }\n\n /**\n * Delete memory by ID\n */\n async delete(id: number): Promise<void> {\n if (!this.initialized) {\n throw new MemoryError('Memory manager not initialized', 'DATABASE_ERROR');\n }\n\n try {\n // Check if entry exists\n const existing = await this.get(id);\n if (!existing) {\n throw new MemoryError(`Memory entry not found: ${id}`, 'ENTRY_NOT_FOUND');\n }\n\n // Phase 1: Use prepared statement and maintain entryCount\n const deleteInfo = this.statements.deleteById!.run(id);\n if (deleteInfo.changes > 0) {\n this.entryCount -= deleteInfo.changes;\n }\n\n logger.debug('Memory entry deleted', { id, newCount: this.entryCount });\n } catch (error) {\n if (error instanceof MemoryError) throw error;\n throw new MemoryError(\n `Failed to delete entry: ${(error as Error).message}`,\n 'DATABASE_ERROR'\n );\n }\n }\n\n /**\n * Get all memory entries with optional filtering and pagination\n */\n async getAll(options?: {\n type?: string;\n tags?: string[];\n limit?: number;\n offset?: number;\n orderBy?: 'created' | 'accessed' | 'count';\n order?: 'asc' | 'desc';\n }): Promise<MemoryEntry[]> {\n if (!this.initialized) {\n throw new MemoryError('Memory manager not initialized', 'DATABASE_ERROR');\n }\n\n try {\n const conditions: string[] = [];\n const params: any[] = [];\n\n // Build WHERE clause with filters\n if (options?.type) {\n conditions.push(\"json_extract(e.metadata, '$.type') = ?\");\n params.push(options.type);\n }\n\n if (options?.tags && options.tags.length > 0) {\n // Check if any of the provided tags exist in the entry's tags array\n const tagConditions = options.tags.map(() =>\n \"EXISTS (SELECT 1 FROM json_each(json_extract(e.metadata, '$.tags')) WHERE value = ?)\"\n );\n conditions.push(`(${tagConditions.join(' OR ')})`);\n params.push(...options.tags);\n }\n\n const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';\n\n // Build ORDER BY clause\n let orderByClause = 'ORDER BY e.created_at DESC';\n if (options?.orderBy) {\n const column = options.orderBy === 'created' ? 'e.created_at' :\n options.orderBy === 'accessed' ? 'e.last_accessed_at' :\n 'e.access_count';\n const direction = options.order || 'desc';\n orderByClause = `ORDER BY ${column} ${direction.toUpperCase()}`;\n }\n\n // Build LIMIT clause\n const limitClause = options?.limit ? `LIMIT ${options.limit}` : '';\n const offsetClause = options?.offset ? `OFFSET ${options.offset}` : '';\n\n // v4.11.0: No JOIN with memory_vectors (FTS5 only)\n const sql = `\n SELECT e.*\n FROM memory_entries e\n ${whereClause}\n ${orderByClause}\n ${limitClause}\n ${offsetClause}\n `;\n\n const rows = this.db.prepare(sql).all(...params) as any[];\n\n return rows.map(row => {\n return {\n id: row.id,\n content: row.content,\n embedding: [], // No embedding in FTS5 mode\n metadata: JSON.parse(row.metadata),\n createdAt: new Date(row.created_at),\n lastAccessedAt: row.last_accessed_at ? new Date(row.last_accessed_at) : undefined,\n accessCount: row.access_count\n };\n });\n } catch (error) {\n throw new MemoryError(\n `Failed to retrieve entries: ${(error as Error).message}`,\n 'DATABASE_ERROR'\n );\n }\n }\n\n /**\n * Clear all memories\n */\n async clear(): Promise<void> {\n if (!this.initialized) {\n throw new MemoryError('Memory manager not initialized', 'DATABASE_ERROR');\n }\n\n try {\n this.db.prepare('DELETE FROM memory_entries').run();\n // Phase 1: Reset internal counter\n this.entryCount = 0;\n\n this.db.prepare('VACUUM').run();\n logger.info('All memory entries cleared');\n } catch (error) {\n throw new MemoryError(\n `Failed to clear entries: ${(error as Error).message}`,\n 'DATABASE_ERROR'\n );\n }\n }\n\n /**\n * Get memory statistics\n */\n async getStats(): Promise<MemoryStats> {\n if (!this.initialized) {\n throw new MemoryError('Memory manager not initialized', 'DATABASE_ERROR');\n }\n\n try {\n const count = this.db.prepare('SELECT COUNT(*) as count FROM memory_entries').get() as { count: number };\n const size = this.db.prepare('SELECT page_count * page_size as size FROM pragma_page_count(), pragma_page_size()').get() as { size: number };\n\n return {\n totalEntries: count.count,\n dbSize: size.size,\n indexSize: 0, // vec extension handles indexing internally\n memoryUsage: process.memoryUsage().heapUsed\n };\n } catch (error) {\n throw new MemoryError(\n `Failed to get stats: ${(error as Error).message}`,\n 'DATABASE_ERROR'\n );\n }\n }\n\n /**\n * Cleanup old entries\n */\n /**\n * Get total count of memory entries\n * v5.0.8: Added for maxEntries enforcement\n */\n /**\n * Get current entry count\n * Phase 1: Use internal counter instead of COUNT(*) for better performance\n */\n private getCount(): number {\n if (!this.initialized) {\n return 0;\n }\n\n // Return internal counter (maintained by transactions)\n return this.entryCount;\n }\n\n /**\n * Phase 2: Validate cleanup configuration\n * v5.0.10 Phase 2.1: Added validation for maxCleanupCount and retentionDays\n * @throws {MemoryError} if configuration is invalid\n */\n private validateCleanupConfig(): void {\n const cfg = this.cleanupConfig;\n\n if (cfg.triggerThreshold < 0.5 || cfg.triggerThreshold > 1.0) {\n throw new MemoryError(\n 'cleanup.triggerThreshold must be between 0.5 and 1.0',\n 'CONFIG_ERROR'\n );\n }\n\n if (cfg.targetThreshold < 0.1 || cfg.targetThreshold > 0.9) {\n throw new MemoryError(\n 'cleanup.targetThreshold must be between 0.1 and 0.9',\n 'CONFIG_ERROR'\n );\n }\n\n if (cfg.targetThreshold >= cfg.triggerThreshold) {\n throw new MemoryError(\n 'cleanup.targetThreshold must be less than triggerThreshold',\n 'CONFIG_ERROR'\n );\n }\n\n if (cfg.minCleanupCount < 1) {\n throw new MemoryError(\n 'cleanup.minCleanupCount must be at least 1',\n 'CONFIG_ERROR'\n );\n }\n\n // Phase 2.1: Validate maxCleanupCount is positive\n if (cfg.maxCleanupCount < 1) {\n throw new MemoryError(\n 'cleanup.maxCleanupCount must be at least 1',\n 'CONFIG_ERROR'\n );\n }\n\n if (cfg.maxCleanupCount < cfg.minCleanupCount) {\n throw new MemoryError(\n 'cleanup.maxCleanupCount must be >= minCleanupCount',\n 'CONFIG_ERROR'\n );\n }\n\n // Phase 2.1: Validate retentionDays is positive\n if (cfg.retentionDays < 1) {\n throw new MemoryError(\n 'cleanup.retentionDays must be at least 1',\n 'CONFIG_ERROR'\n );\n }\n }\n\n /**\n * Phase 2: Check if cleanup should be triggered based on usage threshold\n */\n private shouldTriggerCleanup(): boolean {\n if (!this.cleanupConfig.enabled) {\n return false;\n }\n\n const currentUsage = this.entryCount / this.config.maxEntries;\n return currentUsage >= this.cleanupConfig.triggerThreshold;\n }\n\n /**\n * Phase 2: Calculate how many entries to remove to reach target threshold\n */\n private calculateCleanupCount(): number {\n const targetCount = Math.floor(\n this.config.maxEntries * this.cleanupConfig.targetThreshold\n );\n const toRemove = this.entryCount - targetCount;\n\n // Phase 2.1: If already below target, don't cleanup\n if (toRemove <= 0) {\n return 0;\n }\n\n // Enforce min/max bounds\n return Math.max(\n this.cleanupConfig.minCleanupCount,\n Math.min(this.cleanupConfig.maxCleanupCount, toRemove)\n );\n }\n\n /**\n * Phase 2: Execute cleanup with configured strategy\n * @returns Number of entries removed\n */\n private async executeSmartCleanup(): Promise<number> {\n const count = this.calculateCleanupCount();\n\n logger.debug('Executing smart cleanup', {\n strategy: this.cleanupConfig.strategy,\n count,\n currentCount: this.entryCount,\n threshold: this.cleanupConfig.triggerThreshold\n });\n\n // Phase 2.1: All cleanup methods now return actual deleted count\n switch (this.cleanupConfig.strategy) {\n case 'oldest':\n return await this.cleanupOldest(count);\n\n case 'least_accessed':\n return await this.cleanupLeastAccessed(count);\n\n case 'hybrid':\n return await this.cleanupHybrid(count);\n\n default:\n throw new MemoryError(\n `Unknown cleanup strategy: ${this.cleanupConfig.strategy}`,\n 'CONFIG_ERROR'\n );\n }\n }\n\n /**\n * Remove oldest entries\n * v5.0.8: Added for automatic cleanup when approaching maxEntries\n * v5.0.10 Phase 2: Enhanced logging with strategy info\n * v5.0.10 Phase 2.1: Now returns actual deleted count\n */\n private async cleanupOldest(count: number): Promise<number> {\n if (!this.initialized || count <= 0) {\n return 0;\n }\n\n try {\n // Phase 1: Use prepared statement and maintain entryCount\n const deleteInfo = this.statements.deleteOldest!.run(count);\n if (deleteInfo.changes > 0) {\n this.entryCount -= deleteInfo.changes;\n }\n\n logger.info('Cleaned up oldest entries', {\n requested: count,\n deleted: deleteInfo.changes,\n newCount: this.entryCount,\n strategy: 'oldest' // Phase 2: Add strategy info\n });\n\n return deleteInfo.changes;\n } catch (error) {\n logger.error('Failed to cleanup oldest entries', {\n count,\n error: (error as Error).message\n });\n return 0;\n }\n }\n\n /**\n * Phase 2: Remove least accessed entries\n * v5.0.10 Phase 2.1: Now async to support fallback to cleanupOldest\n * @param count Number of entries to remove\n * @returns Number of entries actually removed\n */\n private async cleanupLeastAccessed(count: number): Promise<number> {\n if (!this.initialized || count <= 0) {\n return 0;\n }\n\n if (!this.config.trackAccess) {\n logger.warn('least_accessed strategy requires trackAccess=true, falling back to oldest');\n return await this.cleanupOldest(count); // Phase 2.1: Properly await fallback\n }\n\n try {\n const deleteInfo = this.db.prepare(`\n DELETE FROM memory_entries\n WHERE id IN (\n SELECT id FROM memory_entries\n ORDER BY access_count ASC, last_accessed_at ASC\n LIMIT ?\n )\n `).run(count);\n\n if (deleteInfo.changes > 0) {\n this.entryCount -= deleteInfo.changes;\n }\n\n logger.info('Cleaned up least accessed entries', {\n requested: count,\n deleted: deleteInfo.changes,\n newCount: this.entryCount,\n strategy: 'least_accessed'\n });\n\n return deleteInfo.changes;\n } catch (error) {\n logger.error('Failed to cleanup least accessed entries', {\n count,\n error: (error as Error).message\n });\n return 0;\n }\n }\n\n /**\n * Phase 2: Remove entries using hybrid strategy (access count + age)\n * v5.0.10 Phase 2.1: Now async for consistency with other cleanup methods\n * @param count Number of entries to remove\n * @returns Number of entries actually removed\n */\n private async cleanupHybrid(count: number): Promise<number> {\n if (!this.initialized || count <= 0) {\n return 0;\n }\n\n try {\n const deleteInfo = this.db.prepare(`\n DELETE FROM memory_entries\n WHERE id IN (\n SELECT id FROM memory_entries\n ORDER BY\n access_count ASC,\n created_at ASC\n LIMIT ?\n )\n `).run(count);\n\n if (deleteInfo.changes > 0) {\n this.entryCount -= deleteInfo.changes;\n }\n\n logger.info('Cleaned up entries using hybrid strategy', {\n requested: count,\n deleted: deleteInfo.changes,\n newCount: this.entryCount,\n strategy: 'hybrid'\n });\n\n return deleteInfo.changes;\n } catch (error) {\n logger.error('Failed to cleanup with hybrid strategy', {\n count,\n error: (error as Error).message\n });\n return 0;\n }\n }\n\n async cleanup(olderThanDays?: number): Promise<number> {\n if (!this.initialized) {\n throw new MemoryError('Memory manager not initialized', 'DATABASE_ERROR');\n }\n\n const days = olderThanDays || this.config.cleanupDays;\n const cutoffTime = Date.now() - (days * 24 * 60 * 60 * 1000);\n\n try {\n // Phase 1: Use prepared statement and maintain entryCount\n const deleteInfo = this.statements.deleteBeforeCutoff!.run(cutoffTime);\n const deleted = deleteInfo.changes;\n\n if (deleted > 0) {\n this.entryCount -= deleted;\n this.db.prepare('VACUUM').run();\n logger.info('Cleanup completed', {\n deleted,\n olderThanDays: days,\n newCount: this.entryCount\n });\n }\n\n return deleted;\n } catch (error) {\n throw new MemoryError(\n `Cleanup failed: ${(error as Error).message}`,\n 'DATABASE_ERROR'\n );\n }\n }\n\n /**\n * Close database\n */\n async close(): Promise<void> {\n if (this.db) {\n this.db.close();\n this.initialized = false;\n logger.info('MemoryManager closed');\n }\n }\n\n // Stub implementations for interface compliance\n async saveIndex(): Promise<void> {\n // sqlite-vec handles indexing automatically\n }\n\n async loadIndex(): Promise<void> {\n // sqlite-vec handles indexing automatically\n }\n\n async backup(destPath: string): Promise<void> {\n if (!this.initialized) {\n throw new MemoryError('Memory manager not initialized', 'DATABASE_ERROR');\n }\n\n try {\n // Ensure destination directory exists\n const { dirname } = await import('path');\n const { mkdir } = await import('fs/promises');\n const destDir = dirname(destPath);\n await mkdir(destDir, { recursive: true });\n\n // Use better-sqlite3 backup API (async in v12+)\n // backup() copies FROM source TO destination path\n await this.db.backup(destPath);\n\n logger.info('Database backup created', { destPath });\n } catch (error) {\n throw new MemoryError(\n `Failed to create backup: ${(error as Error).message}`,\n 'DATABASE_ERROR',\n { destPath, error }\n );\n }\n }\n\n async restore(srcPath: string): Promise<void> {\n if (!this.initialized) {\n throw new MemoryError('Memory manager not initialized', 'DATABASE_ERROR');\n }\n\n try {\n // Validate source exists\n if (!existsSync(srcPath)) {\n throw new MemoryError(\n `Backup file not found: ${srcPath}`,\n 'DATABASE_ERROR',\n { srcPath }\n );\n }\n\n // Close current database and reset state\n // Phase 2.1 Fix: Must reset all state before reinitializing\n this.db.close();\n this.initialized = false;\n this.entryCount = 0;\n this.statements = {};\n\n // Copy backup to current location using better-sqlite3's backup method\n const srcDb = new Database(srcPath, { readonly: true });\n const destDb = new Database(this.config.dbPath);\n await srcDb.backup(this.config.dbPath);\n srcDb.close();\n destDb.close();\n\n // Reopen database\n this.db = new Database(this.config.dbPath);\n this.db.pragma('journal_mode = WAL');\n this.db.pragma('busy_timeout = 5000'); // Wait up to 5 seconds for locks\n\n // Phase 2.1 Fix: Reinitialize completely (rebuild statements, recount entries)\n // This ensures prepared statements are bound to the new connection\n await this.initialize();\n\n logger.info('Database restored successfully', { srcPath });\n } catch (error) {\n throw new MemoryError(\n `Failed to restore database: ${(error as Error).message}`,\n 'DATABASE_ERROR',\n { srcPath, error }\n );\n }\n }\n\n async exportToJSON(\n filePath: string,\n options?: import('../types/memory.js').ExportOptions\n ): Promise<import('../types/memory.js').ExportResult> {\n if (!this.initialized) {\n throw new MemoryError('Memory manager not initialized', 'DATABASE_ERROR');\n }\n\n const {\n includeEmbeddings = false,\n filters = {},\n batchSize = 1000,\n pretty = false\n } = options || {};\n\n try {\n // Ensure destination directory exists\n const destDir = dirname(filePath);\n if (!existsSync(destDir)) {\n mkdirSync(destDir, { recursive: true });\n }\n\n // Build query with filters\n // v4.11.0: No JOIN with memory_vectors (FTS5 only, no embeddings)\n let query = 'SELECT e.* FROM memory_entries e';\n const conditions: string[] = [];\n const params: unknown[] = [];\n\n // Apply filters\n if (filters.type) {\n const types = Array.isArray(filters.type) ? filters.type : [filters.type];\n conditions.push(`json_extract(e.metadata, '$.type') IN (${types.map(() => '?').join(',')})`);\n params.push(...types);\n }\n\n if (filters.source) {\n const sources = Array.isArray(filters.source) ? filters.source : [filters.source];\n conditions.push(`json_extract(e.metadata, '$.source') IN (${sources.map(() => '?').join(',')})`);\n params.push(...sources);\n }\n\n if (filters.agentId) {\n conditions.push(`json_extract(e.metadata, '$.agentId') = ?`);\n params.push(filters.agentId);\n }\n\n if (filters.sessionId) {\n conditions.push(`json_extract(e.metadata, '$.sessionId') = ?`);\n params.push(filters.sessionId);\n }\n\n if (filters.dateRange?.from) {\n conditions.push('e.created_at >= ?');\n params.push(filters.dateRange.from.getTime());\n }\n\n if (filters.dateRange?.to) {\n conditions.push('e.created_at <= ?');\n params.push(filters.dateRange.to.getTime());\n }\n\n if (filters.minImportance !== undefined) {\n conditions.push(`CAST(json_extract(e.metadata, '$.importance') AS REAL) >= ?`);\n params.push(filters.minImportance);\n }\n\n if (conditions.length > 0) {\n query += ' WHERE ' + conditions.join(' AND ');\n }\n\n // Execute query\n const rows = this.db.prepare(query).all(...params) as Array<{\n id: number;\n content: string;\n metadata: string;\n created_at: number;\n last_accessed_at: number | null;\n access_count: number;\n embedding: Buffer | null;\n }>;\n\n // Build export data\n const entries = rows.map(row => {\n const entry: {\n id: number;\n content: string;\n embedding?: number[];\n metadata: MemoryMetadata;\n createdAt: string;\n lastAccessedAt?: string;\n accessCount: number;\n } = {\n id: row.id,\n content: row.content,\n metadata: JSON.parse(row.metadata),\n createdAt: new Date(row.created_at).toISOString(),\n accessCount: row.access_count\n };\n\n if (row.last_accessed_at) {\n entry.lastAccessedAt = new Date(row.last_accessed_at).toISOString();\n }\n\n // v4.11.0: No embeddings in FTS5 mode\n\n return entry;\n });\n\n // Create export object\n const exportData: import('../types/memory.js').MemoryExport = {\n version: '4.11.0', // v4.11.0: Updated version\n metadata: {\n exportedAt: new Date().toISOString(),\n totalEntries: entries.length,\n includesEmbeddings: false // v4.11.0: Always false (FTS5 only)\n },\n entries\n };\n\n // Write to file\n const { writeFile } = await import('fs/promises');\n const json = pretty ? JSON.stringify(exportData, null, 2) : JSON.stringify(exportData);\n await writeFile(filePath, json, 'utf-8');\n\n const sizeBytes = Buffer.byteLength(json, 'utf-8');\n\n logger.info('Memory exported to JSON', {\n filePath,\n entriesExported: entries.length,\n sizeBytes\n });\n\n return {\n entriesExported: entries.length,\n sizeBytes,\n filePath,\n exportedAt: new Date()\n };\n } catch (error) {\n throw new MemoryError(\n `Export failed: ${(error as Error).message}`,\n 'DATABASE_ERROR',\n { filePath, error }\n );\n }\n }\n\n async importFromJSON(\n filePath: string,\n options?: import('../types/memory.js').ImportOptions\n ): Promise<import('../types/memory.js').ImportResult> {\n if (!this.initialized) {\n throw new MemoryError('Memory manager not initialized', 'DATABASE_ERROR');\n }\n\n const {\n skipDuplicates = true,\n batchSize = 100,\n validate = true,\n clearExisting = false\n } = options || {};\n\n try {\n // Validate import file exists\n if (!existsSync(filePath)) {\n throw new MemoryError(\n `Import file not found: ${filePath}`,\n 'DATABASE_ERROR',\n { filePath }\n );\n }\n\n // Read import file\n const { readFile } = await import('fs/promises');\n const content = await readFile(filePath, 'utf-8');\n const importData = JSON.parse(content) as import('../types/memory.js').MemoryExport;\n\n // Validate format version\n const SUPPORTED_VERSIONS = ['1.0', '4.0.0', '4.11.0'];\n if (!importData.version || !SUPPORTED_VERSIONS.includes(importData.version)) {\n throw new MemoryError(\n `Unsupported export format version: ${importData.version}. Supported versions: ${SUPPORTED_VERSIONS.join(', ')}`,\n 'DATABASE_ERROR',\n { version: importData.version, supportedVersions: SUPPORTED_VERSIONS }\n );\n }\n\n // Validate format\n if (!importData.entries || !Array.isArray(importData.entries)) {\n throw new MemoryError(\n 'Invalid import format: missing entries array',\n 'DATABASE_ERROR'\n );\n }\n\n // Clear existing data if requested\n if (clearExisting) {\n await this.clear();\n }\n\n let entriesImported = 0;\n let entriesSkipped = 0;\n let entriesFailed = 0;\n const errors: Array<{ entry: unknown; error: string }> = [];\n\n // Track existing content hashes for duplicate detection\n const existingHashes = new Set<string>();\n if (skipDuplicates) {\n const existing = this.db.prepare('SELECT content FROM memory_entries').all() as Array<{ content: string }>;\n existing.forEach(row => {\n existingHashes.add(this.hashContent(row.content));\n });\n }\n\n // Process entries in batches\n for (let i = 0; i < importData.entries.length; i += batchSize) {\n const batch = importData.entries.slice(i, i + batchSize);\n\n for (const entry of batch) {\n try {\n // Validate entry if requested\n if (validate) {\n if (!entry.content || !entry.metadata) {\n throw new Error('Missing required fields: content or metadata');\n }\n // v4.11.0: Embedding validation removed (FTS5 only, no vector search)\n }\n\n // Check for duplicates\n if (skipDuplicates) {\n const hash = this.hashContent(entry.content);\n if (existingHashes.has(hash)) {\n entriesSkipped++;\n continue;\n }\n existingHashes.add(hash);\n }\n\n // Import entry\n // v4.11.0: No embedding generation (FTS5 only)\n await this.add(\n entry.content,\n null, // No embedding needed for FTS5\n entry.metadata\n );\n\n entriesImported++;\n } catch (error) {\n entriesFailed++;\n errors.push({\n entry,\n error: (error as Error).message\n });\n }\n }\n }\n\n logger.info('Memory imported from JSON', {\n filePath,\n entriesImported,\n entriesSkipped,\n entriesFailed\n });\n\n return {\n entriesImported,\n entriesSkipped,\n entriesFailed,\n errors,\n importedAt: new Date()\n };\n } catch (error) {\n throw new MemoryError(\n `Import failed: ${(error as Error).message}`,\n 'DATABASE_ERROR',\n { filePath, error }\n );\n }\n }\n\n /**\n * Hash content for duplicate detection\n */\n private hashContent(content: string): string {\n // Simple hash using content length + first/last 100 chars\n // For production, consider using crypto.createHash('sha256')\n const len = content.length;\n const start = content.substring(0, 100);\n const end = content.substring(Math.max(0, len - 100));\n return `${len}:${start}:${end}`;\n }\n}\n","/**\n * Memory System Types\n *\n * Defines types for the AutomatosX memory system using SQLite + HNSW\n */\n\n/**\n * Memory entry stored in the system\n */\nexport interface MemoryEntry {\n /** Unique identifier */\n id: number;\n\n /** Content/text of the memory */\n content: string;\n\n /** Vector embedding (1536 dimensions for OpenAI/Claude) */\n embedding: number[];\n\n /** Additional metadata */\n metadata: MemoryMetadata;\n\n /** Creation timestamp */\n createdAt: Date;\n\n /** Last access timestamp */\n lastAccessedAt?: Date;\n\n /** Access count */\n accessCount: number;\n\n /** Relevance score (optional, set during search) */\n score?: number;\n}\n\n/**\n * Metadata associated with memory entries\n */\nexport interface MemoryMetadata {\n /** Type of memory entry */\n type: 'conversation' | 'code' | 'document' | 'task' | 'other';\n\n /** Source of the memory */\n source: string;\n\n /** Associated agent ID */\n agentId?: string;\n\n /** Associated session ID */\n sessionId?: string;\n\n /** Tags for categorization */\n tags?: string[];\n\n /** Importance score (0-1) */\n importance?: number;\n\n /** Custom metadata */\n [key: string]: unknown;\n}\n\n/**\n * Search query for finding memories\n */\nexport interface MemorySearchQuery {\n /** Query vector for similarity search */\n vector?: number[];\n\n /** Text query (will be converted to vector) */\n text?: string;\n\n /** Metadata filters */\n filters?: MemoryFilter;\n\n /** Number of results to return */\n limit?: number;\n\n /** Minimum similarity threshold (0-1) */\n threshold?: number;\n\n /** Include embeddings in results */\n includeEmbeddings?: boolean;\n}\n\n/**\n * Metadata filters for memory search\n */\nexport interface MemoryFilter {\n /** Filter by type */\n type?: MemoryMetadata['type'] | MemoryMetadata['type'][];\n\n /** Filter by source */\n source?: string | string[];\n\n /** Filter by agent ID */\n agentId?: string;\n\n /** Filter by session ID */\n sessionId?: string;\n\n /** Filter by tags (AND logic) */\n tags?: string[];\n\n /** Filter by date range */\n dateRange?: {\n from?: Date;\n to?: Date;\n };\n\n /** Filter by importance */\n minImportance?: number;\n}\n\n/**\n * Search result with similarity score\n */\nexport interface MemorySearchResult {\n /** Memory entry */\n entry: MemoryEntry;\n\n /** Similarity score (0-1, higher is more similar) */\n similarity: number;\n\n /** Distance metric (for HNSW, lower is more similar) */\n distance: number;\n}\n\n/**\n * Memory manager configuration\n */\nexport interface MemoryManagerConfig {\n /** Database file path */\n dbPath: string;\n\n /** HNSW index parameters */\n hnsw?: {\n /** Number of connections per layer (default: 16) */\n M?: number;\n\n /** Size of dynamic candidate list (default: 200) */\n efConstruction?: number;\n\n /** Size of dynamic candidate list for search (default: 50) */\n efSearch?: number;\n };\n\n /** Maximum number of entries (default: 10000) */\n maxEntries?: number;\n\n /**\n * Smart cleanup configuration (v5.0.10 Phase 2)\n */\n cleanup?: {\n /** Enable automatic cleanup (default: true) */\n enabled?: boolean;\n\n /** Cleanup strategy (default: 'oldest') */\n strategy?: 'oldest' | 'least_accessed' | 'hybrid';\n\n /** Trigger cleanup when usage reaches this threshold (default: 0.9 = 90%) */\n triggerThreshold?: number;\n\n /** Clean until usage reaches this target (default: 0.7 = 70%) */\n targetThreshold?: number;\n\n /** Minimum number of entries to remove per cleanup (default: 10) */\n minCleanupCount?: number;\n\n /** Maximum number of entries to remove per cleanup (default: 1000) */\n maxCleanupCount?: number;\n\n /** Days to keep entries for time-based cleanup (default: 30) */\n retentionDays?: number;\n };\n\n /**\n * @deprecated Use cleanup.enabled instead (backward compatibility)\n * Auto-cleanup old entries\n */\n autoCleanup?: boolean;\n\n /**\n * @deprecated Use cleanup.retentionDays instead (backward compatibility)\n * Days to keep entries (default: 30)\n */\n cleanupDays?: number;\n\n /** Enable access tracking */\n trackAccess?: boolean;\n\n /** Embedding provider for text-to-vector conversion (required for text queries) */\n embeddingProvider?: unknown; // IEmbeddingProvider - use unknown to avoid circular dependency\n}\n\n/**\n * Memory statistics\n */\nexport interface MemoryStats {\n /** Total number of entries */\n totalEntries: number;\n\n /** Database size in bytes */\n dbSize: number;\n\n /** Index size in bytes (estimated) */\n indexSize: number;\n\n /** Memory usage in bytes */\n memoryUsage: number;\n\n /** Average search time (ms) */\n avgSearchTime?: number;\n\n /** Last cleanup timestamp */\n lastCleanup?: Date;\n}\n\n/**\n * Export options for JSON export\n */\nexport interface ExportOptions {\n /** Include embeddings in export (default: false) */\n includeEmbeddings?: boolean;\n\n /** Filters for selective export */\n filters?: MemoryFilter;\n\n /** Batch size for streaming large datasets (default: 1000) */\n batchSize?: number;\n\n /** Pretty print JSON (default: false) */\n pretty?: boolean;\n}\n\n/**\n * Export result\n */\nexport interface ExportResult {\n /** Number of entries exported */\n entriesExported: number;\n\n /** Total size in bytes */\n sizeBytes: number;\n\n /** Export file path */\n filePath: string;\n\n /** Export timestamp */\n exportedAt: Date;\n}\n\n/**\n * Import options for JSON import\n */\nexport interface ImportOptions {\n /** Skip duplicate entries (by content hash) */\n skipDuplicates?: boolean;\n\n /** Batch size for processing (default: 100) */\n batchSize?: number;\n\n /** Validate entries before import */\n validate?: boolean;\n\n /** Clear existing data before import */\n clearExisting?: boolean;\n}\n\n/**\n * Import result\n */\nexport interface ImportResult {\n /** Number of entries imported */\n entriesImported: number;\n\n /** Number of entries skipped (duplicates) */\n entriesSkipped: number;\n\n /** Number of entries failed */\n entriesFailed: number;\n\n /** Import errors */\n errors: Array<{ entry: unknown; error: string }>;\n\n /** Import timestamp */\n importedAt: Date;\n}\n\n/**\n * JSON export format\n */\nexport interface MemoryExport {\n /** Format version */\n version: string;\n\n /** Export metadata */\n metadata: {\n exportedAt: string;\n totalEntries: number;\n includesEmbeddings: boolean;\n };\n\n /** Memory entries */\n entries: Array<{\n id: number;\n content: string;\n embedding?: number[];\n metadata: MemoryMetadata;\n createdAt: string;\n lastAccessedAt?: string;\n accessCount: number;\n }>;\n}\n\n/**\n * Memory manager interface\n */\nexport interface IMemoryManager {\n /**\n * Add a new memory entry\n *\n * v4.11.0: Embedding is now optional (null allowed for FTS5-only mode)\n */\n add(content: string, embedding: number[] | null, metadata: MemoryMetadata): Promise<MemoryEntry>;\n\n /**\n * Search for similar memories\n */\n search(query: MemorySearchQuery): Promise<MemorySearchResult[]>;\n\n /**\n * Get memory by ID\n */\n get(id: number): Promise<MemoryEntry | null>;\n\n /**\n * Update memory metadata\n */\n update(id: number, metadata: Partial<MemoryMetadata>): Promise<void>;\n\n /**\n * Delete memory by ID\n */\n delete(id: number): Promise<void>;\n\n /**\n * Clear all memories\n */\n clear(): Promise<void>;\n\n /**\n * Get memory statistics\n */\n getStats(): Promise<MemoryStats>;\n\n /**\n * Cleanup old entries\n */\n cleanup(olderThanDays?: number): Promise<number>;\n\n /**\n * Save index to disk\n */\n saveIndex(): Promise<void>;\n\n /**\n * Load index from disk\n */\n loadIndex(): Promise<void>;\n\n /**\n * Close database and save index\n */\n close(): Promise<void>;\n\n /**\n * Backup database to destination path\n */\n backup(destPath: string, onProgress?: (progress: number) => void): Promise<void>;\n\n /**\n * Restore database from backup\n */\n restore(srcPath: string): Promise<void>;\n\n /**\n * Export memories to JSON\n */\n exportToJSON(filePath: string, options?: ExportOptions): Promise<ExportResult>;\n\n /**\n * Import memories from JSON\n */\n importFromJSON(filePath: string, options?: ImportOptions): Promise<ImportResult>;\n}\n\n/**\n * Memory error types\n */\nexport class MemoryError extends Error {\n constructor(\n message: string,\n public readonly code: MemoryErrorCode,\n public readonly context?: Record<string, unknown>\n ) {\n super(message);\n this.name = 'MemoryError';\n }\n}\n\nexport type MemoryErrorCode =\n | 'ENTRY_NOT_FOUND'\n | 'INVALID_VECTOR'\n | 'DATABASE_ERROR'\n | 'INDEX_ERROR'\n | 'QUERY_ERROR'\n | 'CAPACITY_EXCEEDED'\n | 'PROVIDER_MISSING'\n | 'EMBEDDING_GENERATION_FAILED'\n | 'MEMORY_LIMIT' // v5.0.8: Memory limit reached\n | 'CONFIG_ERROR'; // v5.0.10 Phase 2: Invalid configuration\n","/**\n * Progress Indicator - CLI progress display using ora\n *\n * Provides consistent progress feedback for long-running operations\n */\n\nimport ora, { Ora } from 'ora';\nimport chalk from 'chalk';\n\nexport interface ProgressOptions {\n /**\n * Show spinner animation\n */\n spinner?: boolean;\n\n /**\n * Custom spinner type\n */\n spinnerType?: 'dots' | 'line' | 'arrow' | 'aesthetic';\n\n /**\n * Use colors\n */\n colors?: boolean;\n}\n\n/**\n * Progress Indicator\n *\n * Wrapper around ora for consistent progress display\n */\nexport class ProgressIndicator {\n private spinner: Ora | null = null;\n private options: ProgressOptions;\n\n constructor(options: ProgressOptions = {}) {\n this.options = {\n spinner: true,\n spinnerType: 'dots',\n colors: true,\n ...options\n };\n }\n\n /**\n * Start progress indicator\n */\n start(message: string): void {\n if (!this.options.spinner) {\n console.log(message);\n return;\n }\n\n this.spinner = ora({\n text: message,\n spinner: this.options.spinnerType,\n color: this.options.colors ? 'cyan' : undefined\n }).start();\n }\n\n /**\n * Update progress message\n */\n update(message: string): void {\n if (this.spinner) {\n this.spinner.text = message;\n } else {\n console.log(message);\n }\n }\n\n /**\n * Mark as success and stop\n */\n succeed(message?: string): void {\n if (this.spinner) {\n this.spinner.succeed(message);\n this.spinner = null;\n } else if (message) {\n const text = this.options.colors\n ? chalk.green(`✓ ${message}`)\n : `✓ ${message}`;\n console.log(text);\n }\n }\n\n /**\n * Mark as failure and stop\n */\n fail(message?: string): void {\n if (this.spinner) {\n this.spinner.fail(message);\n this.spinner = null;\n } else if (message) {\n const text = this.options.colors\n ? chalk.red(`✗ ${message}`)\n : `✗ ${message}`;\n console.log(text);\n }\n }\n\n /**\n * Mark as warning and stop\n */\n warn(message?: string): void {\n if (this.spinner) {\n this.spinner.warn(message);\n this.spinner = null;\n } else if (message) {\n const text = this.options.colors\n ? chalk.yellow(`⚠ ${message}`)\n : `⚠ ${message}`;\n console.log(text);\n }\n }\n\n /**\n * Mark as info and stop\n */\n info(message?: string): void {\n if (this.spinner) {\n this.spinner.info(message);\n this.spinner = null;\n } else if (message) {\n const text = this.options.colors\n ? chalk.blue(`ℹ ${message}`)\n : `ℹ ${message}`;\n console.log(text);\n }\n }\n\n /**\n * Stop spinner without status\n */\n stop(): void {\n if (this.spinner) {\n this.spinner.stop();\n this.spinner = null;\n }\n }\n\n /**\n * Clear spinner\n */\n clear(): void {\n if (this.spinner) {\n this.spinner.clear();\n }\n }\n\n /**\n * Check if spinner is active\n */\n isSpinning(): boolean {\n return this.spinner !== null && this.spinner.isSpinning;\n }\n}\n\n/**\n * Create a simple progress indicator\n */\nexport function createProgress(message: string, options?: ProgressOptions): ProgressIndicator {\n const progress = new ProgressIndicator(options);\n progress.start(message);\n return progress;\n}\n","/**\n * Run Command - Execute an agent with a specific task\n */\n\nimport type { CommandModule } from 'yargs';\nimport { ContextManager } from '../../agents/context-manager.js';\nimport { ProfileLoader } from '../../agents/profile-loader.js';\nimport { AbilitiesManager } from '../../agents/abilities-manager.js';\nimport { AgentExecutor } from '../../agents/executor.js';\nimport { StageExecutor } from '../../agents/stage-executor.js';\nimport { AdvancedStageExecutor } from '../../agents/advanced-stage-executor.js';\nimport type { MultiStageExecutionResult } from '../../agents/stage-executor.js';\nimport type { Stage } from '../../types/agent.js';\nimport { AgentNotFoundError } from '../../types/agent.js';\nimport { MemoryManager } from '../../core/memory-manager.js';\nimport { Router } from '../../core/router.js';\nimport { PathResolver } from '../../core/path-resolver.js';\nimport { SessionManager } from '../../core/session-manager.js';\nimport { WorkspaceManager } from '../../core/workspace-manager.js';\nimport { TeamManager } from '../../core/team-manager.js';\nimport { ClaudeProvider } from '../../providers/claude-provider.js';\nimport { GeminiProvider } from '../../providers/gemini-provider.js';\nimport { OpenAIProvider } from '../../providers/openai-provider.js';\nimport { loadConfig } from '../../core/config.js';\nimport { logger } from '../../utils/logger.js';\nimport chalk from 'chalk';\nimport { join } from 'path';\nimport { writeFileSync } from 'fs';\nimport { mkdir } from 'fs/promises';\nimport boxen from 'boxen';\nimport type { ExecutionResult } from '../../agents/executor.js';\nimport { formatOutput, formatForSave } from '../../utils/output-formatter.js';\n\ninterface RunOptions {\n provider?: string;\n model?: string;\n memory?: boolean;\n saveMemory?: boolean;\n verbose?: boolean;\n format?: 'text' | 'json' | 'markdown';\n save?: string;\n timeout?: number;\n session?: string;\n}\n\nexport const runCommand: CommandModule<Record<string, unknown>, RunOptions> = {\n command: 'run <agent> <task>',\n describe: 'Run an agent with a specific task',\n\n builder: (yargs) => {\n return yargs\n .positional('agent', {\n describe: 'Agent name',\n type: 'string',\n demandOption: true\n })\n .positional('task', {\n describe: 'Task to execute',\n type: 'string',\n demandOption: true\n })\n .option('provider', {\n describe: 'Override provider (claude, gemini, openai)',\n type: 'string'\n })\n .option('model', {\n describe: 'Override model',\n type: 'string'\n })\n .option('memory', {\n describe: 'Inject memory',\n type: 'boolean',\n default: true\n })\n .option('save-memory', {\n describe: 'Save result to memory',\n type: 'boolean',\n default: true\n })\n .option('verbose', {\n alias: 'v',\n describe: 'Verbose output',\n type: 'boolean',\n default: false\n })\n .option('format', {\n describe: 'Output format',\n type: 'string',\n choices: ['text', 'json', 'markdown'],\n default: 'text'\n })\n .option('save', {\n describe: 'Save result to file',\n type: 'string'\n })\n .option('timeout', {\n describe: 'Execution timeout in seconds',\n type: 'number'\n })\n .option('session', {\n describe: 'Join existing multi-agent session',\n type: 'string'\n })\n },\n\n handler: async (argv) => {\n // Validate inputs\n if (!argv.agent || typeof argv.agent !== 'string') {\n console.log(chalk.red.bold('\\n❌ Error: Agent name is required\\n'));\n process.exit(1);\n }\n\n if (!argv.task || typeof argv.task !== 'string') {\n console.log(chalk.red.bold('\\n❌ Error: Task is required\\n'));\n process.exit(1);\n }\n\n console.log(chalk.blue.bold(`\\n🤖 AutomatosX - Running ${argv.agent}\\n`));\n\n // Declare resources in outer scope for cleanup\n let memoryManager: MemoryManager | undefined;\n let router: Router | undefined;\n let contextManager: ContextManager | undefined;\n let context: any;\n let resolvedAgentName: string = argv.agent as string; // Default to input, will be resolved later\n\n try {\n // 1. Load configuration\n const config = await loadConfig(process.cwd());\n\n // 2. Detect project directory\n const projectDir = process.cwd(); // Use cwd for now\n\n if (argv.verbose) {\n console.log(chalk.gray(`Project: ${projectDir}`));\n console.log(chalk.gray(`Working directory: ${process.cwd()}`));\n console.log();\n }\n\n // 3. Initialize components\n // v4.10.0+: Initialize TeamManager for team-based configuration\n const teamManager = new TeamManager(\n join(projectDir, '.automatosx', 'teams')\n );\n\n const profileLoader = new ProfileLoader(\n join(projectDir, '.automatosx', 'agents'),\n undefined, // fallbackProfilesDir (uses default)\n teamManager\n );\n\n // Resolve agent name early (supports displayName → actual name)\n // This ensures consistency across session, memory, and all operations\n try {\n resolvedAgentName = await profileLoader.resolveAgentName(argv.agent as string);\n\n if (argv.verbose) {\n if (resolvedAgentName !== argv.agent) {\n console.log(chalk.gray(`Resolved agent: ${argv.agent} → ${resolvedAgentName}`));\n }\n }\n } catch (error) {\n // Agent not found - show helpful suggestions\n console.error(chalk.red.bold(`\\n❌ Agent not found: ${argv.agent}\\n`));\n\n // Try to suggest similar agents\n try {\n const suggestions = await profileLoader.findSimilarAgents(argv.agent as string, 3);\n const closeSuggestions = suggestions.filter(s => s.distance <= 3);\n\n if (closeSuggestions.length > 0) {\n console.log(chalk.yellow('💡 Did you mean:\\n'));\n closeSuggestions.forEach((s, i) => {\n const displayInfo = s.displayName ? `${s.displayName} (${s.name})` : s.name;\n const roleInfo = s.role ? ` - ${s.role}` : '';\n console.log(chalk.cyan(` ${i + 1}. ${displayInfo}${roleInfo}`));\n });\n console.log();\n } else {\n console.log(chalk.gray('Run \"ax agent list\" to see available agents.\\n'));\n }\n } catch {\n console.log(chalk.gray('Run \"ax agent list\" to see available agents.\\n'));\n }\n\n process.exit(1);\n }\n\n const abilitiesManager = new AbilitiesManager(\n join(projectDir, '.automatosx', 'abilities')\n );\n\n // Initialize memory manager (v4.11.0: No embedding provider required)\n // Initialize if either --memory (inject) or --save-memory (save) is enabled\n try {\n if (argv.memory || argv.saveMemory) {\n // v4.11.0: Memory uses FTS5, no embedding provider needed\n memoryManager = await MemoryManager.create({\n dbPath: join(projectDir, '.automatosx', 'memory', 'memory.db')\n });\n\n if (argv.verbose) {\n console.log(chalk.green('✓ Memory system initialized (FTS5 full-text search)\\n'));\n }\n }\n } catch (error) {\n // Graceful fallback if memory initialization fails\n const errMsg = error instanceof Error ? error.message : String(error);\n if (argv.verbose) {\n console.log(chalk.yellow(`⚠ Memory features disabled: ${errMsg}\\n`));\n }\n argv.memory = false;\n argv.saveMemory = false;\n }\n\n const pathResolver = new PathResolver({\n projectDir,\n workingDir: process.cwd(),\n agentWorkspace: join(projectDir, '.automatosx', 'workspaces')\n });\n\n // 4. Initialize providers from config\n const providers = [];\n\n if (config.providers['claude-code']?.enabled) {\n providers.push(new ClaudeProvider({\n name: 'claude-code',\n enabled: true,\n priority: config.providers['claude-code'].priority,\n timeout: config.providers['claude-code'].timeout,\n command: config.providers['claude-code'].command\n }));\n }\n\n if (config.providers['gemini-cli']?.enabled) {\n providers.push(new GeminiProvider({\n name: 'gemini-cli',\n enabled: true,\n priority: config.providers['gemini-cli'].priority,\n timeout: config.providers['gemini-cli'].timeout,\n command: config.providers['gemini-cli'].command\n }));\n }\n\n if (config.providers['openai']?.enabled) {\n providers.push(new OpenAIProvider({\n name: 'openai',\n enabled: true,\n priority: config.providers['openai'].priority,\n timeout: config.providers['openai'].timeout,\n command: config.providers['openai'].command\n }));\n }\n\n router = new Router({\n providers,\n fallbackEnabled: true\n });\n\n // 5. Initialize orchestration managers\n // v4.7.8+: Always initialize for delegation support (all agents can delegate)\n let sessionManager: SessionManager | undefined;\n let workspaceManager: WorkspaceManager | undefined;\n\n // Initialize SessionManager\n sessionManager = new SessionManager({\n persistencePath: join(projectDir, '.automatosx', 'sessions', 'sessions.json')\n });\n await sessionManager.initialize();\n\n // Initialize WorkspaceManager\n workspaceManager = new WorkspaceManager(projectDir);\n await workspaceManager.initialize();\n\n // If session ID provided, verify and join it\n if (argv.session) {\n // Verify session exists\n const session = await sessionManager.getSession(argv.session);\n if (!session) {\n console.log(chalk.red.bold(`\\n✗ Session not found: ${argv.session}\\n`));\n process.exit(1);\n }\n\n // Add this agent to the session (use resolved name for consistency)\n await sessionManager.addAgent(argv.session, resolvedAgentName);\n\n if (argv.verbose) {\n console.log(chalk.cyan(`\\n🔗 Joined session: ${argv.session}`));\n console.log(chalk.gray(`Session task: ${session.task}`));\n console.log(chalk.gray(`Agents in session: ${session.agents.join(', ')}\\n`));\n }\n }\n\n // 6. Create context manager\n contextManager = new ContextManager({\n profileLoader,\n abilitiesManager,\n memoryManager: memoryManager || null,\n router,\n pathResolver,\n sessionManager,\n workspaceManager\n });\n\n // 7. Create execution context\n if (argv.verbose) {\n console.log(chalk.gray('Creating execution context...'));\n console.log();\n }\n\n try {\n context = await contextManager.createContext(\n resolvedAgentName,\n argv.task as string,\n {\n provider: argv.provider,\n model: argv.model,\n skipMemory: !argv.memory,\n sessionId: argv.session\n }\n );\n } catch (error) {\n // Handle agent not found error with suggestions\n if (error instanceof AgentNotFoundError) {\n const agentName = resolvedAgentName;\n console.log(chalk.red.bold(`\\n❌ Agent not found: ${agentName}\\n`));\n\n // Find similar agents (loads profiles silently from cache or disk)\n const suggestions = await profileLoader.findSimilarAgents(agentName, 3);\n\n if (suggestions.length > 0) {\n // Filter to only very similar agents (distance <= 3)\n const closeSuggestions = suggestions.filter(s => s.distance <= 3);\n\n if (closeSuggestions.length > 0) {\n console.log(chalk.yellow('💡 Did you mean:\\n'));\n closeSuggestions.forEach((s, i) => {\n const displayInfo = s.displayName ? `${s.displayName} (${s.name})` : s.name;\n const roleInfo = s.role ? ` - ${s.role}` : '';\n console.log(chalk.cyan(` ${i + 1}. ${displayInfo}${roleInfo}`));\n });\n\n console.log(chalk.gray('\\nTo use one of these agents:'));\n console.log(chalk.gray(` automatosx run ${closeSuggestions[0]!.name} \"${argv.task}\"`));\n console.log();\n } else {\n // No close matches, show all available agents\n console.log(chalk.yellow('💡 Available agents:\\n'));\n const allAgents = await profileLoader.listProfiles();\n allAgents.slice(0, 10).forEach(name => {\n console.log(chalk.cyan(` • ${name}`));\n });\n if (allAgents.length > 10) {\n console.log(chalk.gray(` ... and ${allAgents.length - 10} more`));\n }\n console.log(chalk.gray('\\nRun \"automatosx list agents\" to see all agents\\n'));\n }\n }\n\n process.exit(1);\n }\n // Re-throw other errors\n throw error;\n }\n\n // 8. Detect if agent has multi-stage workflow\n const hasStages = context.agent.stages && context.agent.stages.length > 0;\n\n if (hasStages) {\n const stages = context.agent.stages;\n\n // Check if any stages have advanced features (dependencies, parallel, conditions)\n const hasAdvancedFeatures = stages.filter((s: Stage | undefined): s is Stage => s !== undefined).some((s: Stage) =>\n (s.dependencies && s.dependencies.length > 0) ||\n s.parallel ||\n s.condition\n );\n\n // Use StageExecutor for multi-stage execution\n if (argv.verbose) {\n console.log(chalk.cyan(`\\n📋 Multi-stage execution detected (${context.agent.stages.length} stages)\\n`));\n\n if (hasAdvancedFeatures) {\n console.log(chalk.cyan('✨ Advanced features enabled (dependencies/parallel/conditions)\\n'));\n }\n }\n\n let multiStageResult: MultiStageExecutionResult;\n\n // v5.0.8: Create AbortController for timeout support\n let controller: AbortController | undefined;\n let timeoutId: NodeJS.Timeout | undefined;\n\n if (argv.timeout) {\n const timeoutMs = argv.timeout * 1000;\n controller = new AbortController();\n timeoutId = setTimeout(() => {\n controller!.abort();\n }, timeoutMs);\n }\n\n try {\n if (hasAdvancedFeatures) {\n // Use AdvancedStageExecutor for Phase 3 features\n const advancedExecutor = new AdvancedStageExecutor();\n\n // Show dependency graph if verbose\n if (argv.verbose) {\n console.log(advancedExecutor.visualizeDependencyGraph(stages));\n }\n\n multiStageResult = await advancedExecutor.executeAdvanced(context, {\n verbose: argv.verbose,\n showProgress: !argv.verbose,\n continueOnFailure: false,\n saveToMemory: argv.saveMemory,\n memoryManager: memoryManager || null,\n timeout: argv.timeout ? argv.timeout * 1000 : undefined, // v5.0.8: Pass timeout\n signal: controller?.signal // v5.0.8: Pass abort signal\n });\n\n // Display multi-stage result\n advancedExecutor.displayResult(multiStageResult, argv.verbose || false);\n } else {\n // Use regular StageExecutor for simple multi-stage\n const stageExecutor = new StageExecutor();\n multiStageResult = await stageExecutor.executeStages(context, {\n verbose: argv.verbose,\n showProgress: !argv.verbose,\n continueOnFailure: false,\n saveToMemory: argv.saveMemory,\n memoryManager: memoryManager || null,\n timeout: argv.timeout ? argv.timeout * 1000 : undefined, // v5.0.8: Pass timeout\n signal: controller?.signal // v5.0.8: Pass abort signal\n });\n\n // Display multi-stage result\n stageExecutor.displayResult(multiStageResult, argv.verbose || false);\n }\n } finally {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n }\n\n // Check if execution was aborted (v5.0.8)\n if (controller?.signal.aborted) {\n throw new Error(`Multi-stage execution timeout after ${argv.timeout} seconds`);\n }\n\n // Save multi-stage result to file if requested\n if (argv.save) {\n try {\n const savePath = argv.save;\n const saveDir = join(savePath, '..');\n await mkdir(saveDir, { recursive: true });\n\n let outputData: string;\n if (argv.format === 'json') {\n outputData = JSON.stringify({\n agent: resolvedAgentName,\n task: argv.task,\n stages: multiStageResult.stages.map(s => ({\n name: s.stageName,\n index: s.stageIndex,\n success: s.success,\n output: s.output,\n duration: s.duration,\n tokensUsed: s.tokensUsed,\n model: s.model,\n error: s.error?.message // Include error message if stage failed\n })),\n totalDuration: multiStageResult.totalDuration,\n totalTokens: multiStageResult.totalTokens,\n success: multiStageResult.success,\n failedStage: multiStageResult.failedStage,\n timestamp: new Date().toISOString()\n }, null, 2);\n } else {\n outputData = multiStageResult.finalOutput;\n }\n\n writeFileSync(savePath, outputData, 'utf-8');\n console.log(chalk.green(`\\n✅ Result saved to: ${savePath}\\n`));\n } catch (error) {\n console.log(chalk.yellow(`⚠ Failed to save result: ${(error as Error).message}\\n`));\n }\n }\n\n // Save multi-stage result to memory\n if (argv.saveMemory && memoryManager) {\n try {\n const metadata = {\n type: 'conversation' as const,\n source: 'agent-execution',\n agentId: resolvedAgentName,\n tags: ['agent-execution', resolvedAgentName, 'multi-stage'],\n provider: context.provider.name,\n timestamp: new Date().toISOString()\n };\n\n // FTS5 doesn't need real embeddings - use null\n const embedding = null;\n\n // Build content from multi-stage result\n const content = `Agent: ${resolvedAgentName}\\nTask: ${argv.task}\\n\\nResult: ${multiStageResult.finalOutput}`;\n\n // Save to memory\n await memoryManager.add(content, embedding, metadata);\n\n if (argv.verbose) {\n console.log(chalk.green('✓ Conversation saved to memory'));\n }\n } catch (error) {\n // Don't fail the command if memory save fails\n if (argv.verbose) {\n console.log(chalk.yellow(`⚠ Failed to save to memory: ${(error as Error).message}`));\n }\n }\n }\n\n } else {\n // Use regular AgentExecutor for single-stage execution\n // Configure with orchestration support if managers are available\n const executor = new AgentExecutor({\n sessionManager,\n workspaceManager,\n contextManager,\n profileLoader\n });\n let result: ExecutionResult;\n\n if (argv.timeout) {\n const timeoutMs = argv.timeout * 1000;\n const controller = new AbortController();\n\n const timeoutId = setTimeout(() => {\n controller.abort();\n }, timeoutMs);\n\n try {\n result = await executor.execute(context, {\n verbose: argv.verbose,\n showProgress: !argv.verbose,\n signal: controller.signal\n });\n } finally {\n clearTimeout(timeoutId);\n }\n\n // Check if execution was aborted\n if (controller.signal.aborted) {\n throw new Error(`Execution timeout after ${argv.timeout} seconds`);\n }\n } else {\n result = await executor.execute(context, {\n verbose: argv.verbose,\n showProgress: !argv.verbose\n });\n }\n\n // 9. Format and display result\n const formattedOutput = formatOutput(result, argv.format || 'text', argv.verbose || false);\n console.log(formattedOutput);\n\n // 10. Save result to file\n if (argv.save) {\n try {\n const savePath = argv.save;\n const saveDir = join(savePath, '..');\n await mkdir(saveDir, { recursive: true });\n\n const outputData = formatForSave(result, argv.format || 'text', {\n agent: resolvedAgentName,\n task: argv.task\n });\n\n writeFileSync(savePath, outputData, 'utf-8');\n console.log(chalk.green(`\\n✅ Result saved to: ${savePath}\\n`));\n } catch (error) {\n console.log(chalk.yellow(`⚠ Failed to save result: ${(error as Error).message}\\n`));\n }\n }\n\n // 11. Save result to memory\n if (argv.saveMemory && memoryManager) {\n try {\n const metadata = {\n type: 'conversation' as const,\n source: 'agent-execution',\n agentId: resolvedAgentName,\n tags: ['agent-execution', resolvedAgentName],\n provider: context.provider.name,\n timestamp: new Date().toISOString()\n };\n\n // FTS5 doesn't need real embeddings - use null\n const embedding = null;\n\n // Build content from execution result\n const content = `Agent: ${resolvedAgentName}\\nTask: ${argv.task}\\n\\nResponse: ${result.response.content}`;\n\n // Save to memory\n await memoryManager.add(content, embedding, metadata);\n\n if (argv.verbose) {\n console.log(chalk.green('✓ Conversation saved to memory'));\n }\n } catch (error) {\n // Don't fail the command if memory save fails\n if (argv.verbose) {\n console.log(chalk.yellow(`⚠ Failed to save to memory: ${(error as Error).message}`));\n }\n }\n }\n }\n\n // 12. Cleanup resources\n await contextManager.cleanup(context);\n\n // Clean up memory manager (close database connections)\n if (memoryManager) {\n await memoryManager.close();\n }\n\n // Clean up router (stop health checks)\n if (router) {\n router.destroy();\n }\n\n // Ensure event loop completes all pending operations\n await new Promise(resolve => setImmediate(resolve));\n\n console.log(chalk.green.bold('✅ Complete\\n'));\n\n // Explicitly exit process to prevent hanging\n // (Required for integration tests and clean process termination)\n process.exit(0);\n\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n const executor = new AgentExecutor();\n\n // Display error with helpful suggestions\n executor.displayError(err, resolvedAgentName, { verbose: argv.verbose });\n\n // Log error\n logger.error('Agent execution failed', {\n error: err.message,\n agent: resolvedAgentName,\n task: argv.task,\n provider: argv.provider,\n stack: err.stack\n });\n\n // Cleanup resources even on error\n try {\n if (memoryManager) {\n await memoryManager.close();\n }\n if (router) {\n router.destroy();\n }\n // Clean up context (workspace, temp files)\n if (contextManager && context) {\n await contextManager.cleanup(context).catch(cleanupErr => {\n const errMsg = cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr);\n logger.debug('Context cleanup error', { error: errMsg });\n });\n }\n // Ensure event loop completes all pending operations\n await new Promise(resolve => setImmediate(resolve));\n } catch (cleanupError) {\n const errMsg = cleanupError instanceof Error ? cleanupError.message : String(cleanupError);\n logger.debug('Cleanup error ignored', { error: errMsg });\n }\n\n process.exit(1);\n }\n }\n};\n","/**\n * Context Manager - Create and manage execution contexts for agents\n */\n\nimport { mkdir, chmod } from 'fs/promises';\nimport { join, resolve } from 'path';\nimport type {\n ExecutionContext,\n AgentProfile,\n ContextOptions\n} from '../types/agent.js';\nimport type { Provider } from '../types/provider.js';\nimport type { MemoryEntry } from '../types/memory.js';\nimport type { OrchestrationMetadata, Session } from '../types/orchestration.js';\nimport { ProfileLoader } from './profile-loader.js';\nimport { AbilitiesManager } from './abilities-manager.js';\nimport type { IMemoryManager } from '../types/memory.js';\nimport type { SessionManager } from '../core/session-manager.js';\nimport type { WorkspaceManager } from '../core/workspace-manager.js';\nimport { Router } from '../core/router.js';\nimport { PathResolver } from '../core/path-resolver.js';\nimport { logger } from '../utils/logger.js';\nimport { PathError, ProviderError } from '../utils/errors.js';\n\n/**\n * Provider name aliases (v5.0.7 fix)\n * Maps team config names to actual registered provider names\n */\nconst PROVIDER_ALIASES: Record<string, string> = {\n 'claude': 'claude-code',\n 'gemini': 'gemini-cli',\n 'codex': 'openai',\n 'openai': 'openai'\n};\n\nexport interface ContextManagerConfig {\n profileLoader: ProfileLoader;\n abilitiesManager: AbilitiesManager;\n memoryManager: IMemoryManager | null;\n router: Router;\n pathResolver: PathResolver;\n sessionManager?: SessionManager;\n workspaceManager?: WorkspaceManager;\n}\n\n/**\n * Context Manager - Create and manage execution contexts\n */\nexport class ContextManager {\n private config: ContextManagerConfig;\n\n constructor(config: ContextManagerConfig) {\n this.config = config;\n }\n\n /**\n * Create execution context for an agent task\n */\n async createContext(\n agentName: string,\n task: string,\n options?: ContextOptions\n ): Promise<ExecutionContext> {\n logger.info('Creating execution context', { agentName, task });\n\n // 1. Resolve agent name (supports displayName)\n const resolvedName = await this.config.profileLoader.resolveAgentName(agentName);\n logger.debug('Agent name resolved', {\n input: agentName,\n resolved: resolvedName\n });\n\n // 2. Load agent profile\n const agent = await this.config.profileLoader.loadProfile(resolvedName);\n\n // 3. Load abilities (smart selection based on task)\n const selectedAbilities = this.selectAbilities(agent, task);\n const abilities = await this.config.abilitiesManager.getAbilitiesText(\n selectedAbilities\n );\n\n logger.debug('Abilities selected', {\n total: agent.abilities.length,\n selected: selectedAbilities.length,\n abilities: selectedAbilities\n });\n\n // 4. Select provider (v4.10.0+: team-based → agent-based → router)\n const provider = await this.selectProviderForAgent(agent, options);\n\n // 5. Get paths\n const projectDir = await this.config.pathResolver.detectProjectRoot();\n const workingDir = process.cwd();\n\n // Security: Sanitize agent name for directory (prevent path traversal)\n const agentDirName = agent.name.replace(/[^a-zA-Z0-9-]/g, '-').toLowerCase();\n const agentWorkspace = join(projectDir, '.automatosx', 'workspaces', agentDirName);\n\n // Security: Verify workspace is within project boundary\n const resolvedWorkspace = resolve(agentWorkspace);\n const resolvedProject = resolve(projectDir);\n if (!resolvedWorkspace.startsWith(resolvedProject)) {\n throw PathError.traversal(agentWorkspace);\n }\n\n // 6. Create workspace with restricted permissions\n await mkdir(agentWorkspace, { recursive: true });\n\n // Security: Set restrictive permissions on Unix (700 = owner only)\n if (process.platform !== 'win32') {\n await chmod(agentWorkspace, 0o700);\n }\n\n logger.debug('Agent workspace created', { workspace: agentWorkspace });\n\n // 7. Handle session (if sessionId provided)\n let session: Session | undefined;\n if (options?.sessionId) {\n if (!this.config.sessionManager) {\n throw new Error(\n `SessionManager not configured but session ID was provided: ${options.sessionId}`\n );\n }\n\n const foundSession = await this.config.sessionManager.getSession(options.sessionId);\n if (!foundSession) {\n throw new Error(\n `Session not found: ${options.sessionId}. Please verify the session ID or create a new session.`\n );\n }\n session = foundSession;\n }\n\n // 8. Build orchestration metadata (v4.7.8+: all agents can delegate)\n let orchestration: OrchestrationMetadata | undefined;\n if (this.config.workspaceManager && this.config.profileLoader) {\n // Get list of available agents for delegation\n const allAgents = await this.config.profileLoader.listProfiles();\n\n // v4.7.8+: All agents can delegate by default\n // Only exclude self to prevent direct self-delegation (cycles still detected)\n const availableAgents = allAgents.filter(a => a !== agent.name);\n\n // Get shared workspace path\n const sharedWorkspace = session\n ? join(projectDir, '.automatosx', 'workspaces', 'shared', 'sessions', session.id)\n : join(projectDir, '.automatosx', 'workspaces', 'shared', 'persistent');\n\n // Respect maxDelegationDepth from agent config, default to 2\n const maxDelegationDepth = agent.orchestration?.maxDelegationDepth ?? 2;\n\n orchestration = {\n isDelegationEnabled: true,\n availableAgents,\n sharedWorkspace,\n delegationChain: options?.delegationChain || [],\n maxDelegationDepth\n };\n\n logger.debug('Orchestration metadata built', {\n availableAgents,\n sharedWorkspace,\n delegationChain: orchestration.delegationChain,\n maxDelegationDepth\n });\n }\n\n // 9. Create context\n const context: ExecutionContext = {\n agent,\n task,\n memory: [],\n projectDir,\n workingDir,\n agentWorkspace,\n provider,\n abilities,\n createdAt: new Date(),\n orchestration,\n session\n };\n\n // 10. Inject memory (if not skipped)\n if (!options?.skipMemory) {\n await this.injectMemory(\n context,\n task,\n options?.memoryLimit\n );\n }\n\n logger.info('Execution context created', {\n agent: agent.name,\n provider: provider.name,\n memoryEntries: context.memory.length,\n hasAbilities: abilities.length > 0,\n hasOrchestration: !!orchestration,\n isDelegationEnabled: orchestration?.isDelegationEnabled ?? false\n });\n\n return context;\n }\n\n /**\n * Inject memory into context (search by task)\n */\n async injectMemory(\n context: ExecutionContext,\n query?: string,\n limit: number = 5\n ): Promise<void> {\n // Skip if no memory manager available\n if (!this.config.memoryManager) {\n logger.debug('Memory injection skipped: no memory manager available');\n context.memory = [];\n return;\n }\n\n const searchQuery = query || context.task;\n\n try {\n const results = await this.config.memoryManager.search({\n text: searchQuery,\n limit\n });\n\n context.memory = results.map(r => r.entry);\n\n logger.debug('Memory injected', {\n query: searchQuery,\n count: context.memory.length\n });\n\n } catch (error) {\n logger.warn('Failed to inject memory', {\n error: (error as Error).message\n });\n // Continue without memory\n context.memory = [];\n }\n }\n\n /**\n * Select abilities based on task keywords (smart selection)\n */\n private selectAbilities(agent: AgentProfile, task: string): string[] {\n // If no abilitySelection config, load all abilities (backward compatible)\n if (!agent.abilitySelection || agent.abilitySelection.loadAll) {\n return agent.abilities || [];\n }\n\n const taskLower = task.toLowerCase();\n const selectedAbilities = new Set<string>();\n const availableAbilities = new Set(agent.abilities || []);\n\n // Always load core abilities\n if (agent.abilitySelection.core) {\n agent.abilitySelection.core.forEach(a => {\n if (availableAbilities.has(a)) {\n selectedAbilities.add(a);\n } else {\n logger.warn('Core ability not found in agent abilities list', {\n ability: a,\n agent: agent.name\n });\n }\n });\n }\n\n // Task-based selection\n if (agent.abilitySelection.taskBased) {\n for (const [keyword, abilities] of Object.entries(agent.abilitySelection.taskBased)) {\n if (taskLower.includes(keyword.toLowerCase())) {\n abilities.forEach(a => {\n if (availableAbilities.has(a)) {\n selectedAbilities.add(a);\n } else {\n logger.warn('Task-based ability not found in agent abilities list', {\n ability: a,\n keyword,\n agent: agent.name\n });\n }\n });\n logger.debug('Task keyword matched', { keyword, abilities: abilities.filter(a => availableAbilities.has(a)) });\n }\n }\n }\n\n // If no task-based matches, return core abilities only\n const selected = Array.from(selectedAbilities);\n\n // Fallback: if no abilities selected, load core or first 2 abilities\n if (selected.length === 0) {\n logger.debug('No task-based matches, using fallback');\n return agent.abilities.slice(0, 2);\n }\n\n return selected;\n }\n\n /**\n * Select provider for an agent (v4.10.0+: team-based configuration)\n * Priority: CLI option → team config → agent config → router\n */\n async selectProviderForAgent(\n agent: AgentProfile,\n options?: ContextOptions\n ): Promise<Provider> {\n // 1. CLI option overrides everything\n if (options?.provider) {\n const provider = await this.tryGetProvider(options.provider);\n if (provider) {\n logger.debug('Using CLI-specified provider', { provider: options.provider });\n return provider;\n }\n }\n\n // 2. Try team configuration (v4.10.0+)\n if (agent.team) {\n try {\n const teamConfig = await this.config.profileLoader.getTeamConfig(agent.name);\n if (teamConfig) {\n logger.debug('Using team provider configuration', {\n agent: agent.name,\n team: teamConfig.name,\n primary: teamConfig.provider.primary\n });\n\n // Try fallbackChain if specified, otherwise use primary + fallback\n const providersToTry = teamConfig.provider.fallbackChain ||\n [teamConfig.provider.primary, teamConfig.provider.fallback].filter((p): p is string => Boolean(p));\n\n for (const providerName of providersToTry) {\n const provider = await this.tryGetProvider(providerName);\n if (provider) {\n if (providerName !== teamConfig.provider.primary) {\n logger.info('Team primary provider unavailable, using fallback', {\n team: teamConfig.name,\n primary: teamConfig.provider.primary,\n using: providerName\n });\n }\n return provider;\n }\n }\n\n logger.warn('All team providers unavailable, falling back to router', {\n team: teamConfig.name,\n triedProviders: providersToTry\n });\n }\n } catch (error) {\n logger.warn('Failed to load team configuration, using agent defaults', {\n agent: agent.name,\n team: agent.team,\n error: (error as Error).message\n });\n }\n }\n\n // 3. Fallback to agent's own configuration (deprecated but supported)\n if (agent.provider || agent.fallbackProvider) {\n logger.debug('Using agent provider configuration (deprecated)', {\n agent: agent.name,\n provider: agent.provider,\n fallback: agent.fallbackProvider\n });\n\n return await this.selectProvider(agent.provider, agent.fallbackProvider);\n }\n\n // 4. Final fallback: use router (global priority)\n const provider = await this.config.router.selectProvider();\n if (!provider) {\n throw ProviderError.noAvailableProviders();\n }\n\n logger.info('Using router-selected provider', {\n provider: provider.name,\n agent: agent.name\n });\n\n return provider;\n }\n\n /**\n * Try to get a specific provider if available\n */\n /**\n * Try to get provider by name, with alias support (v5.0.7+)\n */\n private async tryGetProvider(providerName: string): Promise<Provider | undefined> {\n const availableProviders = await this.config.router.getAvailableProviders();\n\n // Try exact match first\n let provider = availableProviders.find(p => p.name === providerName);\n if (provider) {\n return provider;\n }\n\n // Try alias mapping (e.g., 'claude' → 'claude-code')\n const aliasedName = PROVIDER_ALIASES[providerName];\n if (aliasedName) {\n provider = availableProviders.find(p => p.name === aliasedName);\n if (provider) {\n logger.debug('Resolved provider via alias', {\n requested: providerName,\n resolved: aliasedName\n });\n return provider;\n }\n }\n\n return undefined;\n }\n\n /**\n * Select provider (from agent preference or router)\n * Tries: primary → fallback → router (global priority)\n * @deprecated v4.10.0+ Use selectProviderForAgent instead\n */\n async selectProvider(\n preferredProvider?: string,\n fallbackProvider?: string\n ): Promise<Provider> {\n const availableProviders = await this.config.router.getAvailableProviders();\n\n // 1. Try primary provider\n if (preferredProvider) {\n const provider = availableProviders.find(p => p.name === preferredProvider);\n\n if (provider) {\n logger.debug('Using primary provider', { provider: preferredProvider });\n return provider;\n }\n\n logger.warn('Primary provider not available', {\n primary: preferredProvider\n });\n }\n\n // 2. Try fallback provider\n if (fallbackProvider) {\n const provider = availableProviders.find(p => p.name === fallbackProvider);\n\n if (provider) {\n logger.info('Using fallback provider', {\n fallback: fallbackProvider,\n primary: preferredProvider\n });\n return provider;\n }\n\n logger.warn('Fallback provider not available', {\n fallback: fallbackProvider\n });\n }\n\n // 3. Use router to select best provider (global priority)\n const provider = await this.config.router.selectProvider();\n\n if (!provider) {\n throw ProviderError.noAvailableProviders();\n }\n\n logger.info('Using router-selected provider (final fallback)', {\n provider: provider.name,\n primary: preferredProvider,\n fallback: fallbackProvider\n });\n return provider;\n }\n\n /**\n * Cleanup context (delete workspace if needed)\n */\n async cleanup(context: ExecutionContext): Promise<void> {\n // For now, keep workspace for debugging\n // In future, add option to auto-cleanup\n logger.debug('Context cleanup', {\n agent: context.agent.name,\n workspace: context.agentWorkspace\n });\n }\n}\n","/**\n * Profile Loader - Load and validate agent profiles from YAML\n */\n\nimport { readFile, readdir } from 'fs/promises';\nimport { join, extname, basename, dirname } from 'path';\nimport { fileURLToPath } from 'url';\nimport { load } from 'js-yaml';\nimport type { AgentProfile } from '../types/agent.js';\nimport { AgentValidationError, AgentNotFoundError } from '../types/agent.js';\nimport { logger } from '../utils/logger.js';\nimport { TTLCache } from '../core/cache.js';\nimport type { TeamManager } from '../core/team-manager.js';\nimport type { TeamConfig } from '../types/team.js';\n\n// Get the directory of this file for locating built-in agents\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\n// Get package root - handle both dev (src/) and prod (dist/) scenarios\nfunction getPackageRoot(): string {\n // In production, __dirname will be dist/\n // In development, __dirname will be src/agents/\n const currentDir = __dirname;\n\n // If we're in dist/, go up one level to package root\n // If we're in src/agents/, go up two levels to package root\n if (currentDir.includes('/dist')) {\n return join(currentDir, '..');\n } else {\n return join(currentDir, '../..');\n }\n}\n\n/**\n * Profile Loader - Load and validate agent profiles\n */\nexport class ProfileLoader {\n private profilesDir: string;\n private fallbackProfilesDir: string;\n private cache: TTLCache<AgentProfile>;\n private displayNameMap: Map<string, string> = new Map();\n private mapInitialized: boolean = false;\n private teamManager?: TeamManager;\n\n constructor(profilesDir: string, fallbackProfilesDir?: string, teamManager?: TeamManager) {\n this.profilesDir = profilesDir;\n // Default fallback to built-in examples/agents\n // This should work in both dev and production environments\n this.fallbackProfilesDir = fallbackProfilesDir || join(getPackageRoot(), 'examples/agents');\n // Use TTLCache with 5 minute TTL for profile caching\n this.cache = new TTLCache<AgentProfile>({\n maxEntries: 20,\n ttl: 300000, // 5 minutes\n cleanupInterval: 60000, // Cleanup every minute\n debug: false\n });\n // v4.10.0+: Optional TeamManager for team-based configuration\n this.teamManager = teamManager;\n }\n\n /**\n * Build displayName → name mapping table (lightweight)\n * Only reads displayName field from YAML, doesn't load full profile\n * Priority: Local .automatosx/agents override examples/agents\n */\n private async buildDisplayNameMap(): Promise<void> {\n if (this.mapInitialized) {\n return;\n }\n\n logger.debug('Building displayName mapping table');\n this.displayNameMap.clear();\n\n try {\n // Priority 1: Process local profiles first (.automatosx/agents)\n const localProfiles = await this.listProfilesFromDir(this.profilesDir);\n for (const name of localProfiles) {\n await this.addToDisplayNameMap(name, 'local');\n }\n\n // Priority 2: Process fallback profiles (examples/agents)\n // These will NOT override local profiles with the same displayName\n const fallbackProfiles = await this.listProfilesFromDir(this.fallbackProfilesDir);\n for (const name of fallbackProfiles) {\n // Skip if already exists in local profiles (by name)\n if (localProfiles.includes(name)) {\n logger.debug('Skipping fallback profile (local override)', { name });\n continue;\n }\n await this.addToDisplayNameMap(name, 'fallback');\n }\n\n this.mapInitialized = true;\n logger.info('DisplayName mapping built', {\n mappings: this.displayNameMap.size,\n localProfiles: localProfiles.length,\n fallbackProfiles: fallbackProfiles.length\n });\n } catch (error) {\n logger.error('Failed to build displayName mapping', { error });\n // Don't throw - allow fallback to direct name lookup\n }\n }\n\n /**\n * Helper: Add profile to displayName map\n */\n private async addToDisplayNameMap(name: string, source: 'local' | 'fallback'): Promise<void> {\n try {\n // Lightweight: Only read displayName field, not full profile\n const displayName = await this.readDisplayNameOnly(name);\n\n if (displayName) {\n const lowerDisplayName = displayName.toLowerCase();\n\n // Check for duplicate display names\n const existing = this.displayNameMap.get(lowerDisplayName);\n if (existing) {\n logger.warn('Duplicate displayName detected', {\n displayName,\n existingAgent: existing,\n newAgent: name,\n source,\n resolution: `Keeping existing (${existing})`\n });\n // Keep existing entry (local profiles have priority)\n return;\n }\n\n // Store case-insensitive mapping\n this.displayNameMap.set(lowerDisplayName, name);\n logger.debug('Mapped displayName to agent', {\n displayName,\n name,\n source\n });\n }\n } catch (error) {\n // Skip profiles that fail to read\n logger.warn('Failed to read displayName for mapping', { name, source, error });\n }\n }\n\n /**\n * Helper: List profiles from a specific directory\n */\n private async listProfilesFromDir(dir: string): Promise<string[]> {\n try {\n const files = await readdir(dir);\n return files\n .filter(file => extname(file) === '.yaml' || extname(file) === '.yml')\n .map(file => basename(file, extname(file)));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n // Directory doesn't exist\n return [];\n }\n throw error;\n }\n }\n\n /**\n * Read only displayName field from YAML (lightweight, no full parsing)\n * Returns null if no displayName or file doesn't exist\n */\n private async readDisplayNameOnly(name: string): Promise<string | null> {\n const profilePaths = this.getProfilePath(name);\n\n for (const profilePath of profilePaths) {\n try {\n const content = await readFile(profilePath, 'utf-8');\n\n // Security: Limit file size check (same as loadProfile)\n if (content.length > 100 * 1024) {\n continue;\n }\n\n // Parse YAML to extract only displayName\n const data = load(content) as any;\n return data.displayName || null;\n\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n // File not found, try next path\n continue;\n }\n // Other errors, skip this profile\n return null;\n }\n }\n\n return null;\n }\n\n /**\n * Resolve agent identifier (name or displayName) to actual profile name\n * Optimized: Try direct load first, only build full mapping if needed\n */\n async resolveAgentName(identifier: string): Promise<string> {\n // Optimization: Try direct profile load first (most common case)\n // This avoids loading all profiles when using profile names directly\n try {\n await this.loadProfile(identifier);\n // If load succeeds, identifier is a valid profile name\n logger.debug('Using identifier as profile name (direct match)', { identifier });\n return identifier;\n } catch (error) {\n // Profile not found directly, might be a displayName\n // Only now build the displayName mapping if not already done\n if ((error as any).name === 'AgentNotFoundError') {\n logger.debug('Direct profile load failed, trying displayName lookup', { identifier });\n\n // Build map lazily if not already built\n await this.buildDisplayNameMap();\n\n // Try case-insensitive displayName lookup\n const resolved = this.displayNameMap.get(identifier.toLowerCase());\n if (resolved) {\n logger.debug('Resolved displayName to agent name', {\n displayName: identifier,\n name: resolved\n });\n return resolved;\n }\n\n // Still not found, throw the original error\n throw error;\n }\n\n // Other errors (validation, etc.) should be propagated\n throw error;\n }\n }\n\n /**\n * Load a specific agent profile\n */\n async loadProfile(name: string): Promise<AgentProfile> {\n // Check cache first\n const cached = this.cache.get(name);\n if (cached) {\n logger.debug('Profile loaded from cache', { name });\n return cached;\n }\n\n // Get possible paths (primary and fallback)\n const profilePaths = this.getProfilePath(name);\n\n // Try each path in order\n for (const profilePath of profilePaths) {\n try {\n const content = await readFile(profilePath, 'utf-8');\n\n // Security: Limit file size to prevent DoS (max 100KB for profile)\n if (content.length > 100 * 1024) {\n throw new AgentValidationError('Profile file too large (max 100KB)');\n }\n\n // Security: Use safe YAML parsing (default safe schema)\n // Note: js-yaml's load() already uses safe schema by default\n const data = load(content) as any;\n\n // Validate and build profile (v4.10.0+: async for team inheritance)\n const profile = await this.buildProfile(data, name);\n\n // Cache it\n this.cache.set(name, profile);\n\n logger.info('Profile loaded', { name, path: profilePath });\n return profile;\n\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n // File not found, try next path\n continue;\n }\n // Other errors should be thrown immediately\n throw error;\n }\n }\n\n // If we've tried all paths and none worked, throw AgentNotFoundError\n throw new AgentNotFoundError(name);\n }\n\n /**\n * List all available profiles\n */\n async listProfiles(): Promise<string[]> {\n const profileSet = new Set<string>();\n\n // Try to load from primary directory\n try {\n const files = await readdir(this.profilesDir);\n const profiles = files\n .filter(file => extname(file) === '.yaml' || extname(file) === '.yml')\n .map(file => basename(file, extname(file)));\n\n profiles.forEach(p => profileSet.add(p));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw error;\n }\n // Directory doesn't exist, will fallback to built-in agents\n }\n\n // Also load from fallback directory (built-in agents)\n try {\n const files = await readdir(this.fallbackProfilesDir);\n const profiles = files\n .filter(file => extname(file) === '.yaml' || extname(file) === '.yml')\n .map(file => basename(file, extname(file)));\n\n profiles.forEach(p => profileSet.add(p));\n } catch (error) {\n // Fallback directory doesn't exist - this is OK\n logger.debug('Fallback profiles directory not found', {\n dir: this.fallbackProfilesDir\n });\n }\n\n return Array.from(profileSet).sort();\n }\n\n /**\n * Calculate Levenshtein distance between two strings (for fuzzy matching)\n */\n private levenshteinDistance(a: string, b: string): number {\n const matrix: number[][] = [];\n\n for (let i = 0; i <= b.length; i++) {\n matrix[i] = [i];\n }\n\n for (let j = 0; j <= a.length; j++) {\n matrix[0]![j] = j;\n }\n\n for (let i = 1; i <= b.length; i++) {\n for (let j = 1; j <= a.length; j++) {\n if (b.charAt(i - 1) === a.charAt(j - 1)) {\n matrix[i]![j] = matrix[i - 1]![j - 1]!;\n } else {\n matrix[i]![j] = Math.min(\n matrix[i - 1]![j - 1]! + 1, // substitution\n matrix[i]![j - 1]! + 1, // insertion\n matrix[i - 1]![j]! + 1 // deletion\n );\n }\n }\n }\n\n return matrix[b.length]![a.length]!;\n }\n\n /**\n * Find similar agent names using fuzzy matching\n * Returns agents sorted by similarity (most similar first)\n */\n async findSimilarAgents(query: string, maxResults: number = 3): Promise<Array<{ name: string; displayName?: string; role?: string; distance: number }>> {\n const allProfiles = await this.listProfiles();\n const similarities: Array<{ name: string; displayName?: string; role?: string; distance: number }> = [];\n\n // Build displayName map if not already done\n await this.buildDisplayNameMap();\n\n for (const profileName of allProfiles) {\n try {\n // Calculate distance for profile name\n const nameDistance = this.levenshteinDistance(query.toLowerCase(), profileName.toLowerCase());\n\n // Try to get displayName and role for better matching\n const displayName = await this.readDisplayNameOnly(profileName);\n let minDistance = nameDistance;\n\n // Also check distance with displayName\n if (displayName) {\n const displayDistance = this.levenshteinDistance(query.toLowerCase(), displayName.toLowerCase());\n minDistance = Math.min(minDistance, displayDistance);\n }\n\n // Load profile to get role (suppress logs)\n try {\n const cached = this.cache.get(profileName);\n let profile: AgentProfile | undefined = cached;\n\n if (!profile) {\n // Load without logging (for similarity search)\n const profilePaths = this.getProfilePath(profileName);\n for (const profilePath of profilePaths) {\n try {\n const content = await readFile(profilePath, 'utf-8');\n if (content.length > 100 * 1024) continue;\n const data = load(content) as any;\n profile = await this.buildProfile(data, profileName);\n this.cache.set(profileName, profile);\n break;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n continue;\n }\n throw error;\n }\n }\n }\n\n if (profile) {\n const roleDistance = this.levenshteinDistance(query.toLowerCase(), profile.role.toLowerCase());\n minDistance = Math.min(minDistance, roleDistance);\n\n similarities.push({\n name: profileName,\n displayName: displayName || undefined,\n role: profile.role,\n distance: minDistance\n });\n } else {\n // Profile not found, just use name/displayName distance\n similarities.push({\n name: profileName,\n displayName: displayName || undefined,\n distance: minDistance\n });\n }\n } catch {\n // If profile fails to load, just use name/displayName distance\n similarities.push({\n name: profileName,\n displayName: displayName || undefined,\n distance: minDistance\n });\n }\n } catch (error) {\n // Skip profiles that fail\n logger.debug('Failed to calculate similarity', { profileName, error });\n }\n }\n\n // Sort by distance (lower is better) and return top N\n return similarities\n .sort((a, b) => a.distance - b.distance)\n .slice(0, maxResults);\n }\n\n /**\n * Validate profile structure\n */\n validateProfile(profile: AgentProfile): boolean {\n const required = ['name', 'role', 'description', 'systemPrompt'];\n\n for (const field of required) {\n if (!profile[field as keyof AgentProfile]) {\n throw new AgentValidationError(`Missing required field: ${field}`);\n }\n }\n\n // Validate types\n if (typeof profile.name !== 'string') {\n throw new AgentValidationError('name must be a string');\n }\n\n if (typeof profile.role !== 'string') {\n throw new AgentValidationError('role must be a string');\n }\n\n if (typeof profile.description !== 'string') {\n throw new AgentValidationError('description must be a string');\n }\n\n if (typeof profile.systemPrompt !== 'string') {\n throw new AgentValidationError('systemPrompt must be a string');\n }\n\n // Validate optional fields\n if (profile.abilities && !Array.isArray(profile.abilities)) {\n throw new AgentValidationError('abilities must be an array');\n }\n\n if (profile.temperature !== undefined) {\n if (typeof profile.temperature !== 'number' || profile.temperature < 0 || profile.temperature > 1) {\n throw new AgentValidationError('temperature must be a number between 0 and 1');\n }\n }\n\n if (profile.maxTokens !== undefined) {\n if (typeof profile.maxTokens !== 'number' || profile.maxTokens < 1) {\n throw new AgentValidationError('maxTokens must be a positive number');\n }\n }\n\n // Validate v4.1+ enhanced fields\n if (profile.stages !== undefined) {\n if (!Array.isArray(profile.stages)) {\n throw new AgentValidationError('stages must be an array');\n }\n\n profile.stages.forEach((stage, i) => {\n if (!stage.name || typeof stage.name !== 'string') {\n throw new AgentValidationError(`stages[${i}].name is required and must be a string`);\n }\n if (!stage.description || typeof stage.description !== 'string') {\n throw new AgentValidationError(`stages[${i}].description is required and must be a string`);\n }\n if (stage.key_questions !== undefined && !Array.isArray(stage.key_questions)) {\n throw new AgentValidationError(`stages[${i}].key_questions must be an array`);\n }\n if (stage.outputs !== undefined && !Array.isArray(stage.outputs)) {\n throw new AgentValidationError(`stages[${i}].outputs must be an array`);\n }\n if (stage.model !== undefined && typeof stage.model !== 'string') {\n throw new AgentValidationError(`stages[${i}].model must be a string`);\n }\n if (stage.temperature !== undefined) {\n if (typeof stage.temperature !== 'number' || stage.temperature < 0 || stage.temperature > 1) {\n throw new AgentValidationError(`stages[${i}].temperature must be a number between 0 and 1`);\n }\n }\n });\n }\n\n if (profile.personality !== undefined) {\n if (typeof profile.personality !== 'object' || profile.personality === null || Array.isArray(profile.personality)) {\n throw new AgentValidationError('personality must be an object');\n }\n // Validate personality fields if present\n const p = profile.personality;\n if (p.traits !== undefined && !Array.isArray(p.traits)) {\n throw new AgentValidationError('personality.traits must be an array');\n }\n if (p.catchphrase !== undefined && typeof p.catchphrase !== 'string') {\n throw new AgentValidationError('personality.catchphrase must be a string');\n }\n if (p.communication_style !== undefined && typeof p.communication_style !== 'string') {\n throw new AgentValidationError('personality.communication_style must be a string');\n }\n if (p.decision_making !== undefined && typeof p.decision_making !== 'string') {\n throw new AgentValidationError('personality.decision_making must be a string');\n }\n }\n\n if (profile.thinking_patterns !== undefined) {\n if (!Array.isArray(profile.thinking_patterns)) {\n throw new AgentValidationError('thinking_patterns must be an array');\n }\n }\n\n // Validate v4.5.8+ abilitySelection\n if (profile.abilitySelection !== undefined) {\n const as = profile.abilitySelection;\n\n if (typeof as !== 'object' || as === null || Array.isArray(as)) {\n throw new AgentValidationError('abilitySelection must be an object');\n }\n\n if (as.core !== undefined) {\n if (!Array.isArray(as.core)) {\n throw new AgentValidationError('abilitySelection.core must be an array');\n }\n // Validate core abilities are strings\n as.core.forEach((ability, i) => {\n if (typeof ability !== 'string') {\n throw new AgentValidationError(`abilitySelection.core[${i}] must be a string`);\n }\n });\n }\n\n if (as.taskBased !== undefined) {\n if (typeof as.taskBased !== 'object' || as.taskBased === null || Array.isArray(as.taskBased)) {\n throw new AgentValidationError('abilitySelection.taskBased must be an object');\n }\n // Validate taskBased structure: keyword -> abilities[]\n Object.entries(as.taskBased).forEach(([keyword, abilities]) => {\n if (!Array.isArray(abilities)) {\n throw new AgentValidationError(`abilitySelection.taskBased[\"${keyword}\"] must be an array`);\n }\n abilities.forEach((ability, i) => {\n if (typeof ability !== 'string') {\n throw new AgentValidationError(`abilitySelection.taskBased[\"${keyword}\"][${i}] must be a string`);\n }\n });\n });\n }\n\n if (as.loadAll !== undefined && typeof as.loadAll !== 'boolean') {\n throw new AgentValidationError('abilitySelection.loadAll must be a boolean');\n }\n }\n\n // Validate v4.7.0+ orchestration\n if (profile.orchestration !== undefined) {\n const orch = profile.orchestration;\n\n if (typeof orch !== 'object' || orch === null || Array.isArray(orch)) {\n throw new AgentValidationError('orchestration must be an object');\n }\n\n // v4.9.0: canDelegate is deprecated and ignored\n if ((orch as any).canDelegate !== undefined) {\n logger.warn('orchestration.canDelegate is deprecated and ignored (v4.9.0+). All agents can delegate by default.', {\n agent: profile.name\n });\n }\n\n if (orch.maxDelegationDepth !== undefined) {\n if (typeof orch.maxDelegationDepth !== 'number' || orch.maxDelegationDepth < 0 || !Number.isInteger(orch.maxDelegationDepth)) {\n throw new AgentValidationError('orchestration.maxDelegationDepth must be a non-negative integer (0 = no delegation allowed)');\n }\n }\n\n if (orch.canReadWorkspaces !== undefined) {\n if (!Array.isArray(orch.canReadWorkspaces)) {\n throw new AgentValidationError('orchestration.canReadWorkspaces must be an array');\n }\n orch.canReadWorkspaces.forEach((workspace, i) => {\n if (typeof workspace !== 'string') {\n throw new AgentValidationError(`orchestration.canReadWorkspaces[${i}] must be a string`);\n }\n });\n }\n\n if (orch.canWriteToShared !== undefined && typeof orch.canWriteToShared !== 'boolean') {\n throw new AgentValidationError('orchestration.canWriteToShared must be a boolean');\n }\n }\n\n return true;\n }\n\n /**\n * Get profile path (with path traversal protection)\n * Returns an array of possible paths to try (primary first, then fallback)\n */\n getProfilePath(name: string): string[] {\n // Security: Prevent path traversal attacks\n // Only allow alphanumeric, dash, underscore in profile names\n if (!/^[a-zA-Z0-9_-]+$/.test(name)) {\n throw new AgentValidationError(`Invalid profile name: ${name}. Only alphanumeric characters, dashes, and underscores are allowed.`);\n }\n\n // Return paths to try in order: primary directory, then fallback\n return [\n join(this.profilesDir, `${name}.yaml`),\n join(this.fallbackProfilesDir, `${name}.yaml`)\n ];\n }\n\n /**\n * Clear cache and displayName mapping\n */\n clearCache(): void {\n this.cache.clear();\n this.displayNameMap.clear();\n this.mapInitialized = false;\n logger.debug('Cache and displayName mapping cleared');\n }\n\n /**\n * Build profile from raw data with defaults\n * v4.10.0+: Supports team-based configuration inheritance\n */\n private async buildProfile(data: any, name: string): Promise<AgentProfile> {\n let teamConfig: TeamConfig | undefined;\n\n // v4.10.0+: Load team configuration if specified\n if (data.team && this.teamManager) {\n try {\n teamConfig = await this.teamManager.loadTeam(data.team);\n logger.debug('Team configuration loaded for agent', {\n agent: name,\n team: data.team\n });\n } catch (error) {\n logger.warn('Failed to load team configuration, using agent defaults', {\n agent: name,\n team: data.team,\n error: (error as Error).message\n });\n }\n }\n\n // Merge abilities: team's sharedAbilities + agent's abilities\n const abilities = data.abilities || [];\n if (teamConfig?.sharedAbilities) {\n // Combine team shared abilities with agent-specific abilities\n // Remove duplicates using Set\n const allAbilities = [...new Set([...teamConfig.sharedAbilities, ...abilities])];\n logger.debug('Merged abilities from team', {\n agent: name,\n team: teamConfig.name,\n teamAbilities: teamConfig.sharedAbilities.length,\n agentAbilities: abilities.length,\n totalAbilities: allAbilities.length\n });\n abilities.splice(0, abilities.length, ...allAbilities);\n }\n\n // Merge orchestration: team defaults + agent overrides\n let orchestration = data.orchestration;\n if (teamConfig?.orchestration && !orchestration) {\n // Use team orchestration defaults if agent doesn't specify its own\n orchestration = teamConfig.orchestration;\n logger.debug('Using team orchestration defaults', {\n agent: name,\n team: teamConfig.name\n });\n }\n\n const profile: AgentProfile = {\n name: data.name || name,\n displayName: data.displayName,\n role: data.role,\n description: data.description,\n // v4.10.0+: Team field\n team: data.team,\n systemPrompt: data.systemPrompt,\n abilities: abilities,\n // Enhanced v4.1+ features\n stages: data.stages,\n personality: data.personality,\n thinking_patterns: data.thinking_patterns,\n abilitySelection: data.abilitySelection,\n // Provider preferences (deprecated, kept for backward compatibility)\n provider: data.provider,\n model: data.model,\n temperature: data.temperature,\n maxTokens: data.maxTokens,\n // Optional\n tags: data.tags,\n version: data.version,\n metadata: data.metadata,\n // v4.7.0+ Orchestration (merged with team defaults)\n orchestration: orchestration\n };\n\n // Validate\n this.validateProfile(profile);\n\n return profile;\n }\n\n /**\n * Get team configuration for an agent (if available)\n * v4.10.0+: Used by ContextManager to get provider configuration\n */\n async getTeamConfig(agentName: string): Promise<TeamConfig | undefined> {\n if (!this.teamManager) {\n return undefined;\n }\n\n try {\n const profile = await this.loadProfile(agentName);\n if (profile.team) {\n return await this.teamManager.loadTeam(profile.team);\n }\n } catch (error) {\n logger.warn('Failed to get team config for agent', {\n agent: agentName,\n error: (error as Error).message\n });\n }\n\n return undefined;\n }\n}\n","/**\n * Agent Types - Agent Profile and Execution Context\n */\n\nimport type { Provider } from './provider.js';\nimport type { MemoryEntry } from './memory.js';\nimport type { OrchestrationConfig, OrchestrationMetadata, Session } from './orchestration.js';\n\n/**\n * Stage - A step in the agent's workflow\n */\nexport interface Stage {\n name: string;\n description: string;\n key_questions?: string[];\n outputs?: string[];\n\n /**\n * @deprecated Model and temperature are now configured at team level.\n * These fields are ignored. Configure provider behavior via CLI config files:\n * - Claude: Claude Code settings\n * - Gemini: ~/.config/gemini/settings.json\n * - Codex: ~/.codex/config.toml\n */\n model?: string;\n temperature?: number;\n\n // Phase 3: Advanced stage features\n dependencies?: string[]; // Stage names this stage depends on\n condition?: string; // Conditional execution (e.g., \"previous.success\")\n parallel?: boolean; // Can this stage run in parallel with others?\n streaming?: boolean; // Enable streaming output for this stage\n saveToMemory?: boolean; // Persist this stage's results to memory\n}\n\n/**\n * Personality - Defines agent's character and behavior\n */\nexport interface Personality {\n traits?: string[];\n catchphrase?: string;\n communication_style?: string;\n decision_making?: string;\n}\n\n/**\n * Ability Selection Strategy - How to select abilities for different tasks\n */\nexport interface AbilitySelection {\n // Core abilities always loaded\n core?: string[];\n // Task-based ability mapping (keyword -> abilities)\n taskBased?: Record<string, string[]>;\n // Load all abilities (default behavior)\n loadAll?: boolean;\n}\n\n/**\n * Agent Profile - Loaded from YAML\n */\nexport interface AgentProfile {\n // Metadata\n name: string;\n displayName?: string; // Human-friendly name (e.g., \"Bob\", \"Eric\")\n role: string;\n description: string;\n\n // v4.10.0+ Team-based configuration\n team?: string; // Team name (e.g., \"core\", \"engineering\", \"business\", \"design\")\n // Agents inherit provider config from their team\n\n // Behavior\n systemPrompt: string;\n abilities: string[]; // List of ability file names (agent-specific, added to team's sharedAbilities)\n\n // Enhanced v4.1+ features\n stages?: Stage[]; // Workflow stages\n personality?: Personality; // Character traits\n thinking_patterns?: string[]; // Guiding principles\n abilitySelection?: AbilitySelection; // Smart ability loading\n\n /**\n * Provider configuration (v4.10.0+)\n *\n * Recommended approach:\n * 1. Assign agent to a team via `team: \"engineering\"`\n * 2. Configure provider at team level in .automatosx/teams/<team>.yaml\n *\n * Alternative (per-agent override):\n * Configure directly in agent YAML for specific needs:\n * - provider: Override team's provider choice\n * - model: Specific model for this agent\n * - temperature: Control randomness (0 = deterministic, 2 = creative)\n * - maxTokens: Limit output length (cost control or specific use case)\n *\n * Note: Only OpenAI Codex CLI currently supports temperature/maxTokens parameters.\n * Gemini and Claude use their CLI's default settings.\n */\n provider?: string; // Provider override (e.g., \"openai\", \"gemini-cli\", \"claude-code\")\n fallbackProvider?: string; // Fallback if primary provider unavailable\n model?: string; // Model override (e.g., \"gpt-4o\", \"gemini-2.0-flash-exp\")\n temperature?: number; // Randomness control: 0-2 (OpenAI only)\n maxTokens?: number; // Max output tokens (OpenAI only)\n\n // Optional\n tags?: string[];\n version?: string;\n metadata?: Record<string, any>;\n\n // v4.7.0+ Orchestration\n orchestration?: OrchestrationConfig; // Agent collaboration capabilities\n}\n\n/**\n * Execution Context - Everything needed to execute an agent\n */\nexport interface ExecutionContext {\n // Agent info\n agent: AgentProfile;\n task: string;\n\n // Memory (injected from MemoryManager)\n memory: MemoryEntry[];\n\n // Paths (from PathResolver)\n projectDir: string;\n workingDir: string;\n agentWorkspace: string;\n\n // Provider (selected from Router)\n provider: Provider;\n\n // Abilities (from AbilitiesManager)\n abilities: string;\n\n // Timestamp\n createdAt: Date;\n\n // v4.7.0+ Orchestration\n orchestration?: OrchestrationMetadata; // Runtime orchestration info\n session?: Session; // Current session (if part of multi-agent workflow)\n}\n\n/**\n * Context creation options\n */\nexport interface ContextOptions {\n provider?: string; // Override provider\n model?: string; // Override model\n skipMemory?: boolean; // Skip memory injection\n memoryLimit?: number; // Limit memory entries\n\n // v4.7.0+ Orchestration options\n sessionId?: string; // Session ID for multi-agent workflows\n delegationChain?: string[]; // Current delegation chain (for cycle detection)\n sharedData?: Record<string, any>; // Shared data from delegating agent\n}\n\n/**\n * Agent validation error\n */\nexport class AgentValidationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'AgentValidationError';\n }\n}\n\n/**\n * Agent not found error\n */\nexport class AgentNotFoundError extends Error {\n constructor(agentName: string) {\n super(`Agent not found: ${agentName}`);\n this.name = 'AgentNotFoundError';\n }\n}\n","/**\n * Abilities Manager - Load and inject agent abilities from markdown files\n */\n\nimport { readFile, readdir } from 'fs/promises';\nimport { join, extname, basename, dirname } from 'path';\nimport { fileURLToPath } from 'url';\nimport { logger } from '../utils/logger.js';\nimport { TTLCache } from '../core/cache.js';\n\n// Get the directory of this file for locating built-in abilities\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\n// Get package root - handle both dev (src/) and prod (dist/) scenarios\nfunction getPackageRoot(): string {\n const currentDir = __dirname;\n if (currentDir.includes('/dist')) {\n return join(currentDir, '..');\n } else {\n return join(currentDir, '../..');\n }\n}\n\n/**\n * Abilities Manager - Load and manage agent abilities\n */\nexport class AbilitiesManager {\n private abilitiesDir: string;\n private fallbackAbilitiesDir: string;\n private cache: TTLCache<string>;\n\n constructor(abilitiesDir: string, fallbackAbilitiesDir?: string) {\n this.abilitiesDir = abilitiesDir;\n // Default fallback to built-in examples/abilities\n this.fallbackAbilitiesDir = fallbackAbilitiesDir || join(getPackageRoot(), 'examples/abilities');\n // Use TTLCache with 10 minute TTL for abilities (they change less frequently)\n this.cache = new TTLCache<string>({\n maxEntries: 50,\n ttl: 600000, // 10 minutes\n maxSize: 5 * 1024 * 1024, // 5MB total cache size\n cleanupInterval: 120000, // Cleanup every 2 minutes\n debug: false\n });\n }\n\n /**\n * Load a single ability by name\n */\n async loadAbility(name: string): Promise<string> {\n // Security: Validate ability name to prevent path traversal\n if (!/^[a-zA-Z0-9_-]+$/.test(name)) {\n logger.warn('Invalid ability name rejected', { name });\n throw new Error(`Invalid ability name: ${name}. Only alphanumeric characters, dashes, and underscores are allowed.`);\n }\n\n // Check cache first\n const cached = this.cache.get(name);\n if (cached) {\n logger.debug('Ability loaded from cache', { name });\n return cached;\n }\n\n // Try primary directory first, then fallback\n const paths = [\n join(this.abilitiesDir, `${name}.md`),\n join(this.fallbackAbilitiesDir, `${name}.md`)\n ];\n\n for (const abilityPath of paths) {\n try {\n const content = await readFile(abilityPath, 'utf-8');\n\n // Security: Limit file size to prevent DoS (max 500KB for ability)\n if (content.length > 500 * 1024) {\n throw new Error('Ability file too large (max 500KB)');\n }\n\n // Cache it\n this.cache.set(name, content);\n\n logger.info('Ability loaded', { name, path: abilityPath });\n return content;\n\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n // Try next path\n continue;\n }\n throw error;\n }\n }\n\n // If not found in any location, log warning and return empty string\n logger.warn('Ability not found in any location', { name });\n return ''; // Return empty string for missing abilities\n }\n\n /**\n * Load multiple abilities\n */\n async loadAbilities(names: string[]): Promise<Map<string, string>> {\n const abilities = new Map<string, string>();\n\n for (const name of names) {\n const content = await this.loadAbility(name);\n if (content) {\n abilities.set(name, content);\n }\n }\n\n return abilities;\n }\n\n /**\n * Get concatenated abilities text\n */\n async getAbilitiesText(names: string[]): Promise<string> {\n const abilities = await this.loadAbilities(names);\n\n if (abilities.size === 0) {\n return '';\n }\n\n // Concatenate all abilities with section headers\n const sections: string[] = [];\n\n for (const [name, content] of abilities.entries()) {\n sections.push(`## Ability: ${name}\\n\\n${content}`);\n }\n\n return sections.join('\\n\\n---\\n\\n');\n }\n\n /**\n * List all available abilities\n */\n async listAbilities(): Promise<string[]> {\n try {\n const files = await readdir(this.abilitiesDir);\n\n const abilities = files\n .filter(file => extname(file) === '.md')\n .map(file => basename(file, extname(file)));\n\n return abilities.sort();\n\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return [];\n }\n throw error;\n }\n }\n\n /**\n * Clear cache\n */\n clearCache(): void {\n this.cache.clear();\n }\n}\n","/**\n * Agent Executor - Orchestrates agent execution workflow\n *\n * Responsibilities:\n * - Execute agents with progress tracking\n * - Manage execution lifecycle\n * - Provide detailed error reporting\n * - Handle agent-to-agent delegation (v4.7.0+)\n */\n\nimport type { ExecutionContext } from '../types/agent.js';\nimport type { ExecutionResponse } from '../types/provider.js';\nimport type { DelegationRequest, DelegationResult } from '../types/orchestration.js';\nimport type { RetryConfig } from '../types/config.js';\nimport { DelegationError } from '../types/orchestration.js';\nimport type { SessionManager } from '../core/session-manager.js';\nimport type { WorkspaceManager } from '../core/workspace-manager.js';\nimport type { ContextManager } from './context-manager.js';\nimport type { ProfileLoader } from './profile-loader.js';\nimport { DelegationParser } from './delegation-parser.js';\nimport { formatError } from '../utils/error-formatter.js';\nimport { randomUUID } from 'crypto';\nimport { logger } from '../utils/logger.js';\nimport chalk from 'chalk';\nimport ora from 'ora';\n\nexport interface ExecutionOptions {\n verbose?: boolean;\n showProgress?: boolean;\n retry?: RetryConfig;\n timeout?: number;\n signal?: AbortSignal;\n}\n\nexport interface ExecutionResult {\n response: ExecutionResponse;\n duration: number;\n context: ExecutionContext;\n}\n\n/**\n * Agent Executor Configuration\n */\nexport interface AgentExecutorConfig {\n sessionManager?: SessionManager;\n workspaceManager?: WorkspaceManager;\n contextManager?: ContextManager;\n profileLoader?: ProfileLoader;\n /** Default retry configuration (v5.0+) */\n defaultRetryConfig?: RetryConfig;\n}\n\n/**\n * Agent Executor\n *\n * Executes agents with progress tracking and comprehensive error handling.\n * Supports agent-to-agent delegation for multi-agent workflows (v4.7.0+).\n */\nexport class AgentExecutor {\n private sessionManager?: SessionManager;\n private workspaceManager?: WorkspaceManager;\n private contextManager?: ContextManager;\n private profileLoader?: ProfileLoader;\n private delegationParser: DelegationParser;\n\n /**\n * Default retry configuration (v5.0: from config instead of hardcoded)\n */\n private readonly defaultRetryConfig: RetryConfig;\n\n /**\n * Create AgentExecutor with optional delegation support\n *\n * @param config - Optional configuration for delegation features\n */\n constructor(config?: AgentExecutorConfig) {\n this.sessionManager = config?.sessionManager;\n this.workspaceManager = config?.workspaceManager;\n this.contextManager = config?.contextManager;\n this.profileLoader = config?.profileLoader;\n this.delegationParser = new DelegationParser(config?.profileLoader);\n\n // v5.0: Use config value instead of hardcoded constant\n this.defaultRetryConfig = config?.defaultRetryConfig ?? {\n maxAttempts: 3,\n initialDelay: 1000,\n maxDelay: 10000,\n backoffFactor: 2,\n retryableErrors: [\n 'ECONNREFUSED',\n 'ETIMEDOUT',\n 'ENOTFOUND',\n 'rate_limit',\n 'overloaded',\n 'timeout'\n ]\n };\n }\n\n /**\n * Execute an agent with the given context\n */\n async execute(\n context: ExecutionContext,\n options: ExecutionOptions = {}\n ): Promise<ExecutionResult> {\n // If both retry and timeout are enabled\n if (options.retry && options.timeout) {\n return this.executeWithTimeout(context, {\n ...options,\n // Wrap retry logic inside timeout\n retry: options.retry\n });\n }\n\n // If only retry is enabled\n if (options.retry) {\n return this.executeWithRetry(context, options);\n }\n\n // If only timeout is enabled\n if (options.timeout) {\n return this.executeWithTimeout(context, options);\n }\n\n // Otherwise, execute normally\n return this.executeInternal(context, options);\n }\n\n /**\n * Execute with retry logic\n */\n private async executeWithRetry(\n context: ExecutionContext,\n options: ExecutionOptions\n ): Promise<ExecutionResult> {\n const retryConfig = { ...this.defaultRetryConfig, ...options.retry };\n const { maxAttempts, initialDelay, maxDelay, backoffFactor, retryableErrors } = retryConfig;\n const { verbose = false } = options;\n\n let lastError: Error | null = null;\n let attempt = 0;\n\n while (attempt < maxAttempts) {\n attempt++;\n\n try {\n if (verbose && attempt > 1) {\n console.log(chalk.yellow(`\\nRetry attempt ${attempt}/${maxAttempts}...`));\n }\n\n return await this.executeInternal(context, options);\n } catch (error: any) {\n lastError = error;\n\n // Check if error is retryable\n const isRetryable = this.isRetryableError(error, retryableErrors);\n\n if (!isRetryable || attempt >= maxAttempts) {\n throw error;\n }\n\n // Calculate backoff delay\n const delay = Math.min(\n initialDelay * Math.pow(backoffFactor, attempt - 1),\n maxDelay\n );\n\n if (verbose) {\n console.log(chalk.yellow(`Retryable error occurred: ${error.message}`));\n console.log(chalk.gray(`Waiting ${delay}ms before retry...`));\n }\n\n await this.sleep(delay);\n }\n }\n\n // Should not reach here, but throw last error if we do\n throw lastError || new Error('Execution failed after retries');\n }\n\n /**\n * Execute with timeout\n */\n private async executeWithTimeout(\n context: ExecutionContext,\n options: ExecutionOptions\n ): Promise<ExecutionResult> {\n const timeout = options.timeout!;\n const { verbose = false } = options;\n\n // Create an AbortController for cancellation\n const controller = new AbortController();\n const executionOptions = {\n ...options,\n signal: controller.signal,\n timeout: undefined // Remove timeout from nested execution\n };\n\n const executionPromise = options.retry\n ? this.executeWithRetry(context, executionOptions)\n : this.executeInternal(context, executionOptions);\n\n const timeoutPromise = new Promise<ExecutionResult>((_, reject) => {\n setTimeout(() => {\n controller.abort(); // Cancel the execution\n reject(new Error(`Execution timed out after ${timeout}ms`));\n }, timeout);\n });\n\n try {\n return await Promise.race([executionPromise, timeoutPromise]);\n } catch (error) {\n // Ensure abortion on error\n controller.abort();\n throw error;\n }\n }\n\n /**\n * Internal execution (actual implementation)\n */\n private async executeInternal(\n context: ExecutionContext,\n options: ExecutionOptions = {}\n ): Promise<ExecutionResult> {\n const { verbose = false, showProgress = true } = options;\n\n // Display execution info\n if (verbose) {\n this.displayExecutionInfo(context);\n }\n\n // Create progress spinner\n const spinner = showProgress\n ? ora({\n text: 'Executing agent...',\n spinner: 'dots'\n }).start()\n : null;\n\n try {\n // Build prompt\n const prompt = this.buildPrompt(context);\n\n // Update spinner\n if (spinner) {\n spinner.text = `Executing with ${context.provider.name}...`;\n }\n\n // Execute via provider\n const startTime = Date.now();\n const response = await context.provider.execute({\n prompt,\n systemPrompt: context.agent.systemPrompt,\n model: context.agent.model,\n temperature: context.agent.temperature,\n maxTokens: context.agent.maxTokens,\n signal: options.signal // v5.0.7: Pass abort signal for cancellation\n });\n const duration = Date.now() - startTime;\n\n // Check for delegation requests in response (v4.7.2+)\n if (context.orchestration) {\n const delegations = await this.delegationParser.parse(response.content, context.agent.name);\n\n if (delegations.length > 0) {\n if (verbose) {\n console.log(chalk.cyan(`\\n🔗 Found ${delegations.length} delegation request(s)`));\n }\n\n // Update spinner\n if (spinner) {\n spinner.text = 'Processing delegations...';\n }\n\n // Execute all delegations\n const delegationResults = await this.executeDelegations(delegations, context, options);\n\n // Append delegation results to response\n let delegationSummary = '\\n\\n---\\n\\n## Delegation Results\\n\\n';\n delegationResults.forEach((result, index) => {\n delegationSummary += `### Delegation ${index + 1}: ${result.toAgent}\\n\\n`;\n delegationSummary += result.response.content + '\\n\\n';\n });\n\n // Modify response to include delegation results\n response.content += delegationSummary;\n\n if (verbose) {\n console.log(chalk.green(`✅ All delegations completed`));\n }\n }\n }\n\n // Stop spinner\n if (spinner) {\n spinner.succeed('Execution complete');\n }\n\n return {\n response,\n duration,\n context\n };\n\n } catch (error) {\n // Stop spinner with failure\n if (spinner) {\n spinner.fail('Execution failed');\n }\n\n throw this.enhanceError(error as Error, context);\n }\n }\n\n\n /**\n * Execute delegation requests parsed from agent response\n *\n * This is called automatically when an agent's response contains\n * delegation instructions (e.g., \"DELEGATE TO frontend: Create UI\")\n */\n private async executeDelegations(\n delegations: Array<{ toAgent: string; task: string }>,\n context: ExecutionContext,\n options: ExecutionOptions\n ): Promise<DelegationResult[]> {\n const results: DelegationResult[] = [];\n const { verbose = false } = options;\n\n for (const { toAgent, task } of delegations) {\n if (verbose) {\n console.log(chalk.cyan(`\\n📤 Delegating to ${toAgent}...`));\n console.log(chalk.gray(` Task: ${task.substring(0, 100)}${task.length > 100 ? '...' : ''}`));\n }\n\n try {\n const request: DelegationRequest = {\n fromAgent: context.agent.name,\n toAgent,\n task,\n context: {\n sessionId: context.session?.id,\n delegationChain: context.orchestration?.delegationChain || []\n }\n };\n\n const result = await this.delegateToAgent(request);\n results.push(result);\n\n if (verbose) {\n console.log(chalk.green(`✅ Delegation to ${toAgent} completed`));\n }\n } catch (error) {\n const err = error as Error;\n logger.error('Delegation failed', {\n fromAgent: context.agent.name,\n toAgent,\n error: err.message\n });\n\n if (verbose) {\n console.log(chalk.red(`❌ Delegation to ${toAgent} failed: ${err.message}`));\n }\n\n // Store error as failed delegation result\n results.push({\n delegationId: randomUUID(),\n fromAgent: context.agent.name,\n toAgent,\n startTime: new Date(),\n endTime: new Date(),\n duration: 0,\n status: 'failure',\n response: {\n content: `Delegation failed: ${err.message}`,\n model: 'error',\n tokensUsed: { prompt: 0, completion: 0, total: 0 },\n latencyMs: 0,\n finishReason: 'error'\n },\n outputs: {\n files: [],\n memoryIds: [],\n workspacePath: ''\n }\n } as DelegationResult);\n }\n }\n\n return results;\n }\n\n /**\n * Display execution information\n */\n private displayExecutionInfo(context: ExecutionContext): void {\n console.log(chalk.gray('Execution Details:'));\n console.log(chalk.gray(` Agent: ${context.agent.name}`));\n console.log(chalk.gray(` Provider: ${context.provider.name}`));\n console.log(chalk.gray(` Model: ${context.agent.model || 'default'}`));\n console.log(chalk.gray(` Abilities: ${context.agent.abilities.length}`));\n console.log(chalk.gray(` Memory entries: ${context.memory.length}`));\n console.log();\n }\n\n /**\n * Build prompt from execution context\n */\n private buildPrompt(context: ExecutionContext): string {\n let prompt = '';\n\n // Add abilities\n if (context.abilities) {\n prompt += `# Your Abilities\\n\\n${context.abilities}\\n\\n`;\n }\n\n // Add stages workflow (v4.1+ enhanced profiles)\n if (context.agent.stages && context.agent.stages.length > 0) {\n prompt += `# Your Workflow Stages\\n\\n`;\n prompt += `You MUST follow these stages explicitly for every task:\\n\\n`;\n\n context.agent.stages.forEach((stage, i) => {\n prompt += `## Stage ${i + 1}: ${stage.name}\\n\\n`;\n prompt += `${stage.description}\\n\\n`;\n\n if (stage.key_questions && stage.key_questions.length > 0) {\n prompt += `**Key Questions:**\\n`;\n stage.key_questions.forEach(q => {\n prompt += `- ${q}\\n`;\n });\n prompt += `\\n`;\n }\n\n if (stage.outputs && stage.outputs.length > 0) {\n prompt += `**Expected Outputs:**\\n`;\n stage.outputs.forEach(o => {\n prompt += `- ${o}\\n`;\n });\n prompt += `\\n`;\n }\n });\n\n prompt += `**Important:** Announce each stage as you work through it (e.g., \"## Stage 1: requirement_analysis\").\\n\\n`;\n }\n\n // Add memory (relevant context)\n if (context.memory.length > 0) {\n prompt += `# Relevant Context from Memory\\n\\n`;\n context.memory.forEach((entry, i) => {\n const score = entry.score !== undefined ? ` (relevance: ${(entry.score * 100).toFixed(1)}%)` : '';\n prompt += `## Memory ${i + 1}${score}\\n${entry.content}\\n\\n`;\n });\n }\n\n // Add orchestration capabilities (v4.7.0+, Enhanced v4.11.0+)\n if (context.orchestration) {\n prompt += `# Multi-Agent Orchestration Capabilities\\n\\n`;\n prompt += `**IMPORTANT - Task Evaluation Strategy:**\\n`;\n prompt += `1. **First, evaluate if YOU can complete the task** using your abilities and expertise\\n`;\n prompt += `2. **If you CAN do it**, complete the task yourself without delegation\\n`;\n prompt += `3. **If you CANNOT do it** (lacks expertise, tools, or authority), then delegate to a specialized agent\\n`;\n prompt += `4. **Max delegation depth: ${context.orchestration.maxDelegationDepth} levels** - use delegation wisely\\n\\n`;\n prompt += `Only delegate when the task genuinely requires specialized expertise you don't have.\\n\\n`;\n\n // Limit agent list to avoid overly long prompts\n const MAX_AGENTS_TO_SHOW = 10;\n const availableAgents = context.orchestration.availableAgents;\n\n if (availableAgents.length > 0) {\n prompt += `**Available agents for delegation:**\\n`;\n\n const agentsToShow = availableAgents.slice(0, MAX_AGENTS_TO_SHOW);\n agentsToShow.forEach(agent => {\n prompt += `- ${agent}\\n`;\n });\n\n if (availableAgents.length > MAX_AGENTS_TO_SHOW) {\n const remaining = availableAgents.length - MAX_AGENTS_TO_SHOW;\n prompt += `... and ${remaining} more agents\\n`;\n prompt += `\\nNote: You can delegate to ANY agent by name, not just those listed above.\\n`;\n }\n prompt += `\\n`;\n }\n\n if (context.session) {\n prompt += `**Current session:** ${context.session.id}\\n`;\n prompt += `**Session task:** ${context.session.task}\\n`;\n prompt += `**Collaborating agents:** ${context.session.agents.join(', ')}\\n\\n`;\n }\n\n prompt += `**Shared workspace:** ${context.orchestration.sharedWorkspace}\\n\\n`;\n\n if (context.orchestration.delegationChain.length > 0) {\n prompt += `**Delegation chain:** ${context.orchestration.delegationChain.join(' → ')} → YOU\\n`;\n prompt += `**Current depth:** ${context.orchestration.delegationChain.length}/${context.orchestration.maxDelegationDepth}\\n\\n`;\n }\n\n prompt += `**How to delegate:**\\n`;\n prompt += `You can delegate using any of these natural syntaxes:\\n`;\n prompt += `1. \"DELEGATE TO frontend: Create login UI\"\\n`;\n prompt += `2. \"@frontend Create login UI\"\\n`;\n prompt += `3. \"Please ask backend to implement auth API\"\\n`;\n prompt += `4. \"I need frontend to handle the UI\"\\n`;\n prompt += `5. \"請 frontend 建立登入 UI\" (Chinese support)\\n\\n`;\n prompt += `Example: \"@frontend Create a responsive login UI with email and password fields\"\\n\\n`;\n }\n\n // Add task\n prompt += `# Task\\n\\n${context.task}`;\n\n return prompt;\n }\n\n /**\n * Enhance error with context-specific details\n */\n private enhanceError(error: Error, context: ExecutionContext): Error {\n const enhanced = new Error(error.message);\n enhanced.stack = error.stack;\n\n // Add context to error\n (enhanced as any).context = {\n agent: context.agent.name,\n provider: context.provider.name,\n model: context.agent.model,\n task: context.task.substring(0, 100) + (context.task.length > 100 ? '...' : '')\n };\n\n return enhanced;\n }\n\n /**\n * Display execution result\n */\n displayResult(result: ExecutionResult, options: ExecutionOptions = {}): void {\n const { verbose = false } = options;\n\n // Display response\n console.log(chalk.cyan('Response:'));\n console.log(result.response.content);\n console.log();\n\n // Display metrics if verbose\n if (verbose) {\n console.log(chalk.gray('Execution Metrics:'));\n console.log(chalk.gray(` Duration: ${result.duration}ms`));\n console.log(chalk.gray(` Tokens used: ${result.response.tokensUsed.total}`));\n console.log(chalk.gray(` Prompt: ${result.response.tokensUsed.prompt}`));\n console.log(chalk.gray(` Completion: ${result.response.tokensUsed.completion}`));\n console.log();\n }\n }\n\n /**\n * Display execution error with helpful suggestions\n */\n displayError(error: Error, agentName: string, options: ExecutionOptions = {}): void {\n const { verbose = false } = options;\n\n // Use structured error formatter\n console.error(formatError(error, {\n verbose,\n showCode: true,\n showSuggestions: true,\n colors: true\n }));\n }\n\n /**\n * Check if error is retryable\n */\n private isRetryableError(error: any, retryableErrors?: string[]): boolean {\n const patterns = retryableErrors || this.defaultRetryConfig.retryableErrors!;\n\n const errorString = (error.message || error.code || '').toLowerCase();\n\n return patterns.some(pattern =>\n errorString.includes(pattern.toLowerCase())\n );\n }\n\n /**\n * Sleep for specified milliseconds\n */\n private sleep(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n }\n\n /**\n * Delegate a task to another agent\n *\n * This method enables agent-to-agent delegation with proper permission checks,\n * cycle detection, and session management.\n *\n * @param request - Delegation request\n * @returns Delegation result with structured outputs\n * @throws {DelegationError} If delegation fails\n *\n * @example\n * ```typescript\n * const result = await executor.delegateToAgent({\n * fromAgent: 'backend',\n * toAgent: 'frontend',\n * task: 'Create login UI component',\n * context: {\n * sessionId: 'auth-feature-123',\n * requirements: ['Email/password fields'],\n * delegationChain: ['backend']\n * }\n * });\n *\n * console.log('Files created:', result.outputs.files);\n * ```\n */\n async delegateToAgent(request: DelegationRequest): Promise<DelegationResult> {\n // Verify minimum required components for delegation\n // Note: SessionManager and WorkspaceManager are optional (for text-only delegation)\n if (!this.contextManager || !this.profileLoader) {\n throw new DelegationError(\n 'Delegation not configured - missing required managers (contextManager, profileLoader)',\n request.fromAgent,\n request.toAgent,\n 'execution_failed'\n );\n }\n\n const delegationId = randomUUID();\n const startTime = new Date();\n\n logger.info('Delegation started', {\n delegationId,\n fromAgent: request.fromAgent,\n toAgent: request.toAgent,\n task: request.task.substring(0, 100)\n });\n\n try {\n // 1. Load agent profiles\n const fromAgentProfile = await this.profileLoader.loadProfile(request.fromAgent);\n const toAgentProfile = await this.profileLoader.loadProfile(request.toAgent);\n\n // 2. v4.7.8+: All agents can delegate by default\n // Permission check removed - autonomous agent collaboration enabled\n // Safety ensured by:\n // - Cycle detection (below)\n // - Max depth limit (below)\n // - Timeout enforcement\n\n // 3. Cycle detection: check delegation chain\n const delegationChain = request.context?.delegationChain || [];\n if (delegationChain.includes(request.toAgent)) {\n throw new DelegationError(\n `Delegation cycle detected: ${[...delegationChain, request.toAgent].join(' -> ')}`,\n request.fromAgent,\n request.toAgent,\n 'cycle'\n );\n }\n\n // 4. Max depth check\n // delegationChain contains agents that have already delegated\n // If chain = ['A', 'B'], this means A→B has happened, and B is now delegating (3rd delegation)\n // maxDepth = 2 allows up to 2 delegations: A→B (1st), B→C (2nd)\n // So we reject when delegationChain.length >= maxDepth (3rd delegation attempt)\n // v4.11.0+: Default to 2 (agents evaluate capability first, delegate only when needed)\n const maxDepth = fromAgentProfile.orchestration?.maxDelegationDepth ?? 2;\n if (delegationChain.length >= maxDepth) {\n throw new DelegationError(\n `Max delegation depth (${maxDepth}) exceeded. Chain: ${delegationChain.join(' -> ')} (length ${delegationChain.length})`,\n request.fromAgent,\n request.toAgent,\n 'max_depth'\n );\n }\n\n // 5. Session management (optional - only if SessionManager is available)\n let sessionId = request.context?.sessionId;\n let session;\n\n if (this.sessionManager && this.workspaceManager) {\n // Session/Workspace managers available - use full collaboration features\n if (sessionId) {\n // Join existing session\n session = await this.sessionManager.getSession(sessionId);\n if (!session) {\n throw new DelegationError(\n `Session not found: ${sessionId}`,\n request.fromAgent,\n request.toAgent,\n 'execution_failed'\n );\n }\n\n // Validate session is active\n if (session.status !== 'active') {\n throw new DelegationError(\n `Cannot delegate to ${session.status} session: ${sessionId}`,\n request.fromAgent,\n request.toAgent,\n 'execution_failed'\n );\n }\n\n // Add toAgent to session\n await this.sessionManager.addAgent(sessionId, request.toAgent);\n } else {\n // Create new session\n session = await this.sessionManager.createSession(request.task, request.fromAgent);\n sessionId = session.id;\n\n // Add toAgent to session\n await this.sessionManager.addAgent(sessionId, request.toAgent);\n\n // Create session workspace\n await this.workspaceManager.createSessionWorkspace(sessionId);\n }\n } else {\n // Simple text-only delegation mode (no persistent session/workspace)\n logger.debug('Text-only delegation mode (no SessionManager/WorkspaceManager)', {\n fromAgent: request.fromAgent,\n toAgent: request.toAgent\n });\n sessionId = undefined;\n }\n\n // 6. Create execution context for delegated agent\n const context = await this.contextManager.createContext(\n request.toAgent,\n request.task,\n {\n sessionId,\n delegationChain: [...delegationChain, request.fromAgent],\n sharedData: request.context?.sharedData\n }\n );\n\n // 7. Execute delegated agent\n const executionResult = await this.execute(context, {\n timeout: request.options?.timeout,\n verbose: false,\n showProgress: true\n });\n\n // 8. Collect outputs (only if WorkspaceManager is available)\n let files: string[] = [];\n if (this.workspaceManager && sessionId) {\n files = await this.workspaceManager.listSessionFiles(\n sessionId,\n request.toAgent\n );\n }\n\n // 9. Memory IDs collection\n // TODO: Implement memory saving in future enhancement\n const memoryIds: number[] = [];\n\n const endTime = new Date();\n const duration = endTime.getTime() - startTime.getTime();\n\n logger.info('Delegation completed', {\n delegationId,\n fromAgent: request.fromAgent,\n toAgent: request.toAgent,\n duration: `${(duration / 1000).toFixed(1)}s`,\n filesCreated: files.length\n });\n\n // 10. Return structured result\n return {\n delegationId,\n fromAgent: request.fromAgent,\n toAgent: request.toAgent,\n status: 'success',\n response: executionResult.response,\n duration,\n outputs: {\n files,\n memoryIds,\n workspacePath: `sessions/${sessionId}/outputs/${request.toAgent}`\n },\n startTime,\n endTime\n };\n\n } catch (error) {\n const endTime = new Date();\n const duration = endTime.getTime() - startTime.getTime();\n\n // If it's already a DelegationError, re-throw it\n if (error instanceof DelegationError) {\n logger.error('Delegation failed', {\n delegationId,\n fromAgent: request.fromAgent,\n toAgent: request.toAgent,\n reason: error.reason,\n error: error.message\n });\n throw error;\n }\n\n // Otherwise, wrap it in a DelegationError\n const delegationError = new DelegationError(\n `Delegation execution failed: ${(error as Error).message}`,\n request.fromAgent,\n request.toAgent,\n 'execution_failed'\n );\n\n logger.error('Delegation failed', {\n delegationId,\n fromAgent: request.fromAgent,\n toAgent: request.toAgent,\n error: (error as Error).message\n });\n\n throw delegationError;\n }\n }\n}\n","/**\n * Orchestration Types - Agent-to-agent collaboration and delegation\n *\n * @module types/orchestration\n * @since v4.7.0\n */\n\nimport type { ExecutionResponse } from './provider.js';\n\n/**\n * Delegation Request - Structured request for agent delegation\n *\n * @example\n * ```typescript\n * const request: DelegationRequest = {\n * fromAgent: 'backend',\n * toAgent: 'frontend',\n * task: 'Create login UI component',\n * context: {\n * sessionId: 'auth-feature-123',\n * requirements: ['Email/password fields', 'Form validation'],\n * expectedOutputs: ['LoginForm.tsx', 'tests']\n * }\n * };\n * ```\n */\nexport interface DelegationRequest {\n /** Agent initiating the delegation */\n fromAgent: string;\n\n /** Agent receiving the delegated task */\n toAgent: string;\n\n /** Task description for the delegated agent */\n task: string;\n\n /** Additional context for the delegation */\n context?: {\n /** Shared data to pass to delegated agent */\n sharedData?: Record<string, any>;\n\n /** Structured requirements for the task */\n requirements?: string[];\n\n /** Expected outputs from the delegated agent */\n expectedOutputs?: string[];\n\n /** Session ID to track related work (CRITICAL for multi-agent workflows) */\n sessionId?: string;\n\n /** Delegation chain for cycle detection */\n delegationChain?: string[];\n };\n\n /** Execution options */\n options?: {\n /** Maximum execution time in milliseconds */\n timeout?: number;\n\n /** Task priority (affects execution order if queued) */\n priority?: 'low' | 'medium' | 'high';\n };\n}\n\n/**\n * Delegation Result - Structured result from agent delegation\n *\n * Contains both the execution response and structured outputs for easy integration.\n *\n * @example\n * ```typescript\n * const result = await executor.delegateToAgent(request);\n *\n * // Access structured outputs\n * console.log('Files created:', result.outputs.files);\n * console.log('Memory IDs:', result.outputs.memoryIds);\n * console.log('Workspace path:', result.outputs.workspacePath);\n * ```\n */\nexport interface DelegationResult {\n /** Unique delegation identifier (for tracking and auditing) */\n delegationId: string;\n\n /** Agent that initiated the delegation */\n fromAgent: string;\n\n /** Agent that executed the task */\n toAgent: string;\n\n /** Delegation status */\n status: 'success' | 'failure' | 'timeout';\n\n /** Response from the delegated agent execution */\n response: ExecutionResponse;\n\n /** Execution duration in milliseconds */\n duration: number;\n\n /** Structured outputs from the delegation */\n outputs: {\n /** Files created in shared workspace */\n files?: string[];\n\n /** Memory entry IDs created during execution */\n memoryIds?: number[];\n\n /** Path to workspace containing outputs */\n workspacePath?: string;\n };\n\n /** Delegation start timestamp */\n startTime: Date;\n\n /** Delegation completion timestamp */\n endTime: Date;\n}\n\n/**\n * Session - Tracks multi-agent collaborative workflows\n *\n * A session groups related work across multiple agents, providing shared context\n * and workspace organization.\n *\n * @example\n * ```typescript\n * // Create session for auth feature implementation\n * const session = await sessionManager.createSession(\n * 'Implement authentication feature',\n * 'backend'\n * );\n *\n * // Agents added as they join the work\n * await sessionManager.addAgent(session.id, 'frontend');\n * await sessionManager.addAgent(session.id, 'security');\n * ```\n */\nexport interface Session {\n /** Unique session identifier (UUID) */\n id: string;\n\n /** Agent that initiated the session */\n initiator: string;\n\n /** Overall task/goal for the session */\n task: string;\n\n /** Agents involved in this session (ordered by join time) */\n agents: string[];\n\n /** Current session status */\n status: 'active' | 'completed' | 'failed';\n\n /** Session creation timestamp */\n createdAt: Date;\n\n /** Last update timestamp */\n updatedAt: Date;\n\n /** Additional session metadata */\n metadata?: Record<string, any>;\n}\n\n/**\n * Orchestration Configuration - Agent collaboration capabilities\n *\n * Defines workspace access and delegation depth limits for agents.\n * All agents can delegate by default (v4.9.0+). Safety is ensured through\n * cycle detection, depth limits, and timeouts.\n *\n * @example\n * ```yaml\n * # .automatosx/agents/backend.yaml\n * orchestration:\n * maxDelegationDepth: 3\n * canReadWorkspaces:\n * - frontend\n * - data\n * canWriteToShared: true\n * ```\n */\nexport interface OrchestrationConfig {\n /**\n * Maximum delegation chain depth (default: 3)\n *\n * This represents the number of intermediate delegations allowed, NOT the total number of agents.\n *\n * Example:\n * - maxDelegationDepth = 3 allows: A → B → C → D (3 delegations, 4 agents)\n * - maxDelegationDepth = 3 rejects: A → B → C → D → E (4 delegations, 5 agents)\n *\n * The depth is measured by the length of the delegation chain (excluding the current agent).\n */\n maxDelegationDepth?: number;\n\n /** Whitelist of agents' workspaces this agent can read */\n canReadWorkspaces?: string[];\n\n /** Whether this agent can write to shared workspace */\n canWriteToShared?: boolean;\n}\n\n/**\n * Orchestration Metadata - Runtime orchestration information in execution context\n *\n * Added to ExecutionContext when orchestration system is enabled.\n * v4.9.0+: All agents can delegate by default. This metadata indicates whether\n * the orchestration infrastructure (SessionManager, WorkspaceManager) is available.\n */\nexport interface OrchestrationMetadata {\n /** Whether orchestration system is enabled (SessionManager/WorkspaceManager available) */\n isDelegationEnabled: boolean;\n\n /** List of available agents for delegation */\n availableAgents: string[];\n\n /** Path to shared workspace */\n sharedWorkspace: string;\n\n /** Current delegation chain (for cycle detection) */\n delegationChain: string[];\n\n /** Maximum delegation depth (default: 3) */\n maxDelegationDepth: number;\n}\n\n/**\n * Delegation Error - Specialized error for delegation failures\n */\nexport class DelegationError extends Error {\n constructor(\n message: string,\n public readonly fromAgent: string,\n public readonly toAgent: string,\n public readonly reason: 'unauthorized' | 'not_found' | 'max_depth' | 'cycle' | 'timeout' | 'execution_failed'\n ) {\n super(message);\n this.name = 'DelegationError';\n }\n}\n\n/**\n * Session Error - Specialized error for session operations\n */\nexport class SessionError extends Error {\n constructor(\n message: string,\n public readonly sessionId?: string,\n public readonly reason?: 'not_found' | 'already_completed' | 'creation_failed' | 'invalid_format' | 'metadata_too_large'\n ) {\n super(message);\n this.name = 'SessionError';\n }\n}\n\n/**\n * Workspace Error - Specialized error for workspace operations\n */\nexport class WorkspaceError extends Error {\n constructor(\n message: string,\n public readonly workspacePath?: string,\n public readonly reason?: 'permission_denied' | 'not_found' | 'conflict' | 'quota_exceeded' | 'creation_failed' | 'invalid_session_id'\n ) {\n super(message);\n this.name = 'WorkspaceError';\n }\n}\n","/**\n * Delegation Parser - Natural language delegation parsing\n *\n * Parses natural language delegation requests from agent responses.\n * Supports multiple syntaxes for flexibility while maintaining precision.\n *\n * @module agents/delegation-parser\n * @since v4.7.2\n */\n\nimport { logger } from '../utils/logger.js';\nimport type { ProfileLoader } from './profile-loader.js';\n\n/**\n * Parsed delegation instruction\n */\nexport interface ParsedDelegation {\n /** Target agent name */\n toAgent: string;\n\n /** Task description */\n task: string;\n\n /** Original matched text (for debugging) */\n originalText?: string;\n}\n\n/**\n * Delegation Parser\n *\n * Extracts delegation requests from agent response text using multiple patterns.\n * Supports both agent names and display names (e.g., @oliver or @devops).\n *\n * Supported syntaxes:\n * 1. `DELEGATE TO frontend: Create login UI` (explicit, backward-compatible)\n * 2. `@frontend Create login UI` (concise)\n * 3. `@frontend: Create login UI` (with colon separator)\n * 4. `Please ask frontend to create login UI` (polite request)\n * 5. `I need frontend to handle auth` (need expression)\n * 6. `請 frontend 建立登入 UI` (Chinese support)\n * 7. `委派給 backend:實現 API` (Chinese formal)\n *\n * Performance: < 1ms per parse (regex-based, no LLM calls)\n */\nexport class DelegationParser {\n private profileLoader?: ProfileLoader;\n\n /**\n * Create delegation parser with optional ProfileLoader for display name resolution\n *\n * @param profileLoader - Optional ProfileLoader for resolving display names to agent names\n */\n constructor(profileLoader?: ProfileLoader) {\n this.profileLoader = profileLoader;\n }\n\n /**\n * Parse delegation requests from agent response\n *\n * @param response - Agent response text\n * @param fromAgent - Agent name (for logging)\n * @returns Array of parsed delegations\n *\n * @example\n * ```typescript\n * const parser = new DelegationParser(profileLoader);\n * const delegations = await parser.parse(\n * \"I'll handle the backend. @Oliver Create the login UI with validation.\",\n * \"backend\"\n * );\n * // Returns: [{ toAgent: \"devops\", task: \"Create the login UI with validation.\" }]\n * // (Oliver is display name for devops agent)\n * ```\n */\n async parse(response: string, fromAgent: string): Promise<ParsedDelegation[]> {\n const delegations: Array<ParsedDelegation & { position: number }> = [];\n\n // Pattern 1: DELEGATE TO [agent]: [task]\n // Example: \"DELEGATE TO frontend: Create login UI\"\n // Priority: High (most explicit)\n const pattern1 = /DELEGATE\\s+TO\\s+([a-zA-Z0-9-_]+)\\s*:\\s*(.+?)(?=\\n\\n|(?=\\n\\s*DELEGATE\\s+TO)|(?=\\n\\s*@[\\w-]+)|(?=\\n\\s*請\\s+[\\w-]+)|(?=\\n\\s*委派給)|$)/gis;\n await this.extractMatches(pattern1, response, fromAgent, delegations, 'DELEGATE TO');\n\n // Pattern 2a: @[agent]: [task]\n // Example: \"@frontend: Create login UI\"\n // Priority: High (explicit with colon)\n const pattern2a = /@([a-zA-Z0-9-_]+)\\s*:\\s+(.+?)(?=\\n\\n|(?=\\n\\s*DELEGATE\\s+TO)|(?=\\n\\s*@[\\w-]+)|(?=\\n\\s*請\\s+[\\w-]+)|(?=\\n\\s*委派給)|$)/gis;\n await this.extractMatches(pattern2a, response, fromAgent, delegations, '@agent:');\n\n // Pattern 2b: @[agent] [task] (no colon after agent name)\n // Example: \"@frontend Create login UI\" or \"@coder 請檢視程式碼\"\n // Priority: Medium (less explicit, may have false positives)\n // Match task until: double newline, next delegation pattern, or end\n // Support both English (uppercase start) and Chinese/other languages\n // Supports multi-line tasks (e.g., bullet points)\n const pattern2b = /@([a-zA-Z0-9-_]+)\\s+([A-Z\\u4e00-\\u9fff\\u3400-\\u4dbf][\\s\\S]+?)(?:\\n\\n|(?=\\n\\s*DELEGATE\\s+TO)|(?=\\n\\s*@[\\w-]+)|(?=\\n\\s*請\\s+[\\w-]+)|(?=\\n\\s*委派給)|$)/gs;\n await this.extractMatches(pattern2b, response, fromAgent, delegations, '@agent');\n\n // Pattern 3a: Please/Request/Ask [agent] to [task]\n // Example: \"Please ask frontend to create login UI\"\n // Priority: Medium\n const pattern3a = /(?:please|request|ask)\\s+([a-zA-Z0-9-_]+)\\s+to\\s+(.+?)(?=\\n\\n|(?=\\n\\s*DELEGATE\\s+TO)|(?=\\n\\s*@[\\w-]+)|(?=\\n\\s*請\\s+[\\w-]+)|(?=\\n\\s*委派給)|(?=\\n\\s*(?:please|request|ask))|$)/gis;\n await this.extractMatches(pattern3a, response, fromAgent, delegations, 'please/request/ask');\n\n // Pattern 3b: Please/Request [agent]: [task]\n // Example: \"Request frontend: create login UI\"\n // Priority: Medium\n const pattern3b = /(?:please|request)\\s+([a-zA-Z0-9-_]+)\\s*:\\s*(.+?)(?=\\n\\n|(?=\\n\\s*DELEGATE\\s+TO)|(?=\\n\\s*@[\\w-]+)|(?=\\n\\s*請\\s+[\\w-]+)|(?=\\n\\s*委派給)|(?=\\n\\s*(?:please|request))|$)/gis;\n await this.extractMatches(pattern3b, response, fromAgent, delegations, 'please/request:');\n\n // Pattern 4: I need/require [agent] to [task]\n // Example: \"I need frontend to handle the UI\"\n // Priority: Medium\n const pattern4 = /I\\s+(?:need|require)\\s+([a-zA-Z0-9-_]+)\\s+to\\s+(.+?)(?=\\n\\n|(?=\\n\\s*DELEGATE\\s+TO)|(?=\\n\\s*@[\\w-]+)|(?=\\n\\s*請\\s+[\\w-]+)|(?=\\n\\s*委派給)|(?=\\n\\s*I\\s+(?:need|require))|$)/gis;\n await this.extractMatches(pattern4, response, fromAgent, delegations, 'I need/require');\n\n // Pattern 5a: 請 [agent] [task]\n // Example: \"請 frontend 建立登入 UI\"\n // Priority: High (Chinese explicit)\n const pattern5a = /請\\s+([a-zA-Z0-9-_]+)\\s+([^\\n@請委派]+?)(?=\\n\\n|(?=\\n\\s*DELEGATE\\s+TO)|(?=\\n\\s*@[\\w-]+)|(?=\\n\\s*請\\s+[\\w-]+)|(?=\\n\\s*委派給)|$)/gs;\n await this.extractMatches(pattern5a, response, fromAgent, delegations, '請');\n\n // Pattern 5b: 委派給 [agent]:[task] or 委派給 [agent] [task]\n // Example: \"委派給 backend:實現 API\"\n // Priority: High (Chinese formal)\n const pattern5b = /委派給\\s+([a-zA-Z0-9-_]+)\\s*[::]\\s*(.+?)(?=\\n\\n|(?=\\n\\s*DELEGATE\\s+TO)|(?=\\n\\s*@[\\w-]+)|(?=\\n\\s*請\\s+[\\w-]+)|(?=\\n\\s*委派給)|$)/gs;\n await this.extractMatches(pattern5b, response, fromAgent, delegations, '委派給');\n\n // Sort by position in text (ascending)\n delegations.sort((a, b) => a.position - b.position);\n\n // Remove position field before returning\n const result = delegations.map(({ position, ...rest }) => rest);\n\n logger.info(`Parsed ${delegations.length} delegation(s)`, {\n fromAgent,\n delegations: result.map(d => ({ toAgent: d.toAgent, taskPreview: d.task.substring(0, 50) }))\n });\n\n return result;\n }\n\n /**\n * Extract matches from a regex pattern\n *\n * @private\n */\n private async extractMatches(\n pattern: RegExp,\n response: string,\n fromAgent: string,\n delegations: Array<ParsedDelegation & { position: number }>,\n patternName: string\n ): Promise<void> {\n let match;\n while ((match = pattern.exec(response)) !== null) {\n let toAgent = match[1]?.trim();\n const task = match[2]?.trim();\n\n // Validate extracted values\n if (!toAgent || !task) {\n continue;\n }\n\n // Skip if task is too short (likely false positive)\n if (task.length < 5) {\n continue;\n }\n\n // Skip JSDoc annotations (e.g., @returns, @param)\n if (this.isJSDocAnnotation(response, match.index)) {\n logger.debug('Skipping JSDoc annotation', { toAgent, position: match.index });\n continue;\n }\n\n // Skip if in code block (between ``` or `)\n if (this.isInCodeBlock(response, match.index)) {\n logger.debug('Skipping code block', { toAgent, position: match.index });\n continue;\n }\n\n // Skip if in quoted text (e.g., examples in documentation)\n if (this.isInQuotedText(response, match.index)) {\n logger.debug('Skipping quoted text', { toAgent, position: match.index });\n continue;\n }\n\n // Skip if part of documentation examples\n if (this.isDocumentationExample(response, match.index)) {\n logger.debug('Skipping documentation example', { toAgent, position: match.index });\n continue;\n }\n\n // Resolve agent name (supports display names like \"Oliver\" → \"devops\")\n if (this.profileLoader) {\n try {\n const resolvedName = await this.profileLoader.resolveAgentName(toAgent);\n if (resolvedName !== toAgent) {\n logger.debug('Resolved display name to agent name', {\n displayName: toAgent,\n agentName: resolvedName\n });\n toAgent = resolvedName;\n }\n } catch (error) {\n // Agent not found - skip this delegation\n logger.warn('Agent not found, skipping delegation', {\n agentIdentifier: toAgent,\n fromAgent,\n error: error instanceof Error ? error.message : String(error)\n });\n continue;\n }\n }\n\n // Skip if delegating to self\n if (toAgent.toLowerCase() === fromAgent.toLowerCase()) {\n logger.warn('Skipping self-delegation', { fromAgent, toAgent });\n continue;\n }\n\n // Allow multiple delegations to the same agent (removed deduplication)\n delegations.push({\n toAgent,\n task,\n originalText: match[0],\n position: match.index // Track position in text\n });\n\n logger.debug('Delegation extracted', {\n pattern: patternName,\n fromAgent,\n toAgent,\n taskPreview: task.substring(0, 100),\n originalText: match[0]?.substring(0, 100),\n position: match.index\n });\n }\n }\n\n /**\n * Validate if a string looks like a valid agent name\n *\n * @private\n */\n private isValidAgentName(name: string): boolean {\n // Agent names should be alphanumeric with hyphens/underscores\n // 3-50 characters\n return /^[a-zA-Z0-9-_]{3,50}$/.test(name);\n }\n\n /**\n * Check if position is within a JSDoc comment block\n *\n * @private\n */\n private isJSDocAnnotation(text: string, position: number): boolean {\n // Get context before the match (up to 100 chars)\n const before = text.substring(Math.max(0, position - 100), position);\n\n // Check if preceded by JSDoc comment patterns\n // Common patterns: \" * @\", \"* @\", \" *@\"\n if (/[*\\s]+@\\w+\\s*$/.test(before)) {\n return true;\n }\n\n // Check if within a JSDoc block (/** ... */)\n const beforeFull = text.substring(0, position);\n const lastJSDocStart = beforeFull.lastIndexOf('/**');\n const lastJSDocEnd = beforeFull.lastIndexOf('*/');\n\n if (lastJSDocStart > lastJSDocEnd) {\n // Inside JSDoc block\n return true;\n }\n\n return false;\n }\n\n /**\n * Check if position is within a code block (between ``` or `)\n *\n * @private\n */\n private isInCodeBlock(text: string, position: number): boolean {\n const before = text.substring(0, position);\n\n // Check for triple backticks (```) - count should be even if not in block\n const tripleBacktickCount = (before.match(/```/g) || []).length;\n if (tripleBacktickCount % 2 === 1) {\n return true; // Inside ``` code block\n }\n\n // Check for inline code (`) - more complex due to single backticks\n // Only check if not in triple backtick block\n const lines = before.split('\\n');\n const currentLine = lines[lines.length - 1] || '';\n const singleBacktickCount = (currentLine.match(/`/g) || []).length;\n\n if (singleBacktickCount % 2 === 1) {\n return true; // Inside inline code on current line\n }\n\n return false;\n }\n\n /**\n * Check if position is within quoted text (surrounded by \" or ')\n * This helps avoid parsing delegation examples in documentation.\n *\n * @private\n */\n private isInQuotedText(text: string, position: number): boolean {\n // Get context before and after the match (up to 200 chars each)\n const before = text.substring(Math.max(0, position - 200), position);\n const after = text.substring(position, Math.min(text.length, position + 200));\n\n // Check if the match is enclosed in quotes on the same or adjacent lines\n // Look for opening quote in before text\n const lastDoubleQuote = before.lastIndexOf('\"');\n const lastSingleQuote = before.lastIndexOf(\"'\");\n const lastNewline = before.lastIndexOf('\\n');\n\n // If we found a quote after the last newline, check for closing quote\n if (lastDoubleQuote > lastNewline) {\n const closingDoubleQuote = after.indexOf('\"');\n if (closingDoubleQuote !== -1 && closingDoubleQuote < after.indexOf('\\n\\n')) {\n return true; // Enclosed in double quotes\n }\n }\n\n if (lastSingleQuote > lastNewline) {\n const closingSingleQuote = after.indexOf(\"'\");\n if (closingSingleQuote !== -1 && closingSingleQuote < after.indexOf('\\n\\n')) {\n return true; // Enclosed in single quotes\n }\n }\n\n return false;\n }\n\n /**\n * Check if position is part of documentation examples\n * Detects patterns like:\n * - Lines starting with \"Example:\", \"範例:\", \"Supported syntaxes:\"\n * - Numbered lists with quoted text: 1. \"...\", 2. \"...\", etc.\n * - Lines preceded by \"// \" comments\n * - Test code patterns: it(, test(, describe(, async () =>\n *\n * @private\n */\n private isDocumentationExample(text: string, position: number): boolean {\n // Get context before and after the match\n const before = text.substring(Math.max(0, position - 500), position); // Increased from 300\n const after = text.substring(position, Math.min(text.length, position + 200));\n\n // Split into lines for analysis\n const lines = before.split('\\n');\n const recentLines = lines.slice(-10); // Last 10 lines including current (increased from 5)\n\n // Check for example markers in recent lines\n const exampleMarkers = /(?:example|範例|supported syntaxes|syntaxes|patterns?|用法)[::]/i;\n if (recentLines.some(line => exampleMarkers.test(line))) {\n return true;\n }\n\n // Check if current line is part of a numbered list (with or without quotes)\n // Pattern: \"1. \" or \"2) \" at start of line\n const currentLine = recentLines[recentLines.length - 1] || '';\n if (/^\\s*\\d+[.)]\\s+/.test(currentLine)) {\n // Check if previous lines also have numbering (indicates a list)\n const hasNumberedContext = recentLines.slice(-5).some(line => /^\\s*\\d+[.)]\\s+/.test(line));\n if (hasNumberedContext) {\n return true;\n }\n }\n\n // Check if preceded by comment markers (// or #)\n if (/^\\s*(?:\\/\\/|#)\\s*\\d+[.)]\\s*/.test(currentLine)) {\n return true;\n }\n\n // Check for test code patterns in surrounding context\n // Look for: it(, test(, describe(, expect(, async () =>, function()\n const testCodePatterns = /(?:it|test|describe|expect)\\s*\\(|async\\s*\\(\\)\\s*=>|function\\s*\\(/i;\n if (testCodePatterns.test(before) || testCodePatterns.test(after)) {\n return true;\n }\n\n // Check if the match is part of a string literal in code\n // Look for patterns like: 'text...@agent...' or \"text...@agent...\"\n // where the quote starts before the match and ends after it\n const combinedContext = before.slice(-100) + after.slice(0, 100);\n const stringLiteralPattern = /['\"`][^'\"`]{0,100}@[a-zA-Z0-9-_]+[^'\"`]{0,100}['\"`]/;\n if (stringLiteralPattern.test(combinedContext)) {\n return true;\n }\n\n return false;\n }\n}\n","/**\n * Stage Executor - Multi-Stage Agent Execution\n *\n * Executes agents with multiple stages (workflow steps) in sequence.\n * Each stage builds on the outputs of previous stages.\n *\n * Features:\n * - Sequential stage execution\n * - Context accumulation (previous outputs fed to next stage)\n * - Per-stage configuration (model, temperature)\n * - Progress tracking\n * - Stage failure handling\n * - Memory persistence between stages\n */\n\nimport type { ExecutionContext, Stage } from '../types/agent.js';\nimport type { ExecutionResponse } from '../types/provider.js';\nimport type { IMemoryManager } from '../types/memory.js';\nimport { logger } from '../utils/logger.js';\nimport chalk from 'chalk';\nimport ora from 'ora';\n\n/**\n * Result of a single stage execution\n */\nexport interface StageExecutionResult {\n stageName: string;\n stageIndex: number;\n output: string;\n duration: number;\n tokensUsed: number;\n success: boolean;\n error?: Error;\n model?: string;\n}\n\n/**\n * Complete multi-stage execution result\n */\nexport interface MultiStageExecutionResult {\n stages: StageExecutionResult[];\n totalDuration: number;\n totalTokens: number;\n success: boolean;\n failedStage?: number;\n finalOutput: string;\n}\n\n/**\n * Options for stage execution\n */\nexport interface StageExecutionOptions {\n verbose?: boolean;\n showProgress?: boolean;\n continueOnFailure?: boolean;\n saveToMemory?: boolean;\n memoryManager?: IMemoryManager | null;\n timeout?: number; // v5.0.8: Execution timeout in milliseconds\n signal?: AbortSignal; // v5.0.8: Abort signal for cancellation\n retry?: boolean; // v5.0.8: Enable retry on failure\n}\n\n/**\n * Stage Executor\n *\n * Executes agents with multi-stage workflows where each stage:\n * 1. Receives context from previous stages\n * 2. Executes with stage-specific configuration\n * 3. Produces output for next stages\n * 4. Can optionally save to memory\n */\nexport class StageExecutor {\n /**\n * Execute all stages of an agent workflow\n */\n async executeStages(\n context: ExecutionContext,\n options: StageExecutionOptions = {}\n ): Promise<MultiStageExecutionResult> {\n const {\n verbose = false,\n showProgress = true,\n continueOnFailure = false,\n saveToMemory = false,\n memoryManager = null\n } = options;\n\n const stages = context.agent.stages || [];\n\n if (stages.length === 0) {\n throw new Error('Agent has no stages defined');\n }\n\n logger.info('Starting multi-stage execution', {\n agent: context.agent.name,\n stageCount: stages.length\n });\n\n const stageResults: StageExecutionResult[] = [];\n const previousOutputs: string[] = [];\n const startTime = Date.now();\n\n // Execute each stage sequentially\n for (let i = 0; i < stages.length; i++) {\n const stage = stages[i];\n\n // TypeScript strict mode: ensure stage exists\n if (!stage) {\n logger.error('Stage is undefined', { index: i });\n continue;\n }\n\n if (verbose) {\n console.log(chalk.cyan(`\\n${'='.repeat(60)}`));\n console.log(chalk.cyan(`Stage ${i + 1}/${stages.length}: ${stage.name}`));\n console.log(chalk.cyan(`${'='.repeat(60)}\\n`));\n console.log(chalk.gray(`Description: ${stage.description}`));\n console.log();\n }\n\n try {\n // Execute stage\n const result = await this.executeStage(\n stage,\n i,\n context,\n previousOutputs,\n { verbose, showProgress, signal: options.signal }\n );\n\n stageResults.push(result);\n\n // Save output for next stages\n if (result.success) {\n previousOutputs.push(result.output);\n\n // Optionally save to memory\n if (saveToMemory && memoryManager) {\n await this.saveStageToMemory(\n context.agent.name,\n stage,\n result,\n memoryManager\n );\n }\n } else {\n // Stage failed\n if (!continueOnFailure) {\n logger.warn('Stage failed, stopping execution', {\n stage: stage.name,\n index: i\n });\n break;\n } else {\n logger.warn('Stage failed, continuing to next stage', {\n stage: stage.name,\n index: i\n });\n }\n }\n\n } catch (error) {\n const failedResult: StageExecutionResult = {\n stageName: stage.name,\n stageIndex: i,\n output: '',\n duration: 0,\n tokensUsed: 0,\n success: false,\n error: error as Error\n };\n\n stageResults.push(failedResult);\n\n if (!continueOnFailure) {\n logger.error('Stage execution failed, stopping', {\n stage: stage.name,\n error: (error as Error).message\n });\n break;\n }\n }\n }\n\n const totalDuration = Date.now() - startTime;\n const totalTokens = stageResults.reduce((sum, r) => sum + r.tokensUsed, 0);\n const success = stageResults.every(r => r.success);\n const failedStageIndex = stageResults.findIndex(r => !r.success);\n const finalOutput = this.assembleFinalOutput(stageResults);\n\n const result: MultiStageExecutionResult = {\n stages: stageResults,\n totalDuration,\n totalTokens,\n success,\n failedStage: failedStageIndex >= 0 ? failedStageIndex : undefined,\n finalOutput\n };\n\n logger.info('Multi-stage execution complete', {\n totalStages: stages.length,\n successfulStages: stageResults.filter(r => r.success).length,\n totalDuration,\n totalTokens,\n success\n });\n\n return result;\n }\n\n /**\n * Execute a single stage\n */\n private async executeStage(\n stage: Stage,\n index: number,\n context: ExecutionContext,\n previousOutputs: string[],\n options: { verbose?: boolean; showProgress?: boolean; signal?: AbortSignal }\n ): Promise<StageExecutionResult> {\n const { verbose = false, showProgress = true } = options;\n\n // Build stage-specific prompt\n const prompt = this.buildStagePrompt(\n stage,\n context.task,\n previousOutputs,\n context.agent.stages || []\n );\n\n // Create spinner\n const spinner = showProgress\n ? ora({\n text: `Executing stage: ${stage.name}`,\n spinner: 'dots'\n }).start()\n : null;\n\n try {\n const startTime = Date.now();\n\n // Execute via provider with stage-specific config\n const response = await context.provider.execute({\n prompt,\n systemPrompt: context.agent.systemPrompt,\n model: stage.model || context.agent.model,\n temperature: stage.temperature ?? context.agent.temperature,\n maxTokens: context.agent.maxTokens,\n signal: options.signal // v5.0.8: Pass abort signal for timeout cancellation\n });\n\n const duration = Date.now() - startTime;\n\n // Stop spinner\n if (spinner) {\n spinner.succeed(`Stage complete: ${stage.name} (${duration}ms)`);\n }\n\n if (verbose) {\n console.log(chalk.green('\\n✓ Stage output:'));\n console.log(response.content);\n const tokensUsed = response.tokensUsed?.total ?? 0;\n console.log(chalk.gray(`\\nTokens used: ${tokensUsed}`));\n console.log(chalk.gray(`Duration: ${duration}ms`));\n }\n\n return {\n stageName: stage.name,\n stageIndex: index,\n output: response.content,\n duration,\n tokensUsed: response.tokensUsed?.total ?? 0,\n success: true,\n model: stage.model || context.agent.model\n };\n\n } catch (error) {\n // Stop spinner with failure\n if (spinner) {\n spinner.fail(`Stage failed: ${stage.name}`);\n }\n\n if (verbose) {\n console.error(chalk.red(`\\n✗ Stage error: ${(error as Error).message}`));\n }\n\n throw error;\n }\n }\n\n /**\n * Build prompt for a specific stage\n */\n private buildStagePrompt(\n stage: Stage,\n originalTask: string,\n previousOutputs: string[],\n allStages: Stage[]\n ): string {\n let prompt = '';\n\n // Add stage context\n prompt += `# Current Stage: ${stage.name}\\n\\n`;\n prompt += `${stage.description}\\n\\n`;\n\n // Add key questions if available\n if (stage.key_questions && stage.key_questions.length > 0) {\n prompt += `## Key Questions to Address\\n\\n`;\n stage.key_questions.forEach(q => {\n prompt += `- ${q}\\n`;\n });\n prompt += `\\n`;\n }\n\n // Add expected outputs if available\n if (stage.outputs && stage.outputs.length > 0) {\n prompt += `## Expected Outputs\\n\\n`;\n stage.outputs.forEach(o => {\n prompt += `- ${o}\\n`;\n });\n prompt += `\\n`;\n }\n\n // Add original task\n prompt += `## Original Task\\n\\n${originalTask}\\n\\n`;\n\n // Add previous stage outputs (context accumulation)\n if (previousOutputs.length > 0) {\n prompt += `## Context from Previous Stages\\n\\n`;\n previousOutputs.forEach((output, i) => {\n const prevStage = allStages[i];\n if (prevStage) {\n prompt += `### Stage ${i + 1}: ${prevStage.name}\\n\\n`;\n } else {\n prompt += `### Stage ${i + 1}: Previous Stage\\n\\n`;\n }\n prompt += `${output}\\n\\n`;\n });\n }\n\n // Add focus instruction\n prompt += `## Your Task\\n\\n`;\n prompt += `Focus on completing **${stage.name}** based on the context above. `;\n prompt += `Build on the previous stages' work and produce the expected outputs for this stage.\\n`;\n\n return prompt;\n }\n\n /**\n * Assemble final output from all stages\n */\n protected assembleFinalOutput(results: StageExecutionResult[]): string {\n if (results.length === 0) {\n return '';\n }\n\n // If only one stage, return its output or error\n if (results.length === 1) {\n const result = results[0];\n if (!result) return '';\n\n if (result.success) {\n return result.output;\n } else {\n // For failed single stage, return error information\n return `# Execution Failed\\n\\n` +\n `**Stage**: ${result.stageName}\\n\\n` +\n `**Error**: ${result.error?.message || 'Unknown error'}\\n\\n` +\n `**Duration**: ${result.duration}ms\\n`;\n }\n }\n\n // Multiple stages: combine outputs\n let output = '# Multi-Stage Execution Results\\n\\n';\n\n results.forEach((result, i) => {\n const status = result.success ? '✓' : '✗';\n output += `## Stage ${i + 1}: ${result.stageName} ${status}\\n\\n`;\n\n if (result.success) {\n output += `${result.output}\\n\\n`;\n } else {\n output += `**Failed:** ${result.error?.message || 'Unknown error'}\\n\\n`;\n }\n\n output += `---\\n\\n`;\n });\n\n return output;\n }\n\n /**\n * Save stage result to memory\n *\n * v4.11.0: No embedding required (uses FTS5)\n */\n protected async saveStageToMemory(\n agentName: string,\n stage: Stage,\n result: StageExecutionResult,\n memoryManager: IMemoryManager\n ): Promise<void> {\n try {\n const memoryContent = `[${agentName}] Stage: ${stage.name}\\n\\n${result.output}`;\n\n // v4.11.0: Save directly without embedding (uses FTS5)\n await memoryManager.add(memoryContent, null, {\n type: 'task',\n source: agentName,\n agentId: agentName,\n stage: stage.name,\n stageIndex: result.stageIndex,\n timestamp: new Date().toISOString(),\n tokensUsed: result.tokensUsed,\n duration: result.duration\n });\n\n logger.info('Stage result saved to memory', {\n agent: agentName,\n stage: stage.name,\n contentLength: memoryContent.length,\n searchMethod: 'FTS5'\n });\n\n } catch (error) {\n logger.warn('Failed to save stage to memory', {\n stage: stage.name,\n error: (error as Error).message\n });\n // Don't throw - memory save is optional\n }\n }\n\n /**\n * Display multi-stage execution result\n */\n displayResult(result: MultiStageExecutionResult, verbose: boolean = false): void {\n console.log(chalk.cyan('\\n' + '='.repeat(60)));\n console.log(chalk.cyan('Multi-Stage Execution Summary'));\n console.log(chalk.cyan('='.repeat(60)));\n\n // Summary stats\n const successCount = result.stages.filter(s => s.success).length;\n const statusColor = result.success ? chalk.green : chalk.red;\n const statusIcon = result.success ? '✓' : '✗';\n\n console.log(statusColor(`\\n${statusIcon} Status: ${result.success ? 'Success' : 'Failed'}`));\n console.log(chalk.gray(`Stages completed: ${successCount}/${result.stages.length}`));\n console.log(chalk.gray(`Total duration: ${result.totalDuration}ms`));\n console.log(chalk.gray(`Total tokens: ${result.totalTokens}`));\n\n if (result.failedStage !== undefined) {\n const failedStageResult = result.stages[result.failedStage];\n if (failedStageResult) {\n console.log(chalk.red(`Failed at stage ${result.failedStage + 1}: ${failedStageResult.stageName}`));\n }\n }\n\n // Stage details\n if (verbose) {\n console.log(chalk.cyan('\\n' + '-'.repeat(60)));\n console.log(chalk.cyan('Stage Details'));\n console.log(chalk.cyan('-'.repeat(60)));\n\n result.stages.forEach((stage, i) => {\n const icon = stage.success ? '✓' : '✗';\n const color = stage.success ? chalk.green : chalk.red;\n\n console.log(color(`\\n${icon} Stage ${i + 1}: ${stage.stageName}`));\n console.log(chalk.gray(` Duration: ${stage.duration}ms`));\n console.log(chalk.gray(` Tokens: ${stage.tokensUsed}`));\n\n if (stage.model) {\n console.log(chalk.gray(` Model: ${stage.model}`));\n }\n\n if (!stage.success && stage.error) {\n console.log(chalk.red(` Error: ${stage.error.message}`));\n }\n });\n }\n\n // Final output\n console.log(chalk.cyan('\\n' + '='.repeat(60)));\n console.log(chalk.cyan('Final Output'));\n console.log(chalk.cyan('='.repeat(60) + '\\n'));\n console.log(result.finalOutput);\n }\n}\n","/**\n * Advanced Stage Executor - Phase 3 Features\n *\n * Advanced features for multi-stage execution:\n * - Parallel execution of independent stages\n * - Conditional stage execution\n * - Stage dependency graph resolution\n * - Memory persistence with embeddings\n * - Streaming stage output\n * - Dependency visualization\n */\n\nimport type { ExecutionContext, Stage } from '../types/agent.js';\nimport type { IMemoryManager } from '../types/memory.js';\nimport { StageExecutor } from './stage-executor.js';\nimport type {\n StageExecutionResult,\n MultiStageExecutionResult,\n StageExecutionOptions\n} from './stage-executor.js';\nimport { logger } from '../utils/logger.js';\nimport chalk from 'chalk';\n\n/**\n * Stage execution plan node\n */\ninterface StageNode {\n stage: Stage;\n index: number;\n dependencies: string[];\n level: number; // Execution level (0 = no deps, 1 = depends on level 0, etc.)\n}\n\n/**\n * Execution timeline entry\n */\ninterface TimelineEntry {\n stageName: string;\n startTime: number;\n endTime: number;\n duration: number;\n level: number;\n}\n\n/**\n * Advanced Stage Executor\n *\n * Extends StageExecutor with:\n * - Dependency resolution\n * - Parallel execution\n * - Conditional execution\n * - Memory persistence\n */\nexport class AdvancedStageExecutor extends StageExecutor {\n /**\n * Execute stages with advanced features\n */\n async executeAdvanced(\n context: ExecutionContext,\n options: StageExecutionOptions = {}\n ): Promise<MultiStageExecutionResult> {\n const stages = context.agent.stages || [];\n\n if (stages.length === 0) {\n throw new Error('Agent has no stages defined');\n }\n\n // Build dependency graph\n const graph = this.buildDependencyGraph(stages);\n\n // Check for circular dependencies\n this.detectCircularDependencies(graph);\n\n // Check if any stages support parallel execution\n const hasParallelStages = stages.some(s => s.parallel);\n\n if (!hasParallelStages) {\n // Fallback to sequential execution\n logger.info('No parallel stages detected, using sequential execution');\n return this.executeStages(context, options);\n }\n\n // Execute with parallel support\n return this.executeWithParallel(context, graph, options);\n }\n\n /**\n * Build dependency graph from stages\n */\n private buildDependencyGraph(stages: Stage[]): StageNode[] {\n const graph: StageNode[] = [];\n\n // First pass: create nodes\n for (let i = 0; i < stages.length; i++) {\n const stage = stages[i];\n if (!stage) continue;\n\n graph.push({\n stage,\n index: i,\n dependencies: stage.dependencies || [],\n level: 0 // Will be calculated\n });\n }\n\n // Second pass: calculate execution levels\n this.calculateLevels(graph);\n\n return graph;\n }\n\n /**\n * Calculate execution level for each stage\n * Level 0 = no dependencies, Level N = depends on stages at level N-1\n */\n private calculateLevels(graph: StageNode[]): void {\n const maxIterations = graph.length;\n let iteration = 0;\n\n while (iteration < maxIterations) {\n let changed = false;\n\n for (const node of graph) {\n if (node.dependencies.length === 0) {\n node.level = 0;\n continue;\n }\n\n // Find max level of dependencies\n let maxDepLevel = -1;\n for (const depName of node.dependencies) {\n const depNode = graph.find(n => n.stage.name === depName);\n if (depNode) {\n maxDepLevel = Math.max(maxDepLevel, depNode.level);\n }\n }\n\n const newLevel = maxDepLevel + 1;\n if (newLevel !== node.level) {\n node.level = newLevel;\n changed = true;\n }\n }\n\n if (!changed) break;\n iteration++;\n }\n }\n\n /**\n * Detect circular dependencies\n */\n private detectCircularDependencies(graph: StageNode[]): void {\n const visiting = new Set<string>();\n const visited = new Set<string>();\n\n const visit = (nodeName: string): void => {\n if (visiting.has(nodeName)) {\n throw new Error(`Circular dependency detected involving stage: ${nodeName}`);\n }\n\n if (visited.has(nodeName)) {\n return;\n }\n\n visiting.add(nodeName);\n\n const node = graph.find(n => n.stage.name === nodeName);\n if (node) {\n for (const dep of node.dependencies) {\n visit(dep);\n }\n }\n\n visiting.delete(nodeName);\n visited.add(nodeName);\n };\n\n for (const node of graph) {\n visit(node.stage.name);\n }\n }\n\n /**\n * Execute stages with parallel support\n */\n private async executeWithParallel(\n context: ExecutionContext,\n graph: StageNode[],\n options: StageExecutionOptions\n ): Promise<MultiStageExecutionResult> {\n const { verbose = false, memoryManager = null, continueOnFailure = false } = options;\n\n // Group stages by execution level\n const maxLevel = Math.max(...graph.map(n => n.level));\n const levelGroups: StageNode[][] = [];\n\n for (let level = 0; level <= maxLevel; level++) {\n levelGroups.push(graph.filter(n => n.level === level));\n }\n\n if (verbose) {\n console.log(chalk.cyan('\\n📊 Execution Plan:'));\n for (let level = 0; level <= maxLevel; level++) {\n const nodesAtLevel = levelGroups[level];\n if (!nodesAtLevel) continue;\n\n console.log(chalk.gray(` Level ${level}: ${nodesAtLevel.map(n => n.stage.name).join(', ')}`));\n }\n console.log();\n }\n\n const allResults: StageExecutionResult[] = [];\n const stageOutputs = new Map<string, string>(); // stageName -> output\n const stageResults = new Map<string, StageExecutionResult>(); // stageName -> result\n const timeline: TimelineEntry[] = [];\n const startTime = Date.now();\n\n // Execute level by level\n for (let level = 0; level <= maxLevel; level++) {\n const nodesAtLevel = levelGroups[level];\n if (!nodesAtLevel || nodesAtLevel.length === 0) continue;\n\n if (verbose) {\n console.log(chalk.cyan(`\\n▶ Executing Level ${level} (${nodesAtLevel.length} stage${nodesAtLevel.length > 1 ? 's' : ''})...\\n`));\n }\n\n // Check which stages can run in parallel\n const parallelNodes = nodesAtLevel.filter(n => n.stage.parallel);\n const sequentialNodes = nodesAtLevel.filter(n => !n.stage.parallel);\n\n // Execute parallel stages\n if (parallelNodes.length > 0) {\n const parallelPromises = parallelNodes.map(node =>\n this.executeNode(node, context, stageOutputs, stageResults, options, timeline)\n );\n\n const parallelResults = await Promise.all(parallelPromises);\n allResults.push(...parallelResults);\n\n // Store outputs and results (skip '[Skipped due to condition]' outputs)\n for (const result of parallelResults) {\n stageResults.set(result.stageName, result);\n if (result.success && result.output !== '[Skipped due to condition]') {\n stageOutputs.set(result.stageName, result.output);\n }\n }\n\n // Check for failures in parallel stages\n if (!continueOnFailure) {\n const failedStage = parallelResults.find(r => !r.success);\n if (failedStage) {\n logger.warn('Parallel stage failed, stopping execution', {\n stage: failedStage.stageName\n });\n // Skip remaining levels\n const totalDuration = Date.now() - startTime;\n const totalTokens = allResults.reduce((sum, r) => sum + r.tokensUsed, 0);\n return {\n stages: allResults,\n totalDuration,\n totalTokens,\n success: false,\n failedStage: allResults.findIndex(r => !r.success),\n finalOutput: this.assembleFinalOutput(allResults)\n };\n }\n }\n }\n\n // Execute sequential stages\n for (const node of sequentialNodes) {\n const result = await this.executeNode(node, context, stageOutputs, stageResults, options, timeline);\n allResults.push(result);\n\n stageResults.set(result.stageName, result);\n if (result.success && result.output !== '[Skipped due to condition]') {\n stageOutputs.set(result.stageName, result.output);\n } else if (!result.success && !continueOnFailure) {\n // Stage failed and continueOnFailure is false\n logger.warn('Sequential stage failed, stopping execution', {\n stage: result.stageName\n });\n // Skip remaining levels\n const totalDuration = Date.now() - startTime;\n const totalTokens = allResults.reduce((sum, r) => sum + r.tokensUsed, 0);\n return {\n stages: allResults,\n totalDuration,\n totalTokens,\n success: false,\n failedStage: allResults.findIndex(r => !r.success),\n finalOutput: this.assembleFinalOutput(allResults)\n };\n }\n }\n }\n\n const totalDuration = Date.now() - startTime;\n const totalTokens = allResults.reduce((sum, r) => sum + r.tokensUsed, 0);\n const success = allResults.every(r => r.success);\n const failedStageIndex = allResults.findIndex(r => !r.success);\n\n // Generate final output\n const finalOutput = this.assembleFinalOutput(allResults);\n\n return {\n stages: allResults,\n totalDuration,\n totalTokens,\n success,\n failedStage: failedStageIndex >= 0 ? failedStageIndex : undefined,\n finalOutput\n };\n }\n\n /**\n * Execute a single stage node\n */\n private async executeNode(\n node: StageNode,\n context: ExecutionContext,\n stageOutputs: Map<string, string>,\n stageResults: Map<string, StageExecutionResult>,\n options: StageExecutionOptions,\n timeline: TimelineEntry[]\n ): Promise<StageExecutionResult> {\n const { stage } = node;\n const { verbose = false, memoryManager = null } = options;\n\n // Check if all dependencies succeeded\n for (const dep of node.dependencies) {\n const depResult = stageResults.get(dep);\n if (!depResult) {\n // Dependency hasn't been executed yet (shouldn't happen with proper dependency graph)\n if (verbose) {\n console.log(chalk.red(`⚠ Skipping stage \"${stage.name}\" (dependency \"${dep}\" not executed)\\n`));\n }\n return {\n stageName: stage.name,\n stageIndex: node.index,\n output: `[Skipped: dependency \"${dep}\" not executed]`,\n duration: 0,\n tokensUsed: 0,\n success: false,\n error: new Error(`Dependency \"${dep}\" not executed`)\n };\n }\n\n if (!depResult.success) {\n // Dependency failed\n if (verbose) {\n console.log(chalk.yellow(`⊘ Skipping stage \"${stage.name}\" (dependency \"${dep}\" failed)\\n`));\n }\n return {\n stageName: stage.name,\n stageIndex: node.index,\n output: `[Skipped: dependency \"${dep}\" failed]`,\n duration: 0,\n tokensUsed: 0,\n success: false,\n error: new Error(`Dependency \"${dep}\" failed`)\n };\n }\n }\n\n // Check condition\n if (stage.condition) {\n const shouldExecute = this.evaluateCondition(stage.condition, stageOutputs, stageResults);\n if (!shouldExecute) {\n if (verbose) {\n console.log(chalk.yellow(`⊘ Skipping stage \"${stage.name}\" (condition not met)\\n`));\n }\n\n return {\n stageName: stage.name,\n stageIndex: node.index,\n output: '[Skipped due to condition]',\n duration: 0,\n tokensUsed: 0,\n success: true\n };\n }\n }\n\n // Build context from dependencies\n const previousOutputs: string[] = [];\n for (const dep of node.dependencies) {\n const output = stageOutputs.get(dep);\n if (output) {\n previousOutputs.push(output);\n }\n }\n\n // Execute stage\n const stageStartTime = Date.now();\n\n try {\n const result = await this.executeStageInternal(\n stage,\n node.index,\n context,\n previousOutputs,\n options\n );\n\n const stageEndTime = Date.now();\n\n // Record timeline\n timeline.push({\n stageName: stage.name,\n startTime: stageStartTime,\n endTime: stageEndTime,\n duration: stageEndTime - stageStartTime,\n level: node.level\n });\n\n // Save to memory if requested\n if (stage.saveToMemory && result.success && memoryManager) {\n await this.saveStageToMemory(\n context.agent.name,\n stage,\n result,\n memoryManager\n );\n }\n\n return result;\n\n } catch (error) {\n return {\n stageName: stage.name,\n stageIndex: node.index,\n output: '',\n duration: Date.now() - stageStartTime,\n tokensUsed: 0,\n success: false,\n error: error as Error\n };\n }\n }\n\n /**\n * Execute stage internal (copied from parent but made accessible)\n */\n private async executeStageInternal(\n stage: Stage,\n index: number,\n context: ExecutionContext,\n previousOutputs: string[],\n options: { verbose?: boolean; showProgress?: boolean; signal?: AbortSignal }\n ): Promise<StageExecutionResult> {\n // Call parent's private method via public interface\n // Note: This is a workaround - in production we'd refactor StageExecutor\n const allStages = context.agent.stages || [];\n const tempContext = { ...context, agent: { ...context.agent, stages: [stage] } };\n\n // Build prompt manually\n const prompt = this.buildStagePromptManual(stage, context.task, previousOutputs, allStages);\n\n const startTime = Date.now();\n const response = await context.provider.execute({\n prompt,\n systemPrompt: context.agent.systemPrompt,\n model: stage.model || context.agent.model,\n temperature: stage.temperature ?? context.agent.temperature,\n maxTokens: context.agent.maxTokens,\n signal: options.signal // v5.0.8: Pass abort signal for timeout cancellation\n });\n\n const duration = Date.now() - startTime;\n\n return {\n stageName: stage.name,\n stageIndex: index,\n output: response.content,\n duration,\n tokensUsed: response.tokensUsed?.total ?? 0,\n success: true,\n model: stage.model || context.agent.model\n };\n }\n\n /**\n * Build stage prompt manually\n */\n private buildStagePromptManual(\n stage: Stage,\n originalTask: string,\n previousOutputs: string[],\n allStages: Stage[]\n ): string {\n let prompt = '';\n\n prompt += `# Current Stage: ${stage.name}\\n\\n`;\n prompt += `${stage.description}\\n\\n`;\n\n if (stage.key_questions && stage.key_questions.length > 0) {\n prompt += `## Key Questions to Address\\n\\n`;\n stage.key_questions.forEach(q => {\n prompt += `- ${q}\\n`;\n });\n prompt += `\\n`;\n }\n\n if (stage.outputs && stage.outputs.length > 0) {\n prompt += `## Expected Outputs\\n\\n`;\n stage.outputs.forEach(o => {\n prompt += `- ${o}\\n`;\n });\n prompt += `\\n`;\n }\n\n prompt += `## Original Task\\n\\n${originalTask}\\n\\n`;\n\n if (previousOutputs.length > 0) {\n prompt += `## Context from Previous Stages\\n\\n`;\n previousOutputs.forEach((output, i) => {\n prompt += `### Previous Stage ${i + 1}\\n\\n${output}\\n\\n`;\n });\n }\n\n prompt += `## Your Task\\n\\n`;\n prompt += `Focus on completing **${stage.name}** based on the context above.\\n`;\n\n return prompt;\n }\n\n /**\n * Evaluate condition string\n * Simple implementation - supports basic conditions\n */\n private evaluateCondition(\n condition: string,\n stageOutputs: Map<string, string>,\n stageResults: Map<string, StageExecutionResult>\n ): boolean {\n // Simple condition evaluation\n // Example: \"previous.success\" or \"data_fetch.success\"\n\n if (condition === 'previous.success') {\n // Check if all previous stages succeeded\n if (stageResults.size === 0) {\n return false;\n }\n // Check if any stage failed\n for (const result of stageResults.values()) {\n if (!result.success && result.output !== '[Skipped due to condition]') {\n return false;\n }\n }\n return true;\n }\n\n // Check specific stage success\n const match = condition.match(/^(\\w+)\\.success$/);\n if (match && match[1]) {\n const stageName = match[1];\n const result = stageResults.get(stageName);\n return result !== undefined && result.success;\n }\n\n // Default: execute the stage\n return true;\n }\n\n /**\n * Generate dependency graph visualization (ASCII art)\n */\n visualizeDependencyGraph(stages: Stage[]): string {\n const graph = this.buildDependencyGraph(stages);\n let output = '\\n' + chalk.cyan('📊 Stage Dependency Graph\\n\\n');\n\n const maxLevel = Math.max(...graph.map(n => n.level));\n\n for (let level = 0; level <= maxLevel; level++) {\n const nodesAtLevel = graph.filter(n => n.level === level);\n\n output += chalk.gray(`Level ${level}:\\n`);\n\n for (const node of nodesAtLevel) {\n const parallel = node.stage.parallel ? chalk.green(' [parallel]') : '';\n const condition = node.stage.condition ? chalk.yellow(` [if: ${node.stage.condition}]`) : '';\n\n output += ` ${chalk.cyan('○')} ${node.stage.name}${parallel}${condition}\\n`;\n\n // Show dependencies\n if (node.dependencies.length > 0) {\n output += chalk.gray(` ↳ depends on: ${node.dependencies.join(', ')}\\n`);\n }\n }\n\n output += '\\n';\n }\n\n return output;\n }\n\n /**\n * Generate execution timeline visualization\n */\n visualizeTimeline(timeline: TimelineEntry[]): string {\n let output = '\\n' + chalk.cyan('⏱️ Execution Timeline\\n\\n');\n\n const maxLevel = Math.max(...timeline.map(t => t.level));\n const totalDuration = Math.max(...timeline.map(t => t.endTime)) - Math.min(...timeline.map(t => t.startTime));\n\n for (let level = 0; level <= maxLevel; level++) {\n const entriesAtLevel = timeline.filter(t => t.level === level);\n\n output += chalk.gray(`Level ${level}:\\n`);\n\n for (const entry of entriesAtLevel) {\n const bar = '█'.repeat(Math.max(1, Math.floor((entry.duration / totalDuration) * 40)));\n output += ` ${entry.stageName.padEnd(20)} ${chalk.green(bar)} ${entry.duration}ms\\n`;\n }\n\n output += '\\n';\n }\n\n return output;\n }\n}\n","/**\n * Router - AI Provider Router with Fallback\n *\n * Routes requests to available providers based on:\n * - Provider priority\n * - Provider health\n * - Rate limit status\n * - Automatic fallback on failure\n */\n\nimport type {\n Provider,\n ExecutionRequest,\n ExecutionResponse,\n HealthStatus\n} from '../types/provider.js';\nimport { logger } from '../utils/logger.js';\nimport { ProviderError, ErrorCode } from '../utils/errors.js';\n\nexport interface RouterConfig {\n providers: Provider[];\n fallbackEnabled: boolean;\n healthCheckInterval?: number;\n providerCooldownMs?: number; // Cooldown period for failed providers (default: 30000ms)\n}\n\nexport class Router {\n private providers: Provider[];\n private fallbackEnabled: boolean;\n private healthCheckInterval?: NodeJS.Timeout;\n private penalizedProviders: Map<string, number>; // provider name -> penalty expiry timestamp\n private providerCooldownMs: number;\n\n constructor(config: RouterConfig) {\n // Sort providers by priority (lower number = higher priority)\n this.providers = [...config.providers].sort((a, b) => {\n return a.priority - b.priority;\n });\n this.fallbackEnabled = config.fallbackEnabled;\n this.penalizedProviders = new Map();\n this.providerCooldownMs = config.providerCooldownMs ?? 30000; // Default: 30 seconds\n\n // Start health checks if interval is provided\n if (config.healthCheckInterval) {\n this.startHealthChecks(config.healthCheckInterval);\n }\n }\n\n /**\n * Execute request with automatic provider fallback\n */\n async execute(request: ExecutionRequest): Promise<ExecutionResponse> {\n const availableProviders = await this.getAvailableProviders();\n\n if (availableProviders.length === 0) {\n throw ProviderError.noAvailableProviders();\n }\n\n let lastError: Error | undefined;\n\n for (const provider of availableProviders) {\n try {\n logger.info(`Attempting execution with provider: ${provider.name}`);\n\n const response = await provider.execute(request);\n\n logger.info(`Execution successful with provider: ${provider.name}`, {\n latency: response.latencyMs,\n tokens: response.tokensUsed.total\n });\n\n // Remove provider from penalty list on success\n this.penalizedProviders.delete(provider.name);\n\n return response;\n\n } catch (error) {\n lastError = error as Error;\n\n logger.warn(`Provider ${provider.name} failed`, {\n error: lastError.message\n });\n\n // Penalize failed provider (add cooldown period)\n const penaltyExpiry = Date.now() + this.providerCooldownMs;\n this.penalizedProviders.set(provider.name, penaltyExpiry);\n\n logger.debug(`Provider ${provider.name} penalized until ${new Date(penaltyExpiry).toISOString()}`);\n\n // If fallback is disabled, throw immediately\n if (!this.fallbackEnabled) {\n throw lastError;\n }\n\n // Continue to next provider\n continue;\n }\n }\n\n // All providers failed\n throw new ProviderError(\n `All providers failed. Last error: ${lastError?.message || 'Unknown error'}`,\n ErrorCode.PROVIDER_NO_AVAILABLE,\n [\n 'Check provider availability with \"automatosx status\"',\n 'Verify provider CLIs are installed and in PATH',\n 'Check provider configuration in automatosx.config.json',\n 'Review error logs for more details'\n ],\n { lastError: lastError?.message }\n );\n }\n\n /**\n * Get available providers sorted by priority\n * Filters out penalized providers (those in cooldown period)\n */\n async getAvailableProviders(): Promise<Provider[]> {\n const now = Date.now();\n\n // Clean up expired penalties\n for (const [providerName, expiryTime] of this.penalizedProviders.entries()) {\n if (now >= expiryTime) {\n this.penalizedProviders.delete(providerName);\n logger.debug(`Provider ${providerName} penalty expired`);\n }\n }\n\n // Check availability in parallel\n const checks = this.providers.map(async provider => {\n try {\n // Skip penalized providers\n if (this.penalizedProviders.has(provider.name)) {\n const expiryTime = this.penalizedProviders.get(provider.name)!;\n const remainingMs = expiryTime - now;\n logger.debug(`Skipping penalized provider ${provider.name} (${Math.ceil(remainingMs / 1000)}s remaining)`);\n return null;\n }\n\n // Check if provider is available\n const isAvailable = await provider.isAvailable();\n return isAvailable ? provider : null;\n } catch (error) {\n logger.warn('Provider availability check failed', {\n provider: provider.name,\n error: (error as Error).message\n });\n return null;\n }\n });\n\n const results = await Promise.all(checks);\n return results.filter((p): p is Provider => p !== null);\n }\n\n /**\n * Get health status of all providers\n */\n async getHealthStatus(): Promise<Map<string, HealthStatus>> {\n const healthMap = new Map<string, HealthStatus>();\n\n for (const provider of this.providers) {\n const health = await provider.getHealth();\n healthMap.set(provider.name, health);\n }\n\n return healthMap;\n }\n\n /**\n * Select best provider based on health and availability\n */\n async selectProvider(): Promise<Provider | null> {\n const availableProviders = await this.getAvailableProviders();\n\n if (availableProviders.length === 0) {\n return null;\n }\n\n // Return first available provider (already sorted by priority)\n return availableProviders[0] ?? null;\n }\n\n /**\n * Start periodic health checks\n */\n private startHealthChecks(intervalMs: number): void {\n const runHealthChecks = async () => {\n try {\n const healthStatus = await this.getHealthStatus();\n\n logger.debug('Provider health check', {\n providers: Array.from(healthStatus.entries()).map(([name, health]) => ({\n name,\n available: health.available,\n latency: health.latencyMs,\n failures: health.consecutiveFailures\n }))\n });\n } catch (error) {\n logger.warn('Provider health check failed', {\n error: (error as Error).message\n });\n }\n };\n\n // Set up interval\n this.healthCheckInterval = setInterval(() => {\n void runHealthChecks(); // Explicitly handle promise\n }, intervalMs);\n\n // Run immediately on start\n void runHealthChecks();\n }\n\n /**\n * Stop health checks and cleanup resources\n */\n destroy(): void {\n if (this.healthCheckInterval) {\n clearInterval(this.healthCheckInterval);\n this.healthCheckInterval = undefined;\n }\n\n // Clear penalty list\n this.penalizedProviders.clear();\n }\n}\n","/**\n * Session Manager - Manages multi-agent collaborative sessions\n *\n * @module core/session-manager\n * @since v4.7.0\n */\n\nimport { randomUUID } from 'crypto';\nimport { readFile, writeFile, mkdir, rename, copyFile, unlink } from 'fs/promises';\nimport { dirname } from 'path';\nimport type { Session } from '../types/orchestration.js';\nimport { SessionError } from '../types/orchestration.js';\nimport { logger } from '../utils/logger.js';\n\n/**\n * Session Manager\n *\n * Manages the lifecycle of multi-agent collaborative sessions, providing:\n * - Session creation and tracking\n * - Agent participation tracking\n * - Session completion and failure handling\n * - Automatic cleanup of old sessions\n *\n * @example\n * ```typescript\n * const sessionManager = new SessionManager();\n *\n * // Create session\n * const session = await sessionManager.createSession(\n * 'Implement auth feature',\n * 'backend'\n * );\n *\n * // Add agents as they join\n * await sessionManager.addAgent(session.id, 'frontend');\n * await sessionManager.addAgent(session.id, 'security');\n *\n * // Complete session\n * await sessionManager.completeSession(session.id);\n * ```\n */\nexport class SessionManager {\n /** Active sessions (in-memory, keyed by session ID) */\n private activeSessions: Map<string, Session> = new Map();\n\n /** Maximum number of sessions to keep in memory (oldest are cleaned up) */\n private readonly MAX_SESSIONS: number;\n\n /** Path to persistence file (optional) */\n private readonly persistencePath?: string;\n\n /** Pending save operation (for debouncing) */\n private saveTimeout?: NodeJS.Timeout;\n\n /** Pending save promise (for flushing) */\n private pendingSave?: Promise<void>;\n\n /** Maximum metadata size (10 KB) */\n private readonly MAX_METADATA_SIZE = 10 * 1024;\n\n /** UUID v4 validation regex (static for performance) */\n private static readonly UUID_V4_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n\n /**\n * Validate session ID format (must be valid UUID v4)\n *\n * @param sessionId - Session ID to validate\n * @throws {SessionError} If session ID is invalid\n * @private\n */\n private validateSessionId(sessionId: string): void {\n // Check for empty/whitespace session ID\n if (!sessionId || sessionId.trim().length === 0) {\n throw new SessionError(\n 'Session ID cannot be empty. Must be a valid UUID v4.',\n sessionId,\n 'invalid_format'\n );\n }\n\n // UUID v4 format: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\n // where y is 8, 9, a, or b\n if (!SessionManager.UUID_V4_REGEX.test(sessionId)) {\n throw new SessionError(\n `Invalid session ID format: ${sessionId}. Session IDs must be valid UUID v4.`,\n sessionId,\n 'invalid_format'\n );\n }\n }\n\n /**\n * Create SessionManager instance\n *\n * @param config - Configuration options\n * @param config.persistencePath - Optional path to JSON file for persistence\n * @param config.maxSessions - Maximum sessions to keep in memory (default: 100)\n *\n * @example\n * ```typescript\n * // In-memory only (no persistence)\n * const sessionManager = new SessionManager();\n *\n * // With persistence\n * const sessionManager = new SessionManager({\n * persistencePath: '.automatosx/sessions/sessions.json'\n * });\n * await sessionManager.initialize();\n *\n * // With custom limit\n * const sessionManager = new SessionManager({\n * persistencePath: '.automatosx/sessions/sessions.json',\n * maxSessions: 1000 // For large-scale systems\n * });\n * ```\n */\n constructor(config?: { persistencePath?: string; maxSessions?: number }) {\n this.persistencePath = config?.persistencePath;\n this.MAX_SESSIONS = config?.maxSessions ?? 100;\n }\n\n /**\n * Initialize session manager (load from persistence if configured)\n *\n * @example\n * ```typescript\n * const sessionManager = new SessionManager({\n * persistencePath: '.automatosx/sessions/sessions.json'\n * });\n * await sessionManager.initialize();\n * ```\n */\n async initialize(): Promise<void> {\n if (this.persistencePath) {\n await this.loadFromFile();\n }\n }\n\n /**\n * Create a new session\n *\n * @param task - Overall task/goal for the session\n * @param initiator - Agent that initiated the session\n * @returns Created session\n *\n * @example\n * ```typescript\n * const session = await sessionManager.createSession(\n * 'Implement authentication feature',\n * 'backend'\n * );\n * console.log('Session created:', session.id);\n * ```\n */\n async createSession(task: string, initiator: string): Promise<Session> {\n // Auto cleanup if approaching limit (prevent memory exhaustion)\n if (this.activeSessions.size >= this.MAX_SESSIONS) {\n logger.info('Session limit approaching, running auto cleanup', {\n current: this.activeSessions.size,\n limit: this.MAX_SESSIONS\n });\n await this.cleanup(); // Remove oldest completed sessions\n }\n\n // Generate unique session ID (handle extremely rare UUID collisions)\n let sessionId = randomUUID();\n let attempts = 0;\n const MAX_UUID_ATTEMPTS = 100;\n while (this.activeSessions.has(sessionId)) {\n if (++attempts >= MAX_UUID_ATTEMPTS) {\n throw new SessionError(\n `Failed to generate unique session ID after ${MAX_UUID_ATTEMPTS} attempts`,\n undefined,\n 'creation_failed'\n );\n }\n sessionId = randomUUID();\n }\n\n const session: Session = {\n id: sessionId,\n initiator,\n task,\n agents: [initiator], // Initiator is first agent\n status: 'active',\n createdAt: new Date(),\n updatedAt: new Date(),\n metadata: {}\n };\n\n this.activeSessions.set(session.id, session);\n\n logger.info('Session created', {\n sessionId: session.id,\n initiator,\n task: task.substring(0, 100) + (task.length > 100 ? '...' : '')\n });\n\n // Cleanup old completed/failed sessions (prevents memory leak)\n // This runs after session creation to avoid blocking the creation process\n await this.cleanupOldSessions(7); // Clean sessions older than 7 days\n\n // Persist to file\n this.saveToFile();\n\n return session;\n }\n\n /**\n * Add an agent to an existing session\n *\n * @param sessionId - Session ID\n * @param agentName - Agent to add\n * @throws {SessionError} If session not found\n *\n * @example\n * ```typescript\n * await sessionManager.addAgent(session.id, 'frontend');\n * await sessionManager.addAgent(session.id, 'security');\n * ```\n */\n async addAgent(sessionId: string, agentName: string): Promise<void> {\n // Validate session ID format\n this.validateSessionId(sessionId);\n\n const session = this.activeSessions.get(sessionId);\n\n if (!session) {\n throw new SessionError(\n `Session not found: ${sessionId}`,\n sessionId,\n 'not_found'\n );\n }\n\n // Only add if not already in the session\n if (!session.agents.includes(agentName)) {\n session.agents.push(agentName);\n session.updatedAt = new Date();\n\n logger.debug('Agent added to session', {\n sessionId,\n agentName,\n totalAgents: session.agents.length\n });\n\n // Persist to file\n this.saveToFile();\n }\n }\n\n /**\n * Get a session by ID\n *\n * @param sessionId - Session ID\n * @returns Session if found, null otherwise\n *\n * @example\n * ```typescript\n * const session = await sessionManager.getSession('session-123');\n * if (session) {\n * console.log('Session status:', session.status);\n * }\n * ```\n */\n async getSession(sessionId: string): Promise<Session | null> {\n // Validate session ID format (return null for invalid IDs)\n try {\n this.validateSessionId(sessionId);\n } catch {\n return null; // Invalid format = session doesn't exist\n }\n\n return this.activeSessions.get(sessionId) ?? null;\n }\n\n /**\n * Get all active sessions\n *\n * @returns Array of active sessions\n *\n * @example\n * ```typescript\n * const active = await sessionManager.getActiveSessions();\n * console.log(`${active.length} active sessions`);\n * ```\n */\n async getActiveSessions(): Promise<Session[]> {\n return Array.from(this.activeSessions.values())\n .filter(s => s.status === 'active');\n }\n\n /**\n * Get active sessions for a specific agent\n *\n * @param agentName - Agent name\n * @returns Array of sessions where agent is involved\n *\n * @example\n * ```typescript\n * const sessions = await sessionManager.getActiveSessionsForAgent('backend');\n * console.log(`Backend is involved in ${sessions.length} sessions`);\n * ```\n */\n async getActiveSessionsForAgent(agentName: string): Promise<Session[]> {\n return Array.from(this.activeSessions.values())\n .filter(s =>\n s.status === 'active' &&\n s.agents.includes(agentName)\n )\n .sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime());\n }\n\n /**\n * Complete a session successfully\n *\n * @param sessionId - Session ID\n * @throws {SessionError} If session not found\n *\n * @example\n * ```typescript\n * await sessionManager.completeSession(session.id);\n * ```\n */\n async completeSession(sessionId: string): Promise<void> {\n // Validate session ID format\n this.validateSessionId(sessionId);\n\n const session = this.activeSessions.get(sessionId);\n\n if (!session) {\n throw new SessionError(\n `Session not found: ${sessionId}`,\n sessionId,\n 'not_found'\n );\n }\n\n if (session.status === 'completed') {\n logger.warn('Session already completed', { sessionId });\n return;\n }\n\n session.status = 'completed';\n session.updatedAt = new Date();\n\n const duration = session.updatedAt.getTime() - session.createdAt.getTime();\n\n logger.info('Session completed', {\n sessionId,\n duration: `${(duration / 1000).toFixed(1)}s`,\n agents: session.agents.length,\n agentList: session.agents.join(', ')\n });\n\n // Persist to file\n this.saveToFile();\n }\n\n /**\n * Mark a session as failed\n *\n * @param sessionId - Session ID\n * @param error - Error that caused the failure\n * @throws {SessionError} If session not found\n *\n * @example\n * ```typescript\n * try {\n * await delegateToAgent(...);\n * } catch (error) {\n * await sessionManager.failSession(session.id, error);\n * }\n * ```\n */\n async failSession(sessionId: string, error: Error): Promise<void> {\n // Validate session ID format (gracefully handle invalid IDs)\n try {\n this.validateSessionId(sessionId);\n } catch {\n logger.warn('Cannot fail session - invalid ID format', { sessionId });\n return;\n }\n\n const session = this.activeSessions.get(sessionId);\n\n if (!session) {\n // Session might have been cleaned up, just log and return\n logger.warn('Cannot fail session - not found', { sessionId });\n return;\n }\n\n session.status = 'failed';\n session.updatedAt = new Date();\n session.metadata = {\n ...session.metadata,\n error: error.message,\n errorStack: error.stack\n };\n\n logger.warn('Session failed', {\n sessionId,\n error: error.message,\n agents: session.agents.join(', ')\n });\n\n // Persist to file\n this.saveToFile();\n }\n\n /**\n * Update session metadata\n *\n * @param sessionId - Session ID\n * @param metadata - Metadata to merge\n * @throws {SessionError} If session not found\n *\n * @example\n * ```typescript\n * await sessionManager.updateMetadata(session.id, {\n * priority: 'high',\n * tags: ['auth', 'security']\n * });\n * ```\n */\n async updateMetadata(\n sessionId: string,\n metadata: Record<string, any>\n ): Promise<void> {\n // Validate session ID format\n this.validateSessionId(sessionId);\n\n const session = this.activeSessions.get(sessionId);\n\n if (!session) {\n throw new SessionError(\n `Session not found: ${sessionId}`,\n sessionId,\n 'not_found'\n );\n }\n\n // Merge metadata\n const newMetadata = {\n ...session.metadata,\n ...metadata\n };\n\n // Check metadata size (prevent DoS attacks)\n // Use Buffer.byteLength for accurate byte count (handles multi-byte characters)\n let metadataSize: number;\n try {\n metadataSize = Buffer.byteLength(JSON.stringify(newMetadata), 'utf-8');\n } catch (error) {\n throw new SessionError(\n `Metadata contains circular reference or non-serializable value: ${(error as Error).message}`,\n sessionId,\n 'metadata_too_large'\n );\n }\n\n if (metadataSize > this.MAX_METADATA_SIZE) {\n throw new SessionError(\n `Metadata too large: ${metadataSize} bytes (max: ${this.MAX_METADATA_SIZE} bytes)`,\n sessionId,\n 'metadata_too_large'\n );\n }\n\n session.metadata = newMetadata;\n session.updatedAt = new Date();\n\n logger.debug('Session metadata updated', {\n sessionId,\n metadata: Object.keys(metadata)\n });\n\n // Persist to file\n this.saveToFile();\n }\n\n /**\n * Cleanup old sessions (keep last MAX_SESSIONS)\n *\n * Removes oldest sessions (by update time) when limit is exceeded.\n *\n * @returns Number of sessions removed\n *\n * @example\n * ```typescript\n * const removed = await sessionManager.cleanup();\n * console.log(`Cleaned up ${removed} old sessions`);\n * ```\n */\n async cleanup(): Promise<number> {\n if (this.activeSessions.size <= this.MAX_SESSIONS) {\n return 0;\n }\n\n // Prioritize removing completed/failed sessions over active ones\n // Sort by: 1) status (completed/failed first), 2) update time (oldest first)\n const sessions = Array.from(this.activeSessions.values())\n .sort((a, b) => {\n // Priority: completed/failed before active\n const statusPriority = (s: Session) => s.status === 'active' ? 1 : 0;\n const priorityDiff = statusPriority(a) - statusPriority(b);\n if (priorityDiff !== 0) return priorityDiff;\n\n // If same status, sort by update time (oldest first)\n return a.updatedAt.getTime() - b.updatedAt.getTime();\n });\n\n // Calculate how many to remove\n const toRemoveCount = sessions.length - this.MAX_SESSIONS;\n const toRemove = sessions.slice(0, toRemoveCount);\n\n // Remove selected sessions\n toRemove.forEach(session => {\n this.activeSessions.delete(session.id);\n });\n\n if (toRemoveCount > 0) {\n const statusCount = toRemove.reduce((acc, s) => {\n acc[s.status] = (acc[s.status] || 0) + 1;\n return acc;\n }, {} as Record<string, number>);\n\n logger.info('Sessions cleaned up', {\n removed: toRemoveCount,\n remaining: this.activeSessions.size,\n removedByStatus: statusCount\n });\n\n // Persist to file\n this.saveToFile();\n }\n\n return toRemoveCount;\n }\n\n /**\n * Cleanup old completed/failed sessions\n *\n * Removes sessions that are completed or failed and older than the specified age.\n * This prevents memory leaks from inactive sessions.\n *\n * @param maxAgeDays - Maximum age in days (default: 7 days)\n * @returns Object with removed count and removed session IDs\n *\n * @example\n * ```typescript\n * // Clean up sessions older than 7 days\n * const result = await sessionManager.cleanupOldSessions();\n * console.log(`Removed ${result.removedCount} sessions`);\n *\n * // Use removedSessionIds to cleanup corresponding workspaces\n * await workspaceManager.cleanupSessionWorkspaces(result.removedSessionIds);\n * ```\n */\n async cleanupOldSessions(maxAgeDays: number = 7): Promise<{\n removedCount: number;\n removedSessionIds: string[];\n }> {\n const cutoffTime = Date.now() - (maxAgeDays * 24 * 60 * 60 * 1000);\n const sessions = Array.from(this.activeSessions.values());\n\n // Only remove completed/failed sessions (keep active ones)\n const toRemove = sessions.filter(s =>\n (s.status === 'completed' || s.status === 'failed') &&\n s.updatedAt.getTime() < cutoffTime\n );\n\n const removedSessionIds = toRemove.map(s => s.id);\n toRemove.forEach(s => this.activeSessions.delete(s.id));\n\n if (toRemove.length > 0) {\n logger.info('Old sessions cleaned up', {\n removed: toRemove.length,\n cutoffDays: maxAgeDays,\n remaining: this.activeSessions.size,\n removedSessionIds: removedSessionIds.slice(0, 5) // Log first 5 IDs\n });\n\n // Persist to file\n this.saveToFile();\n }\n\n return {\n removedCount: toRemove.length,\n removedSessionIds\n };\n }\n\n /**\n * Clear all sessions (mainly for testing)\n *\n * @returns Number of sessions removed\n *\n * @example\n * ```typescript\n * await sessionManager.clearAll();\n * ```\n */\n async clearAll(): Promise<number> {\n const count = this.activeSessions.size;\n this.activeSessions.clear();\n\n if (count > 0) {\n logger.info('All sessions cleared', { count });\n\n // Persist to file\n this.saveToFile();\n }\n\n return count;\n }\n\n /**\n * Destroy session manager (cleanup resources)\n *\n * Clears pending save timeout and flushes any pending save operations.\n * Should be called before discarding the SessionManager instance.\n *\n * @example\n * ```typescript\n * const sessionManager = new SessionManager({...});\n * // ... use sessionManager ...\n * await sessionManager.destroy();\n * ```\n */\n async destroy(): Promise<void> {\n // Clear timeout\n if (this.saveTimeout) {\n clearTimeout(this.saveTimeout);\n this.saveTimeout = undefined;\n }\n\n // Flush pending save (best effort - don't let errors prevent destroy)\n try {\n await this.flushSave();\n } catch (error) {\n logger.error('Error flushing save during destroy', {\n error: (error as Error).message\n });\n // Continue with destroy even if flush fails\n }\n\n logger.debug('SessionManager destroyed', {\n sessions: this.activeSessions.size\n });\n }\n\n /**\n * Flush pending save operation (wait for completion)\n *\n * Forces immediate save if there's a pending debounced save.\n *\n * @private\n */\n private async flushSave(): Promise<void> {\n // If there's a debounced save pending, cancel it and do immediate save\n if (this.saveTimeout) {\n clearTimeout(this.saveTimeout);\n this.saveTimeout = undefined;\n\n // If there's also a pendingSave, wait for it first to avoid concurrent saves\n if (this.pendingSave) {\n try {\n await this.pendingSave;\n } catch (err) {\n // Ignore errors from previous save, we'll try again below\n }\n }\n\n // Do immediate save\n await this.doSave();\n return;\n }\n\n // No timeout, but there might be a pending save - wait for it\n if (this.pendingSave) {\n try {\n await this.pendingSave;\n } catch (err) {\n // Re-throw so destroy() knows there was a problem\n throw err;\n }\n }\n }\n\n /**\n * Perform actual save operation (internal)\n *\n * @private\n */\n private async doSave(): Promise<void> {\n if (!this.persistencePath) {\n return;\n }\n\n try {\n // Ensure directory exists\n await mkdir(dirname(this.persistencePath), { recursive: true });\n\n // Convert sessions to plain objects (Date -> string)\n const sessionsArray = Array.from(this.activeSessions.values()).map(session => ({\n id: session.id,\n initiator: session.initiator,\n task: session.task,\n agents: session.agents,\n status: session.status,\n createdAt: session.createdAt.toISOString(),\n updatedAt: session.updatedAt.toISOString(),\n metadata: session.metadata\n }));\n\n const data = JSON.stringify(sessionsArray, null, 2);\n\n // Atomic write: write to temp file then rename (prevents corruption)\n const tempPath = `${this.persistencePath}.tmp`;\n\n try {\n await writeFile(tempPath, data, 'utf-8');\n await rename(tempPath, this.persistencePath);\n\n logger.debug('Sessions saved to persistence', {\n path: this.persistencePath,\n count: sessionsArray.length\n });\n } catch (renameError) {\n // Clean up temp file if rename failed (prevents accumulation)\n try {\n await unlink(tempPath);\n } catch (unlinkError) {\n // Ignore unlink errors (file might not exist)\n }\n throw renameError;\n }\n } catch (error) {\n logger.error('Failed to save sessions to persistence', {\n path: this.persistencePath,\n error: (error as Error).message\n });\n throw error; // Re-throw for caller to handle\n }\n }\n\n /**\n * Get statistics about current sessions\n *\n * @returns Session statistics\n *\n * @example\n * ```typescript\n * const stats = await sessionManager.getStats();\n * console.log(`Active: ${stats.active}, Total: ${stats.total}`);\n * ```\n */\n async getStats(): Promise<{\n total: number;\n active: number;\n completed: number;\n failed: number;\n }> {\n const sessions = Array.from(this.activeSessions.values());\n\n return {\n total: sessions.length,\n active: sessions.filter(s => s.status === 'active').length,\n completed: sessions.filter(s => s.status === 'completed').length,\n failed: sessions.filter(s => s.status === 'failed').length\n };\n }\n\n /**\n * Load sessions from persistence file\n *\n * @private\n */\n private async loadFromFile(): Promise<void> {\n if (!this.persistencePath) {\n return;\n }\n\n try {\n const data = await readFile(this.persistencePath, 'utf-8');\n const sessionsArray = JSON.parse(data) as Array<{\n id: string;\n initiator: string;\n task: string;\n agents: string[];\n status: 'active' | 'completed' | 'failed';\n createdAt: string;\n updatedAt: string;\n metadata: Record<string, any>;\n }>;\n\n // Convert date strings back to Date objects\n this.activeSessions.clear();\n let skippedCount = 0;\n\n for (const sessionData of sessionsArray) {\n // Validate session ID before loading (security check)\n try {\n this.validateSessionId(sessionData.id);\n } catch (error) {\n skippedCount++;\n logger.warn('Skipping invalid session ID from persistence', {\n sessionId: sessionData.id,\n error: (error as Error).message\n });\n continue;\n }\n\n // Validate dates (protect against Invalid Date objects)\n const createdAt = new Date(sessionData.createdAt);\n const updatedAt = new Date(sessionData.updatedAt);\n\n if (isNaN(createdAt.getTime()) || isNaN(updatedAt.getTime())) {\n skippedCount++;\n logger.warn('Skipping session with invalid dates from persistence', {\n sessionId: sessionData.id,\n createdAt: sessionData.createdAt,\n updatedAt: sessionData.updatedAt\n });\n continue;\n }\n\n const session: Session = {\n ...sessionData,\n createdAt,\n updatedAt\n };\n this.activeSessions.set(session.id, session);\n }\n\n logger.info('Sessions loaded from persistence', {\n path: this.persistencePath,\n loaded: this.activeSessions.size,\n skipped: skippedCount,\n total: sessionsArray.length\n });\n } catch (error) {\n const err = error as NodeJS.ErrnoException;\n\n // File not found is OK (first time initialization)\n if (err.code === 'ENOENT') {\n logger.debug('No existing sessions file, starting fresh', {\n path: this.persistencePath\n });\n return;\n }\n\n // For other errors (corrupted JSON, permission issues, etc.),\n // backup the corrupted file and start fresh\n try {\n const backupPath = `${this.persistencePath}.corrupted.${Date.now()}`;\n await copyFile(this.persistencePath, backupPath);\n\n logger.error('Corrupted sessions file backed up, starting fresh', {\n path: this.persistencePath,\n backupPath,\n error: err.message\n });\n } catch (backupError) {\n // If backup fails, just log and continue\n logger.error('Failed to backup corrupted sessions file', {\n path: this.persistencePath,\n error: err.message,\n backupError: (backupError as Error).message\n });\n }\n }\n }\n\n /**\n * Save sessions to persistence file (debounced)\n *\n * @private\n */\n private saveToFile(): void {\n if (!this.persistencePath) {\n return;\n }\n\n // Debounce saves to avoid excessive file writes\n if (this.saveTimeout) {\n clearTimeout(this.saveTimeout);\n }\n\n this.saveTimeout = setTimeout(() => {\n this.pendingSave = this.doSave().catch(err => {\n logger.error('Debounced save failed', {\n error: err.message\n });\n // Re-throw to keep promise rejected (so flushSave can detect failures)\n throw err;\n });\n }, 100); // 100ms debounce\n }\n}\n","/**\n * Workspace Manager - Manages agent workspaces and session-based collaboration\n *\n * Provides:\n * - Session-based workspace organization\n * - Agent workspace isolation with controlled sharing\n * - Permission-based access control\n * - Automatic cleanup of old session workspaces\n *\n * @module core/workspace-manager\n * @since v4.7.0\n */\n\nimport { promises as fs } from 'fs';\nimport path from 'path';\nimport type { AgentProfile } from '../types/agent.js';\nimport type { WorkspaceSystemConfig } from '../types/config.js';\nimport { WorkspaceError } from '../types/orchestration.js';\nimport { logger } from '../utils/logger.js';\n\n/**\n * Workspace structure:\n * ```\n * .automatosx/workspaces/\n * ├── shared/\n * │ ├── sessions/<sessionId>/ # Session-specific shared workspace\n * │ │ ├── specs/ # Requirements, designs\n * │ │ └── outputs/\n * │ │ ├── <agentName>/ # Each agent's outputs\n * │ │ └── ...\n * │ └── persistent/ # Cross-session shared files\n * └── <agentName>/ # Agent private workspace\n * ├── drafts/\n * └── temp/\n * ```\n */\n\nexport interface WorkspaceStats {\n /** Total number of session workspaces */\n totalSessions: number;\n\n /** Total disk space used (bytes) */\n totalSizeBytes: number;\n\n /** Number of agent workspaces */\n agentWorkspaces: number;\n}\n\n/**\n * Workspace Manager\n *\n * Manages workspace organization for multi-agent collaboration with:\n * - Session-based isolation (each session gets its own workspace)\n * - Permission-based access control (based on OrchestrationConfig)\n * - Automatic cleanup of old sessions\n *\n * @example\n * ```typescript\n * const workspaceManager = new WorkspaceManager('/path/to/project');\n *\n * // Create session workspace\n * await workspaceManager.createSessionWorkspace('session-123');\n *\n * // Agent writes to session\n * await workspaceManager.writeToSession(\n * 'session-123',\n * 'backend',\n * 'api-spec.md',\n * '# API Specification...'\n * );\n *\n * // Another agent reads from backend's output\n * const spec = await workspaceManager.readFromAgentWorkspace(\n * 'frontend',\n * 'backend',\n * 'session-123',\n * 'api-spec.md'\n * );\n * ```\n */\nexport class WorkspaceManager {\n private readonly workspacesRoot: string;\n private readonly sharedRoot: string;\n private readonly sessionsRoot: string;\n private readonly persistentRoot: string;\n\n /** Maximum file size for writeToSession (from config) */\n private readonly maxFileSize: number;\n\n /** UUID v4 validation regex (static for performance) */\n private static readonly UUID_V4_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n\n /**\n * Create WorkspaceManager\n *\n * @param projectDir - Project directory path\n * @param config - Workspace configuration (optional, defaults to 10MB max file size)\n */\n constructor(projectDir: string, config?: WorkspaceSystemConfig) {\n this.workspacesRoot = path.join(projectDir, '.automatosx', 'workspaces');\n this.sharedRoot = path.join(this.workspacesRoot, 'shared');\n this.sessionsRoot = path.join(this.sharedRoot, 'sessions');\n this.persistentRoot = path.join(this.sharedRoot, 'persistent');\n\n // v5.0: Use config value instead of hardcoded constant\n this.maxFileSize = config?.maxFileSize ?? 10 * 1024 * 1024; // Default: 10 MB\n }\n\n /**\n * Initialize workspace structure\n *\n * Creates all necessary directories for workspace management.\n *\n * @example\n * ```typescript\n * await workspaceManager.initialize();\n * ```\n */\n async initialize(): Promise<void> {\n await fs.mkdir(this.workspacesRoot, { recursive: true });\n await fs.mkdir(this.sharedRoot, { recursive: true });\n await fs.mkdir(this.sessionsRoot, { recursive: true });\n await fs.mkdir(this.persistentRoot, { recursive: true });\n\n logger.debug('Workspace structure initialized', {\n workspacesRoot: this.workspacesRoot\n });\n }\n\n /**\n * Create workspace for a session\n *\n * @param sessionId - Session ID\n * @throws {WorkspaceError} If creation fails\n *\n * @example\n * ```typescript\n * await workspaceManager.createSessionWorkspace('session-123');\n * ```\n */\n async createSessionWorkspace(sessionId: string): Promise<void> {\n const sessionDir = this.getSessionDir(sessionId);\n const specsDir = path.join(sessionDir, 'specs');\n const outputsDir = path.join(sessionDir, 'outputs');\n\n try {\n await fs.mkdir(sessionDir, { recursive: true });\n await fs.mkdir(specsDir, { recursive: true });\n await fs.mkdir(outputsDir, { recursive: true });\n\n logger.info('Session workspace created', {\n sessionId,\n path: sessionDir\n });\n } catch (error) {\n throw new WorkspaceError(\n `Failed to create session workspace: ${(error as Error).message}`,\n sessionDir,\n 'creation_failed'\n );\n }\n }\n\n /**\n * Get agent's output directory within a session\n *\n * @param sessionId - Session ID\n * @param agentName - Agent name\n * @returns Path to agent's output directory\n */\n private getAgentOutputDir(sessionId: string, agentName: string): string {\n return path.join(this.getSessionDir(sessionId), 'outputs', agentName);\n }\n\n /**\n * Validate session ID format (must be valid UUID v4)\n *\n * @param sessionId - Session ID to validate\n * @throws {WorkspaceError} If session ID is invalid\n */\n private validateSessionId(sessionId: string): void {\n // UUID v4 format: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\n // where y is 8, 9, a, or b\n if (!WorkspaceManager.UUID_V4_REGEX.test(sessionId)) {\n throw new WorkspaceError(\n `Invalid session ID format: ${sessionId}. Session IDs must be valid UUID v4.`,\n undefined,\n 'invalid_session_id'\n );\n }\n }\n\n /**\n * Get session directory path\n *\n * @param sessionId - Session ID\n * @returns Session directory path\n */\n private getSessionDir(sessionId: string): string {\n this.validateSessionId(sessionId);\n return path.join(this.sessionsRoot, sessionId);\n }\n\n /**\n * Validate that a file path is safe (prevents path traversal attacks)\n *\n * @param baseDir - Base directory that file must be within\n * @param filePath - Relative file path to validate\n * @returns Resolved absolute path\n * @throws {WorkspaceError} If path is unsafe\n *\n * Security checks:\n * 1. Normalize path to resolve '..' and '.'\n * 2. Resolve to absolute path\n * 3. Verify resolved path is within base directory\n * 4. Prevent symlink attacks by checking real path\n */\n private async validatePath(baseDir: string, filePath: string): Promise<string> {\n // 1. Reject absolute paths immediately\n if (path.isAbsolute(filePath)) {\n throw new WorkspaceError(\n `Absolute paths not allowed: ${filePath}`,\n filePath,\n 'permission_denied'\n );\n }\n\n // 2. Normalize the path (resolves '..' and '.')\n const normalized = path.normalize(filePath);\n\n // 3. Additional check: normalized path shouldn't start with '..'\n if (normalized.startsWith('..')) {\n throw new WorkspaceError(\n `Path traversal detected: ${filePath}`,\n filePath,\n 'permission_denied'\n );\n }\n\n // 4. Resolve to absolute path\n const resolved = path.resolve(baseDir, normalized);\n\n // 5. Verify resolved path is within base directory\n const resolvedBase = path.resolve(baseDir);\n if (!resolved.startsWith(resolvedBase + path.sep) && resolved !== resolvedBase) {\n throw new WorkspaceError(\n `Path outside workspace: ${filePath}`,\n filePath,\n 'permission_denied'\n );\n }\n\n return resolved;\n }\n\n /**\n * Get agent's private workspace directory\n *\n * @param agentName - Agent name\n * @returns Agent workspace path\n */\n private getAgentWorkspaceDir(agentName: string): string {\n return path.join(this.workspacesRoot, agentName);\n }\n\n /**\n * Write file to session workspace (agent's output area)\n *\n * @param sessionId - Session ID\n * @param agentName - Agent writing the file\n * @param filePath - Relative file path within agent's output\n * @param content - File content\n * @param callerAgent - Optional: Agent profile of the caller (for permission verification)\n * @throws {WorkspaceError} If write fails, path is invalid, or permission denied\n *\n * @example\n * ```typescript\n * await workspaceManager.writeToSession(\n * 'session-123',\n * 'backend',\n * 'api/users.ts',\n * 'export interface User { ... }',\n * backendProfile // Verify caller is actually 'backend'\n * );\n * ```\n */\n async writeToSession(\n sessionId: string,\n agentName: string,\n filePath: string,\n content: string,\n callerAgent?: AgentProfile\n ): Promise<void> {\n // Permission check: Verify caller is the agent they claim to be\n if (callerAgent && callerAgent.name !== agentName) {\n throw new WorkspaceError(\n `Agent '${callerAgent.name}' is not authorized to write to '${agentName}' workspace`,\n undefined,\n 'permission_denied'\n );\n }\n\n const agentOutputDir = this.getAgentOutputDir(sessionId, agentName);\n\n // Validate path security (prevents path traversal)\n const fullPath = await this.validatePath(agentOutputDir, filePath);\n\n // Check file size (prevent disk quota exhaustion)\n const fileSize = Buffer.byteLength(content, 'utf-8');\n if (fileSize > this.maxFileSize) {\n throw new WorkspaceError(\n `File too large: ${fileSize} bytes (max: ${this.maxFileSize} bytes)`,\n fullPath,\n 'quota_exceeded'\n );\n }\n\n try {\n // Ensure directory exists\n await fs.mkdir(path.dirname(fullPath), { recursive: true });\n\n // Write file\n await fs.writeFile(fullPath, content, 'utf-8');\n\n logger.debug('File written to session workspace', {\n sessionId,\n agentName,\n filePath,\n size: content.length\n });\n } catch (error) {\n throw new WorkspaceError(\n `Failed to write file: ${(error as Error).message}`,\n fullPath,\n 'permission_denied'\n );\n }\n }\n\n /**\n * Read file from another agent's workspace (within a session)\n *\n * Requires permission check: requestingAgent must have targetAgent\n * in their canReadWorkspaces whitelist.\n *\n * @param requestingAgent - Agent profile requesting access\n * @param targetAgent - Target agent whose workspace to read\n * @param sessionId - Session ID\n * @param filePath - Relative file path within target agent's output\n * @returns File content\n * @throws {WorkspaceError} If permission denied or file not found\n *\n * @example\n * ```typescript\n * const spec = await workspaceManager.readFromAgentWorkspace(\n * frontendProfile,\n * 'backend',\n * 'session-123',\n * 'api-spec.md'\n * );\n * ```\n */\n async readFromAgentWorkspace(\n requestingAgent: AgentProfile,\n targetAgent: string,\n sessionId: string,\n filePath: string\n ): Promise<string> {\n // Permission check\n const canRead = requestingAgent.orchestration?.canReadWorkspaces;\n if (!canRead || !canRead.includes(targetAgent)) {\n throw new WorkspaceError(\n `Agent '${requestingAgent.name}' is not authorized to read '${targetAgent}' workspace`,\n undefined,\n 'permission_denied'\n );\n }\n\n const agentOutputDir = this.getAgentOutputDir(sessionId, targetAgent);\n\n // Validate path security (prevents path traversal)\n const fullPath = await this.validatePath(agentOutputDir, filePath);\n\n try {\n const content = await fs.readFile(fullPath, 'utf-8');\n\n logger.debug('File read from agent workspace', {\n requestingAgent: requestingAgent.name,\n targetAgent,\n sessionId,\n filePath\n });\n\n return content;\n } catch (error) {\n const err = error as NodeJS.ErrnoException;\n if (err.code === 'ENOENT') {\n throw new WorkspaceError(\n `File not found: ${filePath}`,\n fullPath,\n 'not_found'\n );\n }\n throw new WorkspaceError(\n `Failed to read file: ${err.message}`,\n fullPath,\n 'permission_denied'\n );\n }\n }\n\n /**\n * Write to persistent shared workspace (cross-session)\n *\n * Requires permission check: agent must have canWriteToShared enabled.\n *\n * @param agent - Agent profile\n * @param filePath - Relative file path\n * @param content - File content\n * @throws {WorkspaceError} If permission denied or write fails\n *\n * @example\n * ```typescript\n * await workspaceManager.writeToShared(\n * agentProfile,\n * 'templates/api-template.ts',\n * 'export const template = ...'\n * );\n * ```\n */\n async writeToShared(\n agent: AgentProfile,\n filePath: string,\n content: string\n ): Promise<void> {\n // Permission check\n if (!agent.orchestration?.canWriteToShared) {\n throw new WorkspaceError(\n `Agent '${agent.name}' is not authorized to write to shared workspace`,\n undefined,\n 'permission_denied'\n );\n }\n\n // Validate path security (prevents path traversal)\n const fullPath = await this.validatePath(this.persistentRoot, filePath);\n\n // Check file size (prevent disk quota exhaustion)\n const fileSize = Buffer.byteLength(content, 'utf-8');\n if (fileSize > this.maxFileSize) {\n throw new WorkspaceError(\n `File too large: ${fileSize} bytes (max: ${this.maxFileSize} bytes)`,\n fullPath,\n 'quota_exceeded'\n );\n }\n\n try {\n await fs.mkdir(path.dirname(fullPath), { recursive: true });\n await fs.writeFile(fullPath, content, 'utf-8');\n\n logger.info('File written to persistent shared workspace', {\n agentName: agent.name,\n filePath,\n size: fileSize\n });\n } catch (error) {\n throw new WorkspaceError(\n `Failed to write to shared workspace: ${(error as Error).message}`,\n fullPath,\n 'permission_denied'\n );\n }\n }\n\n /**\n * List files in session workspace for a specific agent\n *\n * @param sessionId - Session ID\n * @param agentName - Agent name\n * @returns Array of relative file paths\n * @throws {WorkspaceError} If listing fails\n *\n * @example\n * ```typescript\n * const files = await workspaceManager.listSessionFiles('session-123', 'backend');\n * console.log(files); // ['api-spec.md', 'models/user.ts']\n * ```\n */\n async listSessionFiles(sessionId: string, agentName: string): Promise<string[]> {\n const agentOutputDir = this.getAgentOutputDir(sessionId, agentName);\n\n try {\n const files: string[] = [];\n await this.collectFiles(agentOutputDir, agentOutputDir, files);\n return files;\n } catch (error) {\n const err = error as NodeJS.ErrnoException;\n if (err.code === 'ENOENT') {\n return []; // Directory doesn't exist yet\n }\n throw new WorkspaceError(\n `Failed to list files: ${err.message}`,\n agentOutputDir,\n 'permission_denied'\n );\n }\n }\n\n /**\n * Recursively collect files from a directory\n *\n * @param dir - Directory to scan\n * @param baseDir - Base directory for relative paths\n * @param files - Array to collect file paths\n */\n private async collectFiles(\n dir: string,\n baseDir: string,\n files: string[]\n ): Promise<void> {\n try {\n const entries = await fs.readdir(dir, { withFileTypes: true });\n\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n\n try {\n if (entry.isDirectory()) {\n await this.collectFiles(fullPath, baseDir, files);\n } else {\n const relativePath = path.relative(baseDir, fullPath);\n files.push(relativePath);\n }\n } catch (err) {\n // Skip files/directories that were deleted during traversal\n const error = err as NodeJS.ErrnoException;\n if (error.code === 'ENOENT') {\n logger.debug('File removed during traversal', { path: fullPath });\n continue;\n }\n throw err;\n }\n }\n } catch (err) {\n // If directory is deleted during traversal, just log and return\n const error = err as NodeJS.ErrnoException;\n if (error.code === 'ENOENT') {\n logger.debug('Directory removed during traversal', { path: dir });\n return;\n }\n throw err;\n }\n }\n\n /**\n * Cleanup old session workspaces\n *\n * Removes session workspaces older than specified days.\n * Should be called in sync with SessionManager cleanup.\n *\n * @param sessionIds - Active session IDs to keep\n * @returns Number of sessions cleaned up\n *\n * @example\n * ```typescript\n * const activeSessions = await sessionManager.getActiveSessions();\n * const activeIds = activeSessions.map(s => s.id);\n * const removed = await workspaceManager.cleanupSessions(activeIds);\n * ```\n */\n async cleanupSessions(sessionIds: string[]): Promise<number> {\n try {\n const sessionDirs = await fs.readdir(this.sessionsRoot);\n const activeSet = new Set(sessionIds);\n let removed = 0;\n\n for (const sessionId of sessionDirs) {\n if (!activeSet.has(sessionId)) {\n try {\n const sessionDir = this.getSessionDir(sessionId);\n await fs.rm(sessionDir, { recursive: true, force: true });\n removed++;\n\n logger.debug('Session workspace removed', { sessionId });\n } catch (err) {\n // Skip invalid session directories (non-UUID names)\n if (err instanceof WorkspaceError && err.reason === 'invalid_session_id') {\n logger.warn('Skipping invalid session directory', { sessionId });\n continue;\n }\n throw err;\n }\n }\n }\n\n if (removed > 0) {\n logger.info('Session workspaces cleaned up', { removed });\n }\n\n return removed;\n } catch (error) {\n logger.warn('Failed to cleanup session workspaces', {\n error: (error as Error).message\n });\n return 0;\n }\n }\n\n /**\n * Cleanup specific session workspaces by session IDs\n *\n * Removes workspace directories for the specified session IDs.\n * Useful when coordinating with SessionManager cleanup.\n *\n * @param sessionIds - Session IDs to remove\n * @returns Number of workspaces removed\n *\n * @example\n * ```typescript\n * const result = await sessionManager.cleanupOldSessions(7);\n * await workspaceManager.cleanupSessionWorkspaces(result.removedSessionIds);\n * ```\n */\n async cleanupSessionWorkspaces(sessionIds: string[]): Promise<number> {\n let removed = 0;\n\n for (const sessionId of sessionIds) {\n try {\n const sessionDir = this.getSessionDir(sessionId);\n await fs.rm(sessionDir, { recursive: true, force: true });\n removed++;\n\n logger.debug('Session workspace removed', { sessionId });\n } catch (error) {\n const err = error as NodeJS.ErrnoException;\n // Ignore ENOENT errors (workspace already doesn't exist)\n if (err.code !== 'ENOENT') {\n logger.warn('Failed to remove session workspace', {\n sessionId,\n error: err.message\n });\n }\n }\n }\n\n if (removed > 0) {\n logger.info('Session workspaces cleaned up', {\n removed,\n total: sessionIds.length\n });\n }\n\n return removed;\n }\n\n /**\n * Get workspace statistics\n *\n * @returns Workspace statistics\n *\n * @example\n * ```typescript\n * const stats = await workspaceManager.getStats();\n * console.log(`${stats.totalSessions} session workspaces`);\n * ```\n */\n async getStats(): Promise<WorkspaceStats> {\n try {\n const sessionDirs = await fs.readdir(this.sessionsRoot);\n const agentDirs = await fs.readdir(this.workspacesRoot);\n\n // Count only directories (exclude 'shared')\n const agentWorkspaces = agentDirs.filter(\n name => name !== 'shared'\n ).length;\n\n // Calculate total size (simplified - doesn't traverse all files)\n const stats: WorkspaceStats = {\n totalSessions: sessionDirs.length,\n totalSizeBytes: 0,\n agentWorkspaces\n };\n\n return stats;\n } catch (error) {\n logger.warn('Failed to get workspace stats', {\n error: (error as Error).message\n });\n\n return {\n totalSessions: 0,\n totalSizeBytes: 0,\n agentWorkspaces: 0\n };\n }\n }\n\n /**\n * Create agent's private workspace\n *\n * @param agentName - Agent name\n *\n * @example\n * ```typescript\n * await workspaceManager.createAgentWorkspace('backend');\n * ```\n */\n async createAgentWorkspace(agentName: string): Promise<void> {\n const agentDir = this.getAgentWorkspaceDir(agentName);\n const draftsDir = path.join(agentDir, 'drafts');\n const tempDir = path.join(agentDir, 'temp');\n\n try {\n await fs.mkdir(agentDir, { recursive: true });\n await fs.mkdir(draftsDir, { recursive: true });\n await fs.mkdir(tempDir, { recursive: true });\n\n logger.debug('Agent workspace created', {\n agentName,\n path: agentDir\n });\n } catch (error) {\n throw new WorkspaceError(\n `Failed to create agent workspace: ${(error as Error).message}`,\n agentDir,\n 'creation_failed'\n );\n }\n }\n}\n","/**\n * Team Manager - Load and manage team configurations\n *\n * Teams provide shared configuration for groups of agents:\n * - Provider configuration (which AI providers to use)\n * - Shared abilities (common to all team members)\n * - Orchestration defaults (collaboration settings)\n */\n\nimport { readFile, readdir } from 'fs/promises';\nimport { join, extname, basename } from 'path';\nimport { load } from 'js-yaml';\nimport type { TeamConfig } from '../types/team.js';\nimport { TeamValidationError, TeamNotFoundError } from '../types/team.js';\nimport { logger } from '../utils/logger.js';\nimport { TTLCache } from './cache.js';\n\n/**\n * Team Manager - Load and validate team configurations\n */\nexport class TeamManager {\n private teamsDir: string;\n private cache: TTLCache<TeamConfig>;\n\n constructor(teamsDir: string) {\n this.teamsDir = teamsDir;\n // Use TTLCache with 10 minute TTL for team caching (longer than agents)\n // Teams change less frequently than agent profiles\n this.cache = new TTLCache<TeamConfig>({\n maxEntries: 10, // We only have 4 teams (core, engineering, business, design)\n ttl: 600000, // 10 minutes\n cleanupInterval: 120000, // Cleanup every 2 minutes\n debug: false\n });\n }\n\n /**\n * Load a specific team configuration\n */\n async loadTeam(teamName: string): Promise<TeamConfig> {\n logger.debug('Loading team', { teamName });\n\n // Check cache first\n const cached = this.cache.get(teamName);\n if (cached) {\n logger.debug('Team loaded from cache', { teamName });\n return cached;\n }\n\n try {\n // Load team configuration from YAML\n const teamPath = join(this.teamsDir, `${teamName}.yaml`);\n const content = await readFile(teamPath, 'utf-8');\n const team = load(content) as TeamConfig;\n\n // Validate team configuration\n this.validateTeam(team);\n\n // Cache and return\n this.cache.set(teamName, team);\n logger.info('Team loaded', { name: team.name, path: teamPath });\n\n return team;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n throw new TeamNotFoundError(teamName);\n }\n throw new TeamValidationError(`Failed to load team ${teamName}: ${(error as Error).message}`);\n }\n }\n\n /**\n * Get all available teams\n */\n async getAllTeams(): Promise<TeamConfig[]> {\n logger.debug('Loading all teams');\n\n try {\n const files = await readdir(this.teamsDir);\n const teamFiles = files.filter(f => extname(f) === '.yaml' || extname(f) === '.yml');\n\n const teams: TeamConfig[] = [];\n for (const file of teamFiles) {\n const teamName = basename(file, extname(file));\n try {\n const team = await this.loadTeam(teamName);\n teams.push(team);\n } catch (error) {\n logger.warn('Failed to load team', { file, error: (error as Error).message });\n }\n }\n\n logger.info('All teams loaded', { count: teams.length });\n return teams;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n logger.warn('Teams directory not found', { teamsDir: this.teamsDir });\n return [];\n }\n throw error;\n }\n }\n\n /**\n * List available team names\n */\n async listTeams(): Promise<string[]> {\n try {\n const files = await readdir(this.teamsDir);\n return files\n .filter(f => extname(f) === '.yaml' || extname(f) === '.yml')\n .map(f => basename(f, extname(f)));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return [];\n }\n throw error;\n }\n }\n\n /**\n * Check if a team exists\n */\n async teamExists(teamName: string): Promise<boolean> {\n const teams = await this.listTeams();\n return teams.includes(teamName);\n }\n\n /**\n * Clear cache (useful for testing or after team configuration changes)\n */\n clearCache(): void {\n this.cache.clear();\n logger.debug('Team cache cleared');\n }\n\n /**\n * Validate team configuration\n */\n private validateTeam(team: TeamConfig): void {\n // Required fields\n if (!team.name) {\n throw new TeamValidationError('Team name is required');\n }\n if (!team.displayName) {\n throw new TeamValidationError('Team displayName is required');\n }\n if (!team.description) {\n throw new TeamValidationError('Team description is required');\n }\n\n // Provider configuration is required\n if (!team.provider) {\n throw new TeamValidationError('Team provider configuration is required');\n }\n if (!team.provider.primary) {\n throw new TeamValidationError('Team provider.primary is required');\n }\n\n // Validate provider names (v5.0.7+: accept both aliases and actual names)\n const validProviders = [\n 'claude', 'claude-code', // Claude aliases\n 'gemini', 'gemini-cli', // Gemini aliases\n 'codex', 'openai' // OpenAI aliases\n ];\n\n if (!validProviders.includes(team.provider.primary)) {\n throw new TeamValidationError(\n `Invalid primary provider: ${team.provider.primary}. Must be one of: ${validProviders.join(', ')}`\n );\n }\n\n if (team.provider.fallback && !validProviders.includes(team.provider.fallback)) {\n throw new TeamValidationError(\n `Invalid fallback provider: ${team.provider.fallback}. Must be one of: ${validProviders.join(', ')}`\n );\n }\n\n if (team.provider.fallbackChain) {\n for (const provider of team.provider.fallbackChain) {\n if (!validProviders.includes(provider)) {\n throw new TeamValidationError(\n `Invalid provider in fallbackChain: ${provider}. Must be one of: ${validProviders.join(', ')}`\n );\n }\n }\n }\n\n // Validate arrays if provided\n if (team.sharedAbilities && !Array.isArray(team.sharedAbilities)) {\n throw new TeamValidationError('sharedAbilities must be an array');\n }\n\n if (team.orchestration?.canReadWorkspaces && !Array.isArray(team.orchestration.canReadWorkspaces)) {\n throw new TeamValidationError('orchestration.canReadWorkspaces must be an array');\n }\n\n logger.debug('Team validation passed', { name: team.name });\n }\n}\n","/**\n * Team Configuration Types\n *\n * Defines team-level configuration that agents inherit.\n * Eliminates duplication of provider settings across agent profiles.\n */\n\nimport type { OrchestrationConfig } from './orchestration.js';\n\n/**\n * Team Provider Configuration\n *\n * Defines which AI providers a team uses and in what order.\n */\nexport interface TeamProviderConfig {\n primary: string; // Primary provider (claude, gemini, codex)\n fallback?: string; // Single fallback provider\n fallbackChain?: string[]; // Complete fallback chain (if specified, overrides primary+fallback)\n}\n\n/**\n * Team Orchestration Defaults\n *\n * Default orchestration settings for all agents in the team.\n * Individual agents can override these in their profile.\n */\nexport interface TeamOrchestrationDefaults {\n maxDelegationDepth?: number;\n canWriteToShared?: boolean;\n canReadWorkspaces?: string[];\n}\n\n/**\n * Team Metadata\n *\n * Additional metadata for UI and organizational purposes.\n */\nexport interface TeamMetadata {\n color?: string; // Team color (hex code)\n icon?: string; // Team icon (emoji or string)\n priority?: number; // Team priority (lower = higher priority)\n tags?: string[]; // Team tags\n [key: string]: any; // Additional custom metadata\n}\n\n/**\n * Team Configuration\n *\n * Complete team configuration loaded from .automatosx/teams/*.yaml\n */\nexport interface TeamConfig {\n // Basic info\n name: string;\n displayName: string;\n description: string;\n\n // Provider configuration\n provider: TeamProviderConfig;\n\n // Shared abilities (all team members inherit these)\n sharedAbilities?: string[];\n\n // Orchestration defaults\n orchestration?: TeamOrchestrationDefaults;\n\n // Metadata\n metadata?: TeamMetadata;\n\n // Version tracking\n version?: string;\n}\n\n/**\n * Team validation error\n */\nexport class TeamValidationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'TeamValidationError';\n }\n}\n\n/**\n * Team not found error\n */\nexport class TeamNotFoundError extends Error {\n constructor(teamName: string) {\n super(`Team not found: ${teamName}`);\n this.name = 'TeamNotFoundError';\n }\n}\n","/**\n * ClaudeProvider - Anthropic Claude AI Provider\n *\n * Uses Anthropic SDK for Claude models\n */\n\nimport { BaseProvider } from './base-provider.js';\nimport type {\n ProviderConfig,\n ProviderCapabilities,\n ExecutionRequest,\n ExecutionResponse,\n EmbeddingOptions,\n Cost\n} from '../types/provider.js';\n\nexport class ClaudeProvider extends BaseProvider {\n constructor(config: ProviderConfig) {\n super(config);\n }\n\n get version(): string {\n return '1.0.0';\n }\n\n get capabilities(): ProviderCapabilities {\n return {\n supportsStreaming: false,\n supportsEmbedding: false, // Claude doesn't provide embeddings directly\n supportsVision: true,\n maxContextTokens: 200000,\n supportedModels: [\n 'claude-3-5-sonnet-20241022',\n 'claude-3-5-haiku-20241022',\n 'claude-3-opus-20240229',\n 'claude-3-sonnet-20240229',\n 'claude-3-haiku-20240307'\n ]\n };\n }\n\n protected async executeRequest(request: ExecutionRequest): Promise<ExecutionResponse> {\n // For Phase 1, we use CLI-based execution (Claude Code CLI)\n // In future phases, we'll use the official Anthropic SDK\n\n const startTime = Date.now();\n\n try {\n // Build prompt with system prompt if provided\n let fullPrompt = request.prompt;\n if (request.systemPrompt) {\n fullPrompt = `System: ${request.systemPrompt}\\n\\nUser: ${request.prompt}`;\n }\n\n // Execute via CLI - let CLI use its own default model\n const response = await this.executeCLI(fullPrompt, request);\n\n const latency = Date.now() - startTime;\n\n return {\n content: response.content,\n model: request.model || 'claude-default', // CLI decides actual model\n tokensUsed: {\n prompt: this.estimateTokens(fullPrompt),\n completion: this.estimateTokens(response.content),\n total: this.estimateTokens(fullPrompt) + this.estimateTokens(response.content)\n },\n latencyMs: latency,\n finishReason: 'stop'\n };\n } catch (error) {\n throw new Error(`Claude execution failed: ${(error as Error).message}`);\n }\n }\n\n protected async generateEmbeddingInternal(text: string, options?: EmbeddingOptions): Promise<number[]> {\n throw new Error('Claude does not support embeddings directly. Use OpenAI or Voyage AI for embeddings.');\n }\n\n override async estimateCost(request: ExecutionRequest): Promise<Cost> {\n // Claude pricing (as of 2024)\n const pricing: Record<string, { input: number; output: number }> = {\n 'claude-3-5-sonnet-20241022': { input: 3.00, output: 15.00 }, // per 1M tokens\n 'claude-3-5-haiku-20241022': { input: 0.80, output: 4.00 },\n 'claude-3-opus-20240229': { input: 15.00, output: 75.00 },\n 'claude-3-sonnet-20240229': { input: 3.00, output: 15.00 },\n 'claude-3-haiku-20240307': { input: 0.25, output: 1.25 }\n };\n\n // Use sonnet pricing as default estimate when model not specified\n const defaultPricing = { input: 3.00, output: 15.00 };\n const modelPricing = request.model ? (pricing[request.model] ?? defaultPricing) : defaultPricing;\n\n const inputTokens = this.estimateTokens(request.prompt);\n const outputTokens = request.maxTokens ?? 4096;\n\n const inputCost = (inputTokens / 1_000_000) * modelPricing.input;\n const outputCost = (outputTokens / 1_000_000) * modelPricing.output;\n\n return {\n estimatedUsd: inputCost + outputCost,\n tokensUsed: inputTokens + outputTokens\n };\n }\n\n // CLI execution helper (Phase 1 implementation)\n private async executeCLI(prompt: string, request: ExecutionRequest): Promise<{ content: string }> {\n // Check if running in production mode (real CLI) or test mode (mock)\n const useMock = process.env.AUTOMATOSX_MOCK_PROVIDERS === 'true';\n\n if (useMock) {\n // Mock mode for testing\n return Promise.resolve({\n content: `[Mock Response from Claude]\\n\\nTask received: ${prompt.substring(0, 100)}...\\n\\nThis is a placeholder response. Set AUTOMATOSX_MOCK_PROVIDERS=false to use real CLI.`\n });\n }\n\n // Real CLI execution\n return this.executeRealCLI(prompt, request);\n }\n\n /**\n * Execute real CLI command via spawn\n *\n * Claude Code CLI syntax: claude -p \"prompt\"\n * Uses --print flag for non-interactive output\n * Model selection is delegated to CLI's own defaults\n */\n private async executeRealCLI(prompt: string, request: ExecutionRequest): Promise<{ content: string }> {\n const { spawn } = await import('child_process');\n\n return new Promise((resolve, reject) => {\n let stdout = '';\n let stderr = '';\n let hasTimedOut = false;\n\n // Build CLI arguments using the new buildCLIArgs method\n const args = this.buildCLIArgs(request);\n\n // Add prompt as last argument\n args.push(prompt);\n\n let child: ReturnType<typeof spawn>;\n\n try {\n child = spawn(this.config.command, args, {\n stdio: ['ignore', 'pipe', 'pipe'],\n env: process.env\n });\n } catch (error) {\n const err = error as NodeJS.ErrnoException;\n if (err.code === 'ENOENT') {\n reject(new Error(\n `Claude CLI not found. Please ensure Claude Code is installed and '${this.config.command}' is in your PATH.\\n` +\n `Install from: https://claude.ai/download`\n ));\n } else {\n reject(new Error(`Failed to start Claude CLI: ${err.message}`));\n }\n return;\n }\n\n // v5.0.7: Handle abort signal for proper timeout cancellation\n if (request.signal) {\n request.signal.addEventListener('abort', () => {\n hasTimedOut = true;\n child.kill('SIGTERM');\n // Force kill after 5 seconds if SIGTERM doesn't work\n setTimeout(() => {\n if (!child.killed) {\n child.kill('SIGKILL');\n }\n }, 5000);\n reject(new Error('Execution aborted by timeout'));\n });\n }\n\n // Collect stdout\n child.stdout?.on('data', (data) => {\n stdout += data.toString();\n });\n\n // Collect stderr\n child.stderr?.on('data', (data) => {\n stderr += data.toString();\n });\n\n // Handle process exit\n child.on('close', (code) => {\n if (hasTimedOut) {\n return; // Timeout already handled\n }\n\n if (code !== 0) {\n const errorMsg = stderr || 'No error message';\n\n // Parse common error patterns\n if (errorMsg.toLowerCase().includes('network') ||\n errorMsg.toLowerCase().includes('connection') ||\n errorMsg.toLowerCase().includes('econnrefused') ||\n errorMsg.toLowerCase().includes('enotfound')) {\n reject(new Error(\n `Network connection error: Unable to reach Claude API.\\n` +\n `Please check your internet connection and try again.\\n` +\n `Details: ${errorMsg}`\n ));\n } else if (errorMsg.toLowerCase().includes('authentication') ||\n errorMsg.toLowerCase().includes('unauthorized') ||\n errorMsg.toLowerCase().includes('api key')) {\n reject(new Error(\n `Authentication failed: Please check your Claude API credentials.\\n` +\n `Details: ${errorMsg}`\n ));\n } else if (errorMsg.toLowerCase().includes('rate limit') ||\n errorMsg.toLowerCase().includes('quota')) {\n reject(new Error(\n `Rate limit exceeded: Please wait a moment and try again.\\n` +\n `Details: ${errorMsg}`\n ));\n } else {\n reject(new Error(`Claude CLI exited with code ${code}: ${errorMsg}`));\n }\n } else {\n if (!stdout.trim()) {\n reject(new Error('Claude CLI returned empty response'));\n } else {\n resolve({ content: stdout.trim() });\n }\n }\n });\n\n // Handle process errors\n child.on('error', (error) => {\n const err = error as NodeJS.ErrnoException;\n\n if (err.code === 'ENOENT') {\n reject(new Error(\n `Claude CLI command '${this.config.command}' not found.\\n` +\n `Please install Claude Code from https://claude.ai/download`\n ));\n } else if (err.code === 'EACCES') {\n reject(new Error(\n `Permission denied: Cannot execute '${this.config.command}'.\\n` +\n `Please check file permissions.`\n ));\n } else {\n reject(new Error(`Failed to execute Claude CLI: ${err.message}`));\n }\n });\n\n // Set timeout\n const timeout = setTimeout(() => {\n hasTimedOut = true;\n child.kill('SIGTERM');\n\n // Force kill after 5 seconds if still running\n setTimeout(() => {\n if (child.killed === false) {\n child.kill('SIGKILL');\n }\n }, 5000);\n\n reject(new Error(\n `Request timeout after ${this.config.timeout / 1000} seconds.\\n` +\n `This may be due to:\\n` +\n `- Slow network connection\\n` +\n `- Large request requiring more processing time\\n` +\n `- Claude API being overloaded\\n` +\n `Try again or use --timeout option to increase the limit.`\n ));\n }, this.config.timeout);\n\n child.on('close', () => {\n clearTimeout(timeout);\n });\n });\n }\n\n override shouldRetry(error: Error): boolean {\n // Claude-specific retry logic\n const claudeRetryableErrors = [\n 'overloaded_error',\n 'rate_limit_error',\n 'timeout',\n 'connection_error',\n 'internal_server_error',\n 'network connection error',\n 'econnrefused',\n 'econnreset',\n 'etimedout',\n 'enotfound'\n ];\n\n const message = error.message.toLowerCase();\n const isRetryable = claudeRetryableErrors.some(err => message.includes(err)) || super.shouldRetry(error);\n\n // Don't retry authentication errors or missing CLI\n if (message.includes('authentication') ||\n message.includes('api key') ||\n message.includes('not found') ||\n message.includes('permission denied')) {\n return false;\n }\n\n return isRetryable;\n }\n\n /**\n * Build CLI arguments for Claude Code CLI\n * Currently does not support parameter passing via CLI\n * Claude Code uses its own optimal defaults\n */\n protected buildCLIArgs(request: ExecutionRequest): string[] {\n // Claude Code CLI uses --print for non-interactive output\n const args: string[] = ['--print'];\n\n // Enable file operation tools (v5.0.6 fix)\n // Allow Read, Write, Edit, and Bash tools for agent operations\n args.push('--allowedTools', 'Read Write Edit Bash Glob Grep');\n\n // Allow access to current working directory and tmp folder\n args.push('--add-dir', process.cwd());\n\n // Claude Code CLI does not support parameter configuration via CLI flags\n // It uses provider-optimized defaults for best results\n //\n // Future implementation (if Claude adds support):\n // if (request.temperature !== undefined) {\n // args.push('--temperature', String(request.temperature));\n // }\n // if (request.maxTokens !== undefined) {\n // args.push('--max-tokens', String(request.maxTokens));\n // }\n\n return args;\n }\n\n /**\n * Check if Claude provider supports a specific parameter\n * Currently all parameters are unsupported via CLI\n */\n protected supportsParameter(\n param: 'maxTokens' | 'temperature' | 'topP'\n ): boolean {\n // Claude Code CLI does not support parameter configuration\n // Uses provider-optimized defaults instead\n return false;\n }\n}\n","/**\n * BaseProvider - Abstract base class for all AI providers\n *\n * Provides common functionality:\n * - Rate limiting with token bucket algorithm\n * - Exponential backoff retry logic\n * - Health monitoring and circuit breaker\n * - Cost tracking and estimation\n * - Error categorization\n */\n\nimport type {\n Provider,\n ProviderConfig,\n ProviderCapabilities,\n ExecutionRequest,\n ExecutionResponse,\n HealthStatus,\n RateLimitStatus,\n Cost,\n UsageStats,\n EmbeddingOptions,\n RetryConfig\n} from '../types/provider.js';\nimport { logger } from '../utils/logger.js';\nimport { ProviderResponseCache } from '../core/cache.js';\n\nexport abstract class BaseProvider implements Provider {\n protected config: ProviderConfig;\n protected health: HealthStatus;\n protected usageStats: UsageStats;\n protected rateLimitState: {\n requests: number[]; // timestamps of recent requests\n tokens: number[]; // token usage with timestamps\n concurrentRequests: number;\n };\n protected responseCache: ProviderResponseCache;\n\n constructor(config: ProviderConfig) {\n this.config = config;\n this.health = {\n available: true,\n latencyMs: 0,\n errorRate: 0,\n consecutiveFailures: 0\n };\n this.usageStats = {\n totalRequests: 0,\n totalTokens: 0,\n totalCost: 0,\n averageLatencyMs: 0,\n errorCount: 0\n };\n this.rateLimitState = {\n requests: [],\n tokens: [],\n concurrentRequests: 0\n };\n // Initialize response cache with 5 minute TTL\n this.responseCache = new ProviderResponseCache({\n maxEntries: 100,\n ttl: 300000, // 5 minutes\n maxSize: 10 * 1024 * 1024, // 10MB\n debug: false\n });\n }\n\n // Abstract methods to be implemented by concrete providers\n abstract get version(): string;\n abstract get capabilities(): ProviderCapabilities;\n\n // Name and priority from config\n get name(): string {\n return this.config.name;\n }\n\n get priority(): number {\n return this.config.priority;\n }\n\n protected abstract executeRequest(request: ExecutionRequest): Promise<ExecutionResponse>;\n protected abstract generateEmbeddingInternal(text: string, options?: EmbeddingOptions): Promise<number[]>;\n\n /**\n * Build CLI arguments for execution\n * @param request Execution request containing parameters\n * @returns Array of CLI arguments\n */\n protected abstract buildCLIArgs(request: ExecutionRequest): string[];\n\n /**\n * Check if provider supports a specific parameter\n * @param param Parameter name to check\n * @returns true if parameter is supported\n */\n protected abstract supportsParameter(\n param: 'maxTokens' | 'temperature' | 'topP'\n ): boolean;\n\n // Health & Availability\n async isAvailable(): Promise<boolean> {\n if (!this.config.enabled || !this.health.available) {\n return false;\n }\n\n // Check if CLI command actually exists\n return this.checkCLIAvailability();\n }\n\n /**\n * Check if the CLI command is available in the system\n */\n private async checkCLIAvailability(): Promise<boolean> {\n try {\n const { spawn } = await import('child_process');\n\n return new Promise<boolean>((resolve) => {\n // Try to spawn the command with --version or --help\n const child = spawn(this.config.command, ['--version'], {\n stdio: 'ignore',\n timeout: 5000\n });\n\n let resolved = false;\n\n child.on('close', (code) => {\n if (!resolved) {\n resolved = true;\n // Consider success if exit code is 0 or 1 (some CLIs return 1 for --version)\n resolve(code === 0 || code === 1);\n }\n });\n\n child.on('error', (error: NodeJS.ErrnoException) => {\n if (!resolved) {\n resolved = true;\n // ENOENT means command not found\n if (error.code === 'ENOENT') {\n logger.warn(`CLI command not found: ${this.config.command}`);\n resolve(false);\n } else {\n // Other errors might be temporary\n resolve(true);\n }\n }\n });\n\n // Timeout fallback\n setTimeout(() => {\n if (!resolved) {\n resolved = true;\n child.kill();\n resolve(false);\n }\n }, 5000);\n });\n } catch (error) {\n logger.error(`Error checking CLI availability: ${(error as Error).message}`);\n return false;\n }\n }\n\n async getHealth(): Promise<HealthStatus> {\n return { ...this.health };\n }\n\n // Execution with retry logic\n async execute(request: ExecutionRequest): Promise<ExecutionResponse> {\n if (!await this.isAvailable()) {\n throw new Error(`Provider ${this.name} is not available`);\n }\n\n // Check rate limits\n await this.waitForCapacity();\n\n // Check cache before executing\n const messages = this.requestToMessages(request);\n const cacheOptions = {\n temperature: request.temperature,\n maxTokens: request.maxTokens\n };\n const cached = this.responseCache.get(\n this.name,\n request.model || 'default',\n messages,\n cacheOptions\n );\n\n if (cached) {\n logger.debug('Provider cache hit', {\n provider: this.name,\n model: request.model\n });\n\n // Return cached response (reconstruct ExecutionResponse)\n return {\n content: cached.response,\n model: request.model || 'default',\n tokensUsed: cached.usage || {\n prompt: this.estimateTokens(request.prompt),\n completion: this.estimateTokens(cached.response),\n total: this.estimateTokens(request.prompt) + this.estimateTokens(cached.response)\n },\n latencyMs: 0, // Cached response has no latency\n finishReason: 'stop'\n };\n }\n\n const retryPolicy = this.config.retryPolicy ?? this.getDefaultRetryPolicy();\n let lastError: Error | undefined;\n\n for (let attempt = 1; attempt <= retryPolicy.maxAttempts; attempt++) {\n try {\n // Track concurrent requests\n this.rateLimitState.concurrentRequests++;\n const startTime = Date.now();\n\n const response = await this.executeWithTimeout(request);\n\n // Update metrics\n const latency = Date.now() - startTime;\n this.updateMetrics(response, latency);\n this.health.consecutiveFailures = 0;\n\n // Cache successful response\n this.responseCache.set(\n this.name,\n request.model || 'default',\n messages,\n response.content,\n cacheOptions,\n response.tokensUsed\n );\n\n return response;\n\n } catch (error) {\n lastError = error as Error;\n this.health.consecutiveFailures++;\n this.usageStats.errorCount++;\n\n logger.error(`Provider ${this.name} execution failed (attempt ${attempt})`, {\n error: lastError.message,\n attempt,\n maxAttempts: retryPolicy.maxAttempts\n });\n\n // Check if we should retry\n if (attempt < retryPolicy.maxAttempts && this.shouldRetry(lastError)) {\n const delay = this.getRetryDelay(attempt);\n logger.info(`Retrying after ${delay}ms...`);\n await this.sleep(delay);\n } else {\n break;\n }\n } finally {\n this.rateLimitState.concurrentRequests--;\n }\n }\n\n // All retries failed\n this.updateHealthAfterFailure();\n throw lastError || new Error('Execution failed');\n }\n\n // Embeddings\n async generateEmbedding(text: string, options?: EmbeddingOptions): Promise<number[]> {\n if (!this.capabilities.supportsEmbedding) {\n throw new Error(`Provider ${this.name} does not support embeddings`);\n }\n\n return this.generateEmbeddingInternal(text, options);\n }\n\n // Rate Limiting - Token Bucket Algorithm\n async checkRateLimit(): Promise<RateLimitStatus> {\n const now = Date.now();\n const oneMinuteAgo = now - 60000;\n\n // Clean old entries\n this.rateLimitState.requests = this.rateLimitState.requests.filter(t => t > oneMinuteAgo);\n this.rateLimitState.tokens = this.rateLimitState.tokens.filter(t => t > oneMinuteAgo);\n\n const limits = this.config.rateLimits;\n if (!limits) {\n return {\n hasCapacity: true,\n requestsRemaining: Infinity,\n tokensRemaining: Infinity,\n resetAtMs: now + 60000\n };\n }\n\n const requestsRemaining = limits.maxRequestsPerMinute - this.rateLimitState.requests.length;\n const tokensRemaining = limits.maxTokensPerMinute - this.rateLimitState.tokens.length;\n const concurrentOk = this.rateLimitState.concurrentRequests < limits.maxConcurrentRequests;\n\n return {\n hasCapacity: requestsRemaining > 0 && tokensRemaining > 0 && concurrentOk,\n requestsRemaining,\n tokensRemaining,\n resetAtMs: now + 60000\n };\n }\n\n async waitForCapacity(): Promise<void> {\n const maxWaitMs = 60000; // 1 minute max wait\n const startTime = Date.now();\n\n while (Date.now() - startTime < maxWaitMs) {\n const status = await this.checkRateLimit();\n\n if (status.hasCapacity) {\n // Reserve capacity\n this.rateLimitState.requests.push(Date.now());\n return;\n }\n\n // Wait until reset time\n const waitMs = Math.min(status.resetAtMs - Date.now(), 1000);\n await this.sleep(waitMs);\n }\n\n throw new Error(`Rate limit exceeded for provider ${this.name}`);\n }\n\n // Cost Management (to be overridden by providers with specific pricing)\n async estimateCost(request: ExecutionRequest): Promise<Cost> {\n // Default implementation - providers should override with actual pricing\n const estimatedTokens = this.estimateTokens(request.prompt);\n return {\n estimatedUsd: 0,\n tokensUsed: estimatedTokens\n };\n }\n\n async getUsageStats(): Promise<UsageStats> {\n return { ...this.usageStats };\n }\n\n // Error Handling\n shouldRetry(error: Error): boolean {\n // Default: retry on network errors, rate limits, timeouts\n const retryableErrors = [\n 'ECONNRESET',\n 'ETIMEDOUT',\n 'ENOTFOUND',\n 'rate_limit',\n 'timeout'\n ];\n\n return retryableErrors.some(msg =>\n error.message.toLowerCase().includes(msg.toLowerCase())\n );\n }\n\n getRetryDelay(attempt: number): number {\n const policy = this.config.retryPolicy ?? this.getDefaultRetryPolicy();\n const delay = policy.initialDelayMs * Math.pow(policy.backoffMultiplier, attempt - 1);\n return Math.min(delay, policy.maxDelayMs);\n }\n\n // Protected helper methods\n protected async executeWithTimeout(request: ExecutionRequest): Promise<ExecutionResponse> {\n const timeout = this.config.timeout;\n\n return Promise.race([\n this.executeRequest(request),\n this.createTimeoutPromise(timeout)\n ]);\n }\n\n protected createTimeoutPromise(timeoutMs: number): Promise<never> {\n return new Promise((_, reject) => {\n setTimeout(() => reject(new Error(`Request timeout after ${timeoutMs}ms`)), timeoutMs);\n });\n }\n\n protected updateMetrics(response: ExecutionResponse, latency: number): void {\n this.usageStats.totalRequests++;\n this.usageStats.totalTokens += response.tokensUsed.total;\n\n // Update average latency (running average)\n const totalLatency = this.usageStats.averageLatencyMs * (this.usageStats.totalRequests - 1);\n this.usageStats.averageLatencyMs = (totalLatency + latency) / this.usageStats.totalRequests;\n\n // Update health\n this.health.latencyMs = latency;\n this.health.errorRate = this.usageStats.errorCount / this.usageStats.totalRequests;\n\n // Track tokens for rate limiting\n for (let i = 0; i < response.tokensUsed.total; i++) {\n this.rateLimitState.tokens.push(Date.now());\n }\n }\n\n protected updateHealthAfterFailure(): void {\n // Circuit breaker: disable provider after too many consecutive failures\n if (this.health.consecutiveFailures >= 5) {\n this.health.available = false;\n logger.error(`Provider ${this.name} circuit breaker triggered (5 consecutive failures)`);\n\n // Auto-recover after 60 seconds\n setTimeout(() => {\n this.health.available = true;\n this.health.consecutiveFailures = 0;\n logger.info(`Provider ${this.name} circuit breaker reset`);\n }, 60000);\n }\n }\n\n protected estimateTokens(text: string): number {\n // Rough estimate: ~4 characters per token\n return Math.ceil(text.length / 4);\n }\n\n protected sleep(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n }\n\n /**\n * Convert ExecutionRequest to messages array for cache key generation\n */\n protected requestToMessages(request: ExecutionRequest): any[] {\n const messages: any[] = [];\n\n // Add system message if present\n if (request.systemPrompt) {\n messages.push({\n role: 'system',\n content: request.systemPrompt\n });\n }\n\n // Add user message\n messages.push({\n role: 'user',\n content: request.prompt\n });\n\n // Include context if present\n if (request.context && Object.keys(request.context).length > 0) {\n messages.push({\n role: 'context',\n content: request.context\n });\n }\n\n return messages;\n }\n\n protected getDefaultRetryPolicy(): RetryConfig {\n return {\n maxAttempts: 3,\n initialDelayMs: 1000,\n maxDelayMs: 10000,\n backoffMultiplier: 2\n };\n }\n}\n","/**\n * GeminiProvider - Google Gemini AI Provider\n *\n * Uses Google Generative AI SDK for Gemini models\n */\n\nimport { BaseProvider } from './base-provider.js';\nimport type {\n ProviderConfig,\n ProviderCapabilities,\n ExecutionRequest,\n ExecutionResponse,\n EmbeddingOptions,\n Cost\n} from '../types/provider.js';\n\nexport class GeminiProvider extends BaseProvider {\n constructor(config: ProviderConfig) {\n super(config);\n }\n\n get version(): string {\n return '1.0.0';\n }\n\n get capabilities(): ProviderCapabilities {\n return {\n supportsStreaming: false,\n supportsEmbedding: true,\n supportsVision: true,\n maxContextTokens: 1000000, // Gemini 1.5 Pro has 1M context window\n supportedModels: [\n 'gemini-2.0-flash-exp',\n 'gemini-1.5-pro',\n 'gemini-1.5-flash',\n 'gemini-1.0-pro'\n ]\n };\n }\n\n protected async executeRequest(request: ExecutionRequest): Promise<ExecutionResponse> {\n const startTime = Date.now();\n\n try {\n // Build prompt with system prompt if provided\n let fullPrompt = request.prompt;\n if (request.systemPrompt) {\n fullPrompt = `${request.systemPrompt}\\n\\n${request.prompt}`;\n }\n\n // Execute via CLI - let CLI use its own default model\n const response = await this.executeCLI(fullPrompt, request);\n\n const latency = Date.now() - startTime;\n\n return {\n content: response.content,\n model: request.model || 'gemini-default', // CLI decides actual model\n tokensUsed: {\n prompt: this.estimateTokens(fullPrompt),\n completion: this.estimateTokens(response.content),\n total: this.estimateTokens(fullPrompt) + this.estimateTokens(response.content)\n },\n latencyMs: latency,\n finishReason: 'stop'\n };\n } catch (error) {\n throw new Error(`Gemini execution failed: ${(error as Error).message}`);\n }\n }\n\n protected async generateEmbeddingInternal(text: string, options?: EmbeddingOptions): Promise<number[]> {\n // Gemini supports embeddings via embedding-001 model\n const model = options?.model || 'embedding-001';\n\n try {\n // TODO: Implement actual embedding generation with Google AI SDK\n // For now, return mock embedding\n const dimensions = options?.dimensions || 768;\n return Array(dimensions).fill(0).map(() => Math.random());\n } catch (error) {\n throw new Error(`Gemini embedding generation failed: ${(error as Error).message}`);\n }\n }\n\n override async estimateCost(request: ExecutionRequest): Promise<Cost> {\n // Gemini pricing (as of 2024)\n const pricing: Record<string, { input: number; output: number }> = {\n 'gemini-2.0-flash-exp': { input: 0, output: 0 }, // Free during preview\n 'gemini-1.5-pro': { input: 3.50, output: 10.50 }, // per 1M tokens\n 'gemini-1.5-flash': { input: 0.35, output: 1.05 },\n 'gemini-1.0-pro': { input: 0.50, output: 1.50 }\n };\n\n // Use gemini-2.0-flash-exp pricing as default estimate when model not specified\n const defaultPricing = { input: 0, output: 0 };\n const modelPricing = request.model ? (pricing[request.model] ?? defaultPricing) : defaultPricing;\n\n const inputTokens = this.estimateTokens(request.prompt);\n const outputTokens = request.maxTokens ?? 4096;\n\n const inputCost = (inputTokens / 1_000_000) * modelPricing.input;\n const outputCost = (outputTokens / 1_000_000) * modelPricing.output;\n\n return {\n estimatedUsd: inputCost + outputCost,\n tokensUsed: inputTokens + outputTokens\n };\n }\n\n // CLI execution helper (Phase 1 implementation)\n private async executeCLI(prompt: string, request: ExecutionRequest): Promise<{ content: string }> {\n // Check if running in production mode (real CLI) or test mode (mock)\n const useMock = process.env.AUTOMATOSX_MOCK_PROVIDERS === 'true';\n\n if (useMock) {\n // Mock mode for testing\n return Promise.resolve({\n content: `[Mock Response from Gemini]\\n\\nTask received: ${prompt.substring(0, 100)}...\\n\\nThis is a placeholder response. Set AUTOMATOSX_MOCK_PROVIDERS=false to use real CLI.`\n });\n }\n\n // Real CLI execution\n return this.executeRealCLI(prompt, request);\n }\n\n /**\n * Execute real CLI command via spawn\n *\n * Gemini CLI syntax: gemini \"prompt\"\n * Model selection is delegated to CLI's own defaults\n */\n private async executeRealCLI(prompt: string, request: ExecutionRequest): Promise<{ content: string }> {\n const { spawn } = await import('child_process');\n\n return new Promise((resolve, reject) => {\n let stdout = '';\n let stderr = '';\n let hasTimedOut = false;\n\n // Build CLI arguments for Gemini CLI\n // Note: Gemini CLI uses positional prompt, not --prompt flag\n // Do NOT pass --model - let CLI use its own default\n const args: string[] = [];\n\n // Enable file operation tools (v5.0.6 fix)\n // This allows agents to create, modify, and delete files\n args.push('--approval-mode', 'auto_edit');\n\n // Add prompt as positional argument (not as flag)\n args.push(prompt);\n\n // Note: Gemini CLI doesn't support temperature and maxTokens via CLI flags\n // These parameters are configured in the Gemini settings.json instead\n\n // Spawn the CLI process\n const child = spawn(this.config.command, args, {\n stdio: ['pipe', 'pipe', 'pipe'],\n env: process.env\n });\n\n // v5.0.7: Handle abort signal for proper timeout cancellation\n if (request.signal) {\n request.signal.addEventListener('abort', () => {\n hasTimedOut = true;\n child.kill('SIGTERM');\n // Force kill after 5 seconds if SIGTERM doesn't work\n setTimeout(() => {\n if (!child.killed) {\n child.kill('SIGKILL');\n }\n }, 5000);\n reject(new Error('Execution aborted by timeout'));\n });\n }\n\n // Collect stdout\n child.stdout?.on('data', (data) => {\n stdout += data.toString();\n });\n\n // Collect stderr\n child.stderr?.on('data', (data) => {\n stderr += data.toString();\n });\n\n // Handle process exit\n child.on('close', (code) => {\n if (hasTimedOut) {\n return; // Timeout already handled\n }\n if (code !== 0) {\n reject(new Error(`Gemini CLI exited with code ${code}: ${stderr}`));\n } else {\n resolve({ content: stdout.trim() });\n }\n });\n\n // Handle process errors\n child.on('error', (error) => {\n reject(new Error(`Failed to spawn Gemini CLI: ${error.message}`));\n });\n\n // Set timeout\n const timeout = setTimeout(() => {\n child.kill('SIGTERM');\n reject(new Error('Gemini CLI execution timeout'));\n }, this.config.timeout);\n\n child.on('close', () => {\n clearTimeout(timeout);\n });\n });\n }\n\n override shouldRetry(error: Error): boolean {\n // Gemini-specific retry logic\n const geminiRetryableErrors = [\n 'resource_exhausted',\n 'unavailable',\n 'deadline_exceeded',\n 'internal',\n 'rate_limit'\n ];\n\n const message = error.message.toLowerCase();\n return geminiRetryableErrors.some(err => message.includes(err)) || super.shouldRetry(error);\n }\n\n /**\n * Build CLI arguments for Gemini CLI\n * Currently does not support parameter passing via CLI\n * TODO: Implement when Gemini CLI adds support (Issue #5280)\n */\n protected buildCLIArgs(request: ExecutionRequest): string[] {\n const args: string[] = [];\n\n // Gemini CLI currently does not support parameter passing\n // Parameters would need to be configured in ~/.gemini/settings.json\n //\n // Future implementation (when Gemini CLI adds support):\n // if (request.temperature !== undefined) {\n // args.push('--temperature', String(request.temperature));\n // }\n // if (request.maxTokens !== undefined) {\n // args.push('--max-tokens', String(request.maxTokens));\n // }\n // if (request.topP !== undefined) {\n // args.push('--top-p', String(request.topP));\n // }\n\n return args;\n }\n\n /**\n * Check if Gemini provider supports a specific parameter\n * Currently all parameters are unsupported\n * See: https://github.com/google-gemini/gemini-cli/issues/5280\n */\n protected supportsParameter(\n param: 'maxTokens' | 'temperature' | 'topP'\n ): boolean {\n // Gemini CLI does not support any parameters yet\n // This will return true once Issue #5280 is resolved\n return false;\n }\n}\n","/**\n * OpenAIProvider - OpenAI AI Provider\n *\n * Uses OpenAI API for GPT models\n */\n\nimport { BaseProvider } from './base-provider.js';\nimport type {\n ProviderConfig,\n ProviderCapabilities,\n ExecutionRequest,\n ExecutionResponse,\n EmbeddingOptions,\n Cost\n} from '../types/provider.js';\n\nexport class OpenAIProvider extends BaseProvider {\n constructor(config: ProviderConfig) {\n super(config);\n }\n\n get version(): string {\n return '1.0.0';\n }\n\n get capabilities(): ProviderCapabilities {\n return {\n supportsStreaming: false,\n supportsEmbedding: true,\n supportsVision: true,\n maxContextTokens: 128000, // GPT-4 Turbo/GPT-4o has 128k context\n supportedModels: [\n 'gpt-4o',\n 'gpt-4o-mini',\n 'gpt-4-turbo',\n 'gpt-4',\n 'gpt-3.5-turbo',\n 'o1-preview',\n 'o1-mini'\n ]\n };\n }\n\n protected async executeRequest(request: ExecutionRequest): Promise<ExecutionResponse> {\n const startTime = Date.now();\n\n try {\n // Build prompt with system prompt if provided\n let fullPrompt = request.prompt;\n if (request.systemPrompt) {\n fullPrompt = `System: ${request.systemPrompt}\\n\\nUser: ${request.prompt}`;\n }\n\n // Execute via CLI - let CLI use its own default model\n const response = await this.executeCLI(fullPrompt, request);\n\n const latency = Date.now() - startTime;\n\n return {\n content: response.content,\n model: request.model || 'openai-default', // CLI decides actual model\n tokensUsed: {\n prompt: this.estimateTokens(fullPrompt),\n completion: this.estimateTokens(response.content),\n total: this.estimateTokens(fullPrompt) + this.estimateTokens(response.content)\n },\n latencyMs: latency,\n finishReason: 'stop'\n };\n } catch (error) {\n throw new Error(`OpenAI execution failed: ${(error as Error).message}`);\n }\n }\n\n protected async generateEmbeddingInternal(text: string, options?: EmbeddingOptions): Promise<number[]> {\n // OpenAI supports embeddings via text-embedding models\n const model = options?.model || 'text-embedding-3-small';\n\n try {\n // TODO: Implement actual embedding generation with OpenAI SDK\n // For now, return mock embedding\n const dimensions = options?.dimensions || 1536;\n return Array(dimensions).fill(0).map(() => Math.random());\n } catch (error) {\n throw new Error(`OpenAI embedding generation failed: ${(error as Error).message}`);\n }\n }\n\n override async estimateCost(request: ExecutionRequest): Promise<Cost> {\n // OpenAI pricing (as of 2024)\n const pricing: Record<string, { input: number; output: number }> = {\n 'gpt-4o': { input: 2.50, output: 10.00 }, // per 1M tokens\n 'gpt-4o-mini': { input: 0.15, output: 0.60 },\n 'gpt-4-turbo': { input: 10.00, output: 30.00 },\n 'gpt-4': { input: 30.00, output: 60.00 },\n 'gpt-3.5-turbo': { input: 0.50, output: 1.50 },\n 'o1-preview': { input: 15.00, output: 60.00 },\n 'o1-mini': { input: 3.00, output: 12.00 }\n };\n\n // Use gpt-4o pricing as default estimate when model not specified\n const defaultPricing = { input: 2.50, output: 10.00 };\n const modelPricing = request.model ? (pricing[request.model] ?? defaultPricing) : defaultPricing;\n\n const inputTokens = this.estimateTokens(request.prompt);\n const outputTokens = request.maxTokens ?? 4096;\n\n const inputCost = (inputTokens / 1_000_000) * modelPricing.input;\n const outputCost = (outputTokens / 1_000_000) * modelPricing.output;\n\n return {\n estimatedUsd: inputCost + outputCost,\n tokensUsed: inputTokens + outputTokens\n };\n }\n\n // CLI execution helper (Phase 1 implementation)\n private async executeCLI(prompt: string, request: ExecutionRequest): Promise<{ content: string }> {\n // Check if running in production mode (real CLI) or test mode (mock)\n const useMock = process.env.AUTOMATOSX_MOCK_PROVIDERS === 'true';\n\n if (useMock) {\n // Mock mode for testing\n return Promise.resolve({\n content: `[Mock Response from OpenAI]\\n\\nTask received: ${prompt.substring(0, 100)}...\\n\\nThis is a placeholder response. Set AUTOMATOSX_MOCK_PROVIDERS=false to use real CLI.`\n });\n }\n\n // Real CLI execution\n return this.executeRealCLI(prompt, request);\n }\n\n /**\n * Execute real CLI command via spawn\n *\n * Codex CLI syntax: codex exec [OPTIONS] [PROMPT]\n * Model and other parameters are passed via -c (config override) or specific flags\n */\n private async executeRealCLI(prompt: string, request: ExecutionRequest): Promise<{ content: string }> {\n const { spawn } = await import('child_process');\n\n return new Promise((resolve, reject) => {\n let stdout = '';\n let stderr = '';\n let hasTimedOut = false;\n\n // Build CLI arguments using the new buildCLIArgs method\n const args = this.buildCLIArgs(request);\n\n // Add prompt as last argument\n args.push(prompt);\n\n // Spawn the CLI process\n const child = spawn(this.config.command, args, {\n stdio: ['pipe', 'pipe', 'pipe'],\n env: process.env\n });\n\n // v5.0.7: Handle abort signal for proper timeout cancellation\n if (request.signal) {\n request.signal.addEventListener('abort', () => {\n hasTimedOut = true;\n child.kill('SIGTERM');\n // Force kill after 5 seconds if SIGTERM doesn't work\n setTimeout(() => {\n if (!child.killed) {\n child.kill('SIGKILL');\n }\n }, 5000);\n reject(new Error('Execution aborted by timeout'));\n });\n }\n\n // Collect stdout\n child.stdout?.on('data', (data) => {\n stdout += data.toString();\n });\n\n // Collect stderr\n child.stderr?.on('data', (data) => {\n stderr += data.toString();\n });\n\n // Handle process exit\n child.on('close', (code) => {\n if (hasTimedOut) {\n return; // Already rejected by timeout\n }\n\n if (code !== 0) {\n reject(new Error(`OpenAI CLI exited with code ${code}: ${stderr}`));\n } else {\n resolve({ content: stdout.trim() });\n }\n });\n\n // Handle process errors\n child.on('error', (error) => {\n if (!hasTimedOut) {\n reject(new Error(`Failed to spawn OpenAI CLI: ${error.message}`));\n }\n });\n\n // Set timeout\n const timeout = setTimeout(() => {\n hasTimedOut = true;\n child.kill('SIGTERM');\n\n // Give it a moment to terminate gracefully\n setTimeout(() => {\n if (!child.killed) {\n child.kill('SIGKILL');\n }\n }, 1000);\n\n reject(new Error(`OpenAI CLI execution timeout after ${this.config.timeout}ms`));\n }, this.config.timeout);\n\n child.on('close', () => {\n clearTimeout(timeout);\n });\n });\n }\n\n override shouldRetry(error: Error): boolean {\n // OpenAI-specific retry logic\n const openaiRetryableErrors = [\n 'rate_limit',\n 'server_error',\n 'timeout',\n 'connection_error',\n 'service_unavailable',\n 'internal_error'\n ];\n\n const message = error.message.toLowerCase();\n return openaiRetryableErrors.some(err => message.includes(err)) || super.shouldRetry(error);\n }\n\n /**\n * Build CLI arguments for OpenAI Codex CLI\n * Supports: maxTokens, temperature\n */\n protected buildCLIArgs(request: ExecutionRequest): string[] {\n const args: string[] = ['exec'];\n\n // Add model if specified\n if (request.model) {\n args.push('-m', request.model);\n }\n\n // Add temperature via config override if specified\n if (request.temperature !== undefined) {\n args.push('-c', `temperature=${request.temperature}`);\n }\n\n // Add max tokens via config override if specified\n if (request.maxTokens !== undefined) {\n args.push('-c', `max_tokens=${request.maxTokens}`);\n }\n\n return args;\n }\n\n /**\n * Check if OpenAI provider supports a specific parameter\n * OpenAI Codex CLI supports maxTokens and temperature via -c flags\n */\n protected supportsParameter(\n param: 'maxTokens' | 'temperature' | 'topP'\n ): boolean {\n // OpenAI Codex CLI supports maxTokens and temperature\n return param === 'maxTokens' || param === 'temperature';\n }\n}\n","/**\n * Output Formatter - Format execution results in different formats\n */\n\nimport chalk from 'chalk';\nimport type { ExecutionResult } from '../agents/executor.js';\n\nexport type OutputFormat = 'text' | 'json' | 'markdown';\n\n/**\n * Format execution result based on output format\n */\nexport function formatOutput(\n result: ExecutionResult,\n format: OutputFormat,\n verbose: boolean = false\n): string {\n switch (format) {\n case 'json':\n return formatAsJson(result);\n\n case 'markdown':\n return formatAsMarkdown(result, verbose);\n\n case 'text':\n default:\n return formatAsText(result, verbose);\n }\n}\n\n/**\n * Format as JSON\n */\nfunction formatAsJson(result: ExecutionResult): string {\n return JSON.stringify({\n content: result.response.content,\n tokensUsed: result.response.tokensUsed,\n latencyMs: result.response.latencyMs,\n model: result.response.model,\n finishReason: result.response.finishReason\n }, null, 2);\n}\n\n/**\n * Format as Markdown\n */\nfunction formatAsMarkdown(result: ExecutionResult, verbose: boolean): string {\n const md: string[] = [\n `# Execution Result\\n`,\n `**Model**: ${result.response.model}`,\n `**Latency**: ${result.response.latencyMs}ms`,\n `**Tokens**: ${result.response.tokensUsed?.total || 'N/A'}\\n`,\n `## Response\\n`,\n result.response.content,\n `\\n`\n ];\n\n if (verbose && result.response.tokensUsed) {\n md.push(`## Token Usage\\n`);\n md.push(`- Prompt: ${result.response.tokensUsed.prompt || 'N/A'}`);\n md.push(`- Completion: ${result.response.tokensUsed.completion || 'N/A'}`);\n md.push(`- Total: ${result.response.tokensUsed.total || 'N/A'}\\n`);\n }\n\n return md.join('\\n');\n}\n\n/**\n * Format as plain text\n */\nfunction formatAsText(result: ExecutionResult, verbose: boolean): string {\n const output: string[] = [];\n\n if (!verbose) {\n output.push(chalk.cyan('\\n📝 Result:\\n'));\n output.push(result.response.content);\n output.push('\\n');\n }\n\n if (verbose) {\n output.push(chalk.gray(`\\nModel: ${result.response.model}`));\n output.push(chalk.gray(`Latency: ${result.response.latencyMs}ms`));\n if (result.response.tokensUsed) {\n output.push(chalk.gray(`Tokens: ${result.response.tokensUsed.total || 'N/A'}`));\n }\n }\n\n return output.join('\\n');\n}\n\n/**\n * Format for file save (includes metadata)\n */\nexport function formatForSave(\n result: ExecutionResult,\n format: OutputFormat,\n metadata: {\n agent: string;\n task: string;\n timestamp?: string;\n }\n): string {\n if (format === 'json') {\n return JSON.stringify({\n agent: metadata.agent,\n task: metadata.task,\n timestamp: metadata.timestamp || new Date().toISOString(),\n result: {\n content: result.response.content,\n tokensUsed: result.response.tokensUsed,\n latencyMs: result.response.latencyMs,\n model: result.response.model,\n finishReason: result.response.finishReason\n }\n }, null, 2);\n }\n\n // For text and markdown, just return the formatted output\n return formatOutput(result, format, true);\n}\n","/**\n * Session Command - Manage multi-agent collaborative sessions\n *\n * @since v4.7.0\n */\n\nimport type { CommandModule, Argv } from 'yargs';\nimport { createSessionManager } from '../utils/session-utils.js';\nimport chalk from 'chalk';\nimport Table from 'cli-table3';\n\ninterface SessionCreateOptions {\n task: string;\n initiator: string;\n}\n\ninterface SessionListOptions {\n agent?: string;\n status?: 'active' | 'completed' | 'failed';\n json?: boolean;\n}\n\ninterface SessionStatusOptions {\n id: string;\n json?: boolean;\n}\n\ninterface SessionCompleteOptions {\n id: string;\n}\n\ninterface SessionFailOptions {\n id: string;\n}\n\n/**\n * Session Create Command\n */\nconst createCommand: CommandModule<Record<string, unknown>, SessionCreateOptions> = {\n command: 'create <task> <initiator>',\n describe: 'Create a new multi-agent session',\n\n builder: (yargs: Argv<Record<string, unknown>>): Argv<SessionCreateOptions> => {\n return yargs\n .positional('task', {\n describe: 'Overall task/goal for the session',\n type: 'string',\n demandOption: true\n })\n .positional('initiator', {\n describe: 'Agent that initiates the session',\n type: 'string',\n demandOption: true\n }) as Argv<SessionCreateOptions>;\n },\n\n handler: async (argv) => {\n try {\n const sessionManager = await createSessionManager();\n\n const session = await sessionManager.createSession(argv.task, argv.initiator);\n\n console.log(chalk.green.bold('\\n✓ Session created successfully\\n'));\n console.log(chalk.gray(`Session ID: ${chalk.white(session.id)}`));\n console.log(chalk.gray(`Task: ${chalk.white(session.task)}`));\n console.log(chalk.gray(`Initiator: ${chalk.white(session.initiator)}`));\n console.log(chalk.gray(`Status: ${chalk.white(session.status)}`));\n console.log(chalk.gray(`Created: ${chalk.white(session.createdAt.toISOString())}`));\n console.log();\n\n process.exit(0);\n } catch (error) {\n console.error(chalk.red.bold('\\n✗ Failed to create session\\n'));\n console.error(chalk.red((error as Error).message));\n process.exit(1);\n }\n }\n};\n\n/**\n * Session List Command\n */\nconst listCommand: CommandModule<Record<string, unknown>, SessionListOptions> = {\n command: 'list',\n describe: 'List all sessions',\n\n builder: (yargs) => {\n return yargs\n .option('agent', {\n describe: 'Filter by agent name',\n type: 'string'\n })\n .option('status', {\n describe: 'Filter by status',\n type: 'string',\n choices: ['active', 'completed', 'failed']\n })\n .option('json', {\n describe: 'Output as JSON',\n type: 'boolean',\n default: false\n });\n },\n\n handler: async (argv) => {\n try {\n const sessionManager = await createSessionManager();\n\n let sessions = argv.agent\n ? await sessionManager.getActiveSessionsForAgent(argv.agent)\n : await sessionManager.getActiveSessions();\n\n // Filter by status if specified\n if (argv.status) {\n sessions = sessions.filter(s => s.status === argv.status);\n }\n\n if (argv.json) {\n console.log(JSON.stringify(sessions, null, 2));\n process.exit(0);\n }\n\n if (sessions.length === 0) {\n console.log(chalk.yellow('\\nNo sessions found\\n'));\n process.exit(0);\n }\n\n console.log(chalk.blue.bold(`\\n📋 Sessions (${sessions.length})\\n`));\n\n const table = new Table({\n head: ['ID', 'Task', 'Initiator', 'Agents', 'Status', 'Created'],\n colWidths: [38, 40, 15, 25, 12, 12]\n });\n\n sessions.forEach(session => {\n table.push([\n session.id.substring(0, 8) + '...',\n session.task.substring(0, 37) + (session.task.length > 37 ? '...' : ''),\n session.initiator,\n session.agents.join(', ').substring(0, 22),\n session.status,\n new Date(session.createdAt).toLocaleDateString()\n ]);\n });\n\n console.log(table.toString());\n console.log();\n\n process.exit(0);\n } catch (error) {\n console.error(chalk.red.bold('\\n✗ Failed to list sessions\\n'));\n console.error(chalk.red((error as Error).message));\n process.exit(1);\n }\n }\n};\n\n/**\n * Session Status Command\n */\nconst statusCommand: CommandModule<Record<string, unknown>, SessionStatusOptions> = {\n command: 'status <id>',\n describe: 'Show session status',\n\n builder: (yargs: Argv<Record<string, unknown>>): Argv<SessionStatusOptions> => {\n return yargs\n .positional('id', {\n describe: 'Session ID',\n type: 'string',\n demandOption: true\n })\n .option('json', {\n describe: 'Output as JSON',\n type: 'boolean',\n default: false\n }) as Argv<SessionStatusOptions>;\n },\n\n handler: async (argv) => {\n try {\n const sessionManager = await createSessionManager();\n const session = await sessionManager.getSession(argv.id);\n\n if (!session) {\n console.log(chalk.red.bold(`\\n✗ Session not found: ${argv.id}\\n`));\n process.exit(1);\n }\n\n if (argv.json) {\n console.log(JSON.stringify(session, null, 2));\n process.exit(0);\n }\n\n console.log(chalk.blue.bold('\\n📊 Session Status\\n'));\n console.log(chalk.gray(`ID: ${chalk.white(session.id)}`));\n console.log(chalk.gray(`Task: ${chalk.white(session.task)}`));\n console.log(chalk.gray(`Initiator: ${chalk.white(session.initiator)}`));\n console.log(chalk.gray(`Status: ${chalk.white(session.status)}`));\n console.log(chalk.gray(`Agents: ${chalk.white(session.agents.join(', '))}`));\n console.log(chalk.gray(`Created: ${chalk.white(session.createdAt.toISOString())}`));\n console.log(chalk.gray(`Updated: ${chalk.white(session.updatedAt.toISOString())}`));\n\n if (session.metadata && Object.keys(session.metadata).length > 0) {\n console.log(chalk.gray(`\\nMetadata:`));\n Object.entries(session.metadata).forEach(([key, value]) => {\n console.log(chalk.gray(` ${key}: ${JSON.stringify(value)}`));\n });\n }\n\n console.log();\n process.exit(0);\n } catch (error) {\n console.error(chalk.red.bold('\\n✗ Failed to get session status\\n'));\n console.error(chalk.red((error as Error).message));\n process.exit(1);\n }\n }\n};\n\n/**\n * Session Complete Command\n */\nconst completeCommand: CommandModule<Record<string, unknown>, SessionCompleteOptions> = {\n command: 'complete <id>',\n describe: 'Mark session as completed',\n\n builder: (yargs) => {\n return yargs.positional('id', {\n describe: 'Session ID',\n type: 'string',\n demandOption: true\n });\n },\n\n handler: async (argv) => {\n try {\n const sessionManager = await createSessionManager();\n await sessionManager.completeSession(argv.id);\n\n console.log(chalk.green.bold(`\\n✓ Session marked as completed: ${argv.id}\\n`));\n process.exit(0);\n } catch (error) {\n console.error(chalk.red.bold('\\n✗ Failed to complete session\\n'));\n console.error(chalk.red((error as Error).message));\n process.exit(1);\n }\n }\n};\n\n/**\n * Session Fail Command\n */\nconst failCommand: CommandModule<Record<string, unknown>, SessionFailOptions> = {\n command: 'fail <id>',\n describe: 'Mark session as failed',\n\n builder: (yargs) => {\n return yargs.positional('id', {\n describe: 'Session ID',\n type: 'string',\n demandOption: true\n });\n },\n\n handler: async (argv) => {\n try {\n const sessionManager = await createSessionManager();\n await sessionManager.failSession(argv.id, new Error('Manually marked as failed'));\n\n console.log(chalk.yellow.bold(`\\n⚠ Session marked as failed: ${argv.id}\\n`));\n process.exit(0);\n } catch (error) {\n console.error(chalk.red.bold('\\n✗ Failed to mark session as failed\\n'));\n console.error(chalk.red((error as Error).message));\n process.exit(1);\n }\n }\n};\n\n/**\n * Main Session Command\n */\nexport const sessionCommand: CommandModule = {\n command: 'session <command>',\n describe: 'Manage multi-agent collaborative sessions',\n\n builder: (yargs) => {\n return yargs\n .command(createCommand)\n .command(listCommand)\n .command(statusCommand)\n .command(completeCommand)\n .command(failCommand)\n .demandCommand(1, 'You must specify a session command')\n .help();\n },\n\n handler: () => {\n // Parent command handler (not used, subcommands handle everything)\n }\n};\n","/**\n * Session Utils - Shared utilities for session management in CLI commands\n *\n * @module cli/utils/session-utils\n * @since v4.7.0\n */\n\nimport { SessionManager } from '../../core/session-manager.js';\nimport { PathResolver } from '../../core/path-resolver.js';\nimport { join } from 'path';\n\n/**\n * Create SessionManager instance with persistence\n *\n * Detects project root and initializes SessionManager with persistence file.\n * This is the standard way to create SessionManager in CLI commands.\n *\n * @returns Initialized SessionManager instance\n * @throws {Error} If project root cannot be detected or initialization fails\n *\n * @example\n * ```typescript\n * try {\n * const sessionManager = await createSessionManager();\n * const session = await sessionManager.createSession('Task', 'agent');\n * } catch (error) {\n * console.error('Failed to initialize session manager:', error.message);\n * process.exit(1);\n * }\n * ```\n */\nexport async function createSessionManager(): Promise<SessionManager> {\n try {\n const projectDir = await new PathResolver({\n projectDir: process.cwd(),\n workingDir: process.cwd(),\n agentWorkspace: join(process.cwd(), '.automatosx', 'workspaces')\n }).detectProjectRoot();\n\n const sessionManager = new SessionManager({\n persistencePath: join(projectDir, '.automatosx', 'sessions', 'sessions.json')\n });\n\n await sessionManager.initialize();\n return sessionManager;\n } catch (error) {\n const err = error as Error;\n throw new Error(\n `Failed to initialize SessionManager: ${err.message}\\n` +\n `Make sure you're in an AutomatosX project directory or run 'automatosx init' first.`\n );\n }\n}\n","/**\n * Status Command - Display system status and health\n *\n * Shows comprehensive system information including:\n * - Project and configuration info\n * - Directory structure and existence\n * - Provider availability and health\n * - Workspace statistics\n * - Memory system status\n */\n\nimport type { CommandModule } from 'yargs';\nimport { Router } from '../../core/router.js';\nimport { PathResolver } from '../../core/path-resolver.js';\nimport { ClaudeProvider } from '../../providers/claude-provider.js';\nimport { GeminiProvider } from '../../providers/gemini-provider.js';\nimport { OpenAIProvider } from '../../providers/openai-provider.js';\nimport { loadConfig } from '../../core/config.js';\nimport { logger } from '../../utils/logger.js';\nimport chalk from 'chalk';\nimport { existsSync, statSync } from 'fs';\nimport { readdir, stat } from 'fs/promises';\nimport { join, basename } from 'path';\nimport { createRequire } from 'module';\nimport os from 'os';\nimport { printError } from '../../utils/error-formatter.js';\n\n// Read version from version.json (single source of truth)\nconst require = createRequire(import.meta.url);\nlet VERSION = 'unknown';\ntry {\n // Try to load from same directory first (when built to dist/)\n const versionData = require('../version.json');\n VERSION = versionData.version || 'unknown';\n} catch (err) {\n // Fallback: try parent directory\n try {\n const versionData = require('../../version.json');\n VERSION = versionData.version || 'unknown';\n } catch (err2) {\n // Fallback: try grandparent directory (development mode from src/cli/commands/)\n try {\n const versionData = require('../../../version.json');\n VERSION = versionData.version || 'unknown';\n } catch (err3) {\n // Final fallback: package.json\n try {\n const packageJson = require('../../../package.json');\n VERSION = packageJson.version || 'unknown';\n } catch (err4) {\n logger.debug('Version file not found, using fallback');\n }\n }\n }\n}\n\ninterface StatusOptions {\n verbose?: boolean;\n json?: boolean;\n}\n\nexport const statusCommand: CommandModule<Record<string, unknown>, StatusOptions> = {\n command: 'status',\n describe: 'Display system status and health',\n\n builder: (yargs) => {\n return yargs\n .option('verbose', {\n describe: 'Verbose output with detailed statistics',\n type: 'boolean',\n default: false\n })\n .option('json', {\n describe: 'Output as JSON',\n type: 'boolean',\n default: false\n });\n },\n\n handler: async (argv) => {\n try {\n const startTime = Date.now();\n const config = await loadConfig(process.cwd());\n const projectDir = process.cwd();\n\n // Initialize path resolver\n const pathResolver = new PathResolver({\n projectDir,\n workingDir: process.cwd(),\n agentWorkspace: join(projectDir, '.automatosx', 'workspaces')\n });\n\n // Detect project root\n const detectedProjectDir = await pathResolver.detectProjectRoot();\n\n // Check directories\n const automatosxDir = join(detectedProjectDir, '.automatosx');\n const agentsDir = join(automatosxDir, 'agents');\n const abilitiesDir = join(automatosxDir, 'abilities');\n const memoryDir = join(automatosxDir, 'memory');\n const workspacesDir = join(automatosxDir, 'workspaces');\n\n // Initialize providers\n const providers = [];\n\n if (config.providers['claude-code']?.enabled) {\n providers.push(new ClaudeProvider({\n name: 'claude-code',\n enabled: true,\n priority: config.providers['claude-code'].priority,\n timeout: config.providers['claude-code'].timeout,\n command: config.providers['claude-code'].command\n }));\n }\n\n if (config.providers['gemini-cli']?.enabled) {\n providers.push(new GeminiProvider({\n name: 'gemini-cli',\n enabled: true,\n priority: config.providers['gemini-cli'].priority,\n timeout: config.providers['gemini-cli'].timeout,\n command: config.providers['gemini-cli'].command\n }));\n }\n\n if (config.providers['openai']?.enabled) {\n providers.push(new OpenAIProvider({\n name: 'openai',\n enabled: true,\n priority: config.providers['openai'].priority,\n timeout: config.providers['openai'].timeout,\n command: config.providers['openai'].command\n }));\n }\n\n const router = new Router({\n providers,\n fallbackEnabled: true\n });\n\n // Get provider health\n const availableProviders = await router.getAvailableProviders();\n const providerHealth = await Promise.all(\n providers.map(async (p) => ({\n name: p.name,\n available: await p.isAvailable(),\n health: await p.getHealth(),\n priority: p.priority\n }))\n );\n\n // Collect workspace statistics\n const workspaceStats = await getWorkspaceStatistics(workspacesDir);\n\n // Collect memory statistics\n const memoryStats = await getMemoryStatistics(memoryDir);\n\n // Collect agent and ability counts\n const agentCount = await countFiles(agentsDir, ['.yaml', '.yml']);\n const abilityCount = await countFiles(abilitiesDir, ['.md']);\n\n // Get project info\n const projectInfo = await getProjectInfo(detectedProjectDir);\n\n // Build status object\n const status = {\n system: {\n version: VERSION,\n nodeVersion: process.version,\n platform: `${os.platform()} ${os.arch()}`,\n uptime: Math.floor(process.uptime()),\n projectDir: detectedProjectDir,\n workingDir: process.cwd()\n },\n project: projectInfo,\n configuration: {\n configFile: join(detectedProjectDir, 'automatosx.config.json'),\n configExists: existsSync(join(detectedProjectDir, 'automatosx.config.json')),\n logLevel: config.logging.level,\n memoryMaxEntries: config.memory.maxEntries,\n memoryRetentionDays: config.memory.cleanupDays\n },\n directories: {\n automatosx: { path: automatosxDir, exists: existsSync(automatosxDir) },\n agents: { path: agentsDir, exists: existsSync(agentsDir), count: agentCount },\n abilities: { path: abilitiesDir, exists: existsSync(abilitiesDir), count: abilityCount },\n memory: { path: memoryDir, exists: existsSync(memoryDir), ...memoryStats },\n workspaces: { path: workspacesDir, exists: existsSync(workspacesDir), ...workspaceStats }\n },\n providers: providerHealth,\n router: {\n totalProviders: providers.length,\n availableProviders: availableProviders.length,\n fallbackEnabled: true\n },\n performance: {\n statusCheckMs: Date.now() - startTime\n }\n };\n\n // Output\n if (argv.json) {\n console.log(JSON.stringify(status, null, 2));\n } else {\n console.log(chalk.blue.bold('\\n📊 AutomatosX Status\\n'));\n\n // System\n console.log(chalk.cyan('System:'));\n console.log(` Version: ${chalk.white(status.system.version)}`);\n console.log(` Node: ${chalk.white(status.system.nodeVersion)}`);\n console.log(` Platform: ${chalk.white(status.system.platform)}`);\n if (argv.verbose) {\n console.log(` Process Uptime: ${chalk.white(formatUptime(status.system.uptime))}`);\n }\n console.log();\n\n // Project Info\n if (status.project.name || argv.verbose) {\n console.log(chalk.cyan('Project:'));\n if (status.project.name) {\n console.log(` Name: ${chalk.white(status.project.name)}`);\n }\n if (status.project.type) {\n console.log(` Type: ${chalk.white(status.project.type)}`);\n }\n console.log(` Directory: ${chalk.white(status.system.projectDir)}`);\n if (status.system.workingDir !== status.system.projectDir) {\n console.log(` Working Dir: ${chalk.white(status.system.workingDir)}`);\n }\n console.log();\n }\n\n // Configuration\n console.log(chalk.cyan('Configuration:'));\n const configIcon = status.configuration.configExists ? chalk.green('✓') : chalk.yellow('⚠');\n const configText = status.configuration.configExists ? 'found' : 'using defaults';\n console.log(` ${configIcon} Config: ${configText}`);\n if (argv.verbose && status.configuration.configExists) {\n console.log(chalk.gray(` ${status.configuration.configFile}`));\n }\n console.log(` Log Level: ${chalk.white(status.configuration.logLevel)}`);\n console.log(` Memory Limit: ${chalk.white(status.configuration.memoryMaxEntries.toLocaleString())} entries`);\n console.log(` Retention: ${chalk.white(status.configuration.memoryRetentionDays)} days`);\n console.log();\n\n // Directories\n console.log(chalk.cyan('Resources:'));\n for (const [name, dir] of Object.entries(status.directories)) {\n const statusIcon = dir.exists ? chalk.green('✓') : chalk.red('✗');\n\n let info = '';\n if (name === 'agents' && 'count' in dir) {\n const agentDir = dir as { count: number };\n info = ` (${agentDir.count} ${agentDir.count === 1 ? 'agent' : 'agents'})`;\n } else if (name === 'abilities' && 'count' in dir) {\n const abilityDir = dir as { count: number };\n info = ` (${abilityDir.count} ${abilityDir.count === 1 ? 'ability' : 'abilities'})`;\n } else if (name === 'memory' && 'files' in dir) {\n const memDir = dir as { files: number; sizeBytes: number };\n info = ` (${memDir.files} ${memDir.files === 1 ? 'file' : 'files'}, ${formatBytes(memDir.sizeBytes || 0)})`;\n } else if (name === 'workspaces' && 'workspaces' in dir) {\n const wsDir = dir as { workspaces: number; totalSizeBytes: number };\n info = ` (${wsDir.workspaces} ${wsDir.workspaces === 1 ? 'workspace' : 'workspaces'}, ${formatBytes(wsDir.totalSizeBytes || 0)})`;\n }\n\n console.log(` ${statusIcon} ${name}${info}`);\n if (argv.verbose) {\n console.log(chalk.gray(` ${dir.path}`));\n }\n }\n console.log();\n\n // Providers\n console.log(chalk.cyan('Providers:'));\n for (const provider of status.providers) {\n const statusIcon = provider.available ? chalk.green('✓') : chalk.red('✗');\n const statusText = provider.available ? chalk.green('available') : chalk.red('unavailable');\n console.log(` ${statusIcon} ${provider.name}: ${statusText} (priority: ${provider.priority})`);\n\n if (argv.verbose) {\n console.log(chalk.gray(` Failures: ${provider.health.consecutiveFailures}`));\n console.log(chalk.gray(` Latency: ${provider.health.latencyMs}ms`));\n console.log(chalk.gray(` Error rate: ${(provider.health.errorRate * 100).toFixed(2)}%`));\n }\n }\n console.log();\n\n // Router\n console.log(chalk.cyan('Router:'));\n console.log(` Total providers: ${chalk.white(status.router.totalProviders)}`);\n console.log(` Available: ${chalk.white(status.router.availableProviders)}`);\n console.log(` Fallback: ${chalk.white(status.router.fallbackEnabled ? 'enabled' : 'disabled')}`);\n console.log();\n\n // Performance (verbose only)\n if (argv.verbose) {\n console.log(chalk.cyan('Performance:'));\n console.log(` Status check: ${chalk.white(status.performance.statusCheckMs)}ms`);\n console.log();\n }\n\n // Overall status\n const allDirsExist = Object.values(status.directories).every(d => d.exists);\n const hasAvailableProviders = status.router.availableProviders > 0;\n const isHealthy = allDirsExist && hasAvailableProviders;\n\n if (isHealthy) {\n console.log(chalk.green.bold('✅ System is healthy\\n'));\n } else {\n console.log(chalk.yellow.bold('⚠️ System has issues\\n'));\n if (!allDirsExist) {\n console.log(chalk.yellow(' Some directories are missing. Run `automatosx init` to initialize.'));\n }\n if (!hasAvailableProviders) {\n console.log(chalk.yellow(' No providers available. Check provider configuration.'));\n }\n console.log();\n }\n }\n\n } catch (error) {\n printError(error, {\n verbose: argv.verbose,\n showCode: true,\n showSuggestions: true,\n colors: true\n });\n logger.error('Status check failed', { error: (error as Error).message });\n process.exit(1);\n }\n }\n};\n\n/**\n * Helper Functions\n */\n\n/**\n * Get workspace statistics\n */\nasync function getWorkspaceStatistics(workspacesDir: string): Promise<{\n workspaces: number;\n totalSizeBytes: number;\n files: number;\n}> {\n if (!existsSync(workspacesDir)) {\n return { workspaces: 0, totalSizeBytes: 0, files: 0 };\n }\n\n try {\n const entries = await readdir(workspacesDir, { withFileTypes: true });\n const workspaces = entries.filter(e => e.isDirectory());\n\n let totalSizeBytes = 0;\n let files = 0;\n\n for (const workspace of workspaces) {\n const workspacePath = join(workspacesDir, workspace.name);\n const stats = await getDirectoryStats(workspacePath);\n totalSizeBytes += stats.size;\n files += stats.files;\n }\n\n return {\n workspaces: workspaces.length,\n totalSizeBytes,\n files\n };\n } catch (error) {\n logger.warn('Failed to get workspace statistics', { error: (error as Error).message });\n return { workspaces: 0, totalSizeBytes: 0, files: 0 };\n }\n}\n\n/**\n * Get memory statistics\n */\nasync function getMemoryStatistics(memoryDir: string): Promise<{\n files: number;\n sizeBytes: number;\n}> {\n if (!existsSync(memoryDir)) {\n return { files: 0, sizeBytes: 0 };\n }\n\n try {\n const stats = await getDirectoryStats(memoryDir);\n return {\n files: stats.files,\n sizeBytes: stats.size\n };\n } catch (error) {\n logger.warn('Failed to get memory statistics', { error: (error as Error).message });\n return { files: 0, sizeBytes: 0 };\n }\n}\n\n/**\n * Get directory statistics recursively\n */\nasync function getDirectoryStats(dirPath: string): Promise<{ size: number; files: number }> {\n let totalSize = 0;\n let totalFiles = 0;\n\n try {\n const entries = await readdir(dirPath, { withFileTypes: true });\n\n for (const entry of entries) {\n const fullPath = join(dirPath, entry.name);\n\n if (entry.isDirectory()) {\n const subStats = await getDirectoryStats(fullPath);\n totalSize += subStats.size;\n totalFiles += subStats.files;\n } else if (entry.isFile()) {\n const stats = await stat(fullPath);\n totalSize += stats.size;\n totalFiles++;\n }\n }\n } catch (error) {\n // Silently ignore errors (permission denied, etc.)\n }\n\n return { size: totalSize, files: totalFiles };\n}\n\n/**\n * Count files with specific extensions in a directory\n */\nasync function countFiles(dirPath: string, extensions: string[]): Promise<number> {\n if (!existsSync(dirPath)) {\n return 0;\n }\n\n try {\n const files = await readdir(dirPath);\n return files.filter(f => extensions.some(ext => f.endsWith(ext))).length;\n } catch (error) {\n logger.warn('Failed to count files', { dirPath, error: (error as Error).message });\n return 0;\n }\n}\n\n/**\n * Get project information from package.json\n */\nasync function getProjectInfo(projectDir: string): Promise<{\n name?: string;\n version?: string;\n type?: string;\n}> {\n const packageJsonPath = join(projectDir, 'package.json');\n\n if (!existsSync(packageJsonPath)) {\n return {};\n }\n\n try {\n const { readFile } = await import('fs/promises');\n const content = await readFile(packageJsonPath, 'utf-8');\n const pkg = JSON.parse(content);\n\n return {\n name: pkg.name,\n version: pkg.version,\n type: pkg.type || 'commonjs'\n };\n } catch (error) {\n logger.warn('Failed to read package.json', { error: (error as Error).message });\n return {};\n }\n}\n\n/**\n * Format bytes to human-readable string\n */\nfunction formatBytes(bytes: number): string {\n if (bytes === 0) return '0 B';\n\n const k = 1024;\n const sizes = ['B', 'KB', 'MB', 'GB'];\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n\n return `${(bytes / Math.pow(k, i)).toFixed(1)} ${sizes[i]}`;\n}\n\n/**\n * Format uptime to human-readable string\n */\nfunction formatUptime(seconds: number): string {\n const hours = Math.floor(seconds / 3600);\n const minutes = Math.floor((seconds % 3600) / 60);\n const secs = seconds % 60;\n\n const parts = [];\n if (hours > 0) parts.push(`${hours}h`);\n if (minutes > 0) parts.push(`${minutes}m`);\n if (secs > 0 || parts.length === 0) parts.push(`${secs}s`);\n\n return parts.join(' ');\n}\n","/**\n * Update Command - Check for updates and upgrade AutomatosX\n */\n\nimport type { CommandModule } from 'yargs';\nimport { exec } from 'child_process';\nimport { promisify } from 'util';\nimport chalk from 'chalk';\nimport { logger } from '../../utils/logger.js';\nimport { printError } from '../../utils/error-formatter.js';\n\nconst execAsync = promisify(exec);\n\ninterface UpdateOptions {\n check?: boolean;\n yes?: boolean;\n}\n\nexport const updateCommand: CommandModule<Record<string, unknown>, UpdateOptions> = {\n command: 'update',\n describe: 'Check for updates and upgrade AutomatosX to the latest version',\n\n builder: (yargs) => {\n return yargs\n .option('check', {\n describe: 'Only check for updates without installing',\n type: 'boolean',\n default: false\n })\n .option('yes', {\n alias: 'y',\n describe: 'Skip confirmation prompt',\n type: 'boolean',\n default: false\n })\n .example('automatosx update', 'Check and install latest version')\n .example('automatosx update --check', 'Only check for updates')\n .example('automatosx update --yes', 'Update without confirmation');\n },\n\n handler: async (argv) => {\n console.log(chalk.blue.bold('\\n🔄 AutomatosX Update Checker\\n'));\n\n try {\n // Get current version\n const currentVersion = await getCurrentVersion();\n console.log(chalk.gray(`Current version: ${currentVersion}`));\n\n // Check for latest version\n console.log(chalk.cyan('Checking for updates...'));\n const latestVersion = await getLatestVersion();\n console.log(chalk.gray(`Latest version: ${latestVersion}\\n`));\n\n // Compare versions\n if (currentVersion === latestVersion) {\n console.log(chalk.green('✅ You are already running the latest version!\\n'));\n return;\n }\n\n if (isNewer(latestVersion, currentVersion)) {\n console.log(chalk.yellow(`📦 New version available: ${currentVersion} → ${latestVersion}\\n`));\n\n // Show changelog\n await showChangelog(currentVersion, latestVersion);\n\n // If only checking, exit here\n if (argv.check) {\n console.log(chalk.gray('\\nTo install the update, run:'));\n console.log(chalk.cyan(` npm install -g @defai.digital/automatosx@${latestVersion}\\n`));\n return;\n }\n\n // Confirm update\n if (!argv.yes) {\n const readline = await import('readline');\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n });\n\n const answer = await new Promise<string>((resolve) => {\n rl.question(chalk.yellow('Would you like to update now? (y/N) '), resolve);\n });\n rl.close();\n\n if (answer.toLowerCase() !== 'y' && answer.toLowerCase() !== 'yes') {\n console.log(chalk.gray('\\nUpdate cancelled.\\n'));\n return;\n }\n }\n\n // Perform update\n console.log(chalk.cyan('\\n📥 Installing update...\\n'));\n await installUpdate(latestVersion);\n\n console.log(chalk.green.bold('\\n✅ AutomatosX updated successfully!\\n'));\n console.log(chalk.gray('New version:'), chalk.cyan(latestVersion));\n console.log(chalk.gray('\\nRun'), chalk.cyan('automatosx --version'), chalk.gray('to verify.\\n'));\n\n logger.info('AutomatosX updated', { from: currentVersion, to: latestVersion });\n\n } else {\n console.log(chalk.yellow(`⚠️ Your version (${currentVersion}) is newer than the published version (${latestVersion})\\n`));\n console.log(chalk.gray('This might happen if you are running a development version.\\n'));\n }\n\n } catch (error) {\n printError(error, {\n verbose: false,\n showCode: true,\n showSuggestions: true,\n colors: true\n });\n logger.error('Update check failed', { error: (error as Error).message });\n process.exit(1);\n }\n }\n};\n\n/**\n * Get current installed version\n */\nasync function getCurrentVersion(): Promise<string> {\n try {\n const { stdout } = await execAsync('npm list -g @defai.digital/automatosx --depth=0 --json');\n const result = JSON.parse(stdout);\n return result.dependencies['@defai.digital/automatosx']?.version || 'unknown';\n } catch (error) {\n // Fallback to package.json\n const { readFile } = await import('fs/promises');\n const { dirname, join } = await import('path');\n const { fileURLToPath } = await import('url');\n\n const __filename = fileURLToPath(import.meta.url);\n const __dirname = dirname(__filename);\n const pkgPath = join(__dirname, '../../../package.json');\n\n const content = await readFile(pkgPath, 'utf-8');\n const pkg = JSON.parse(content);\n return pkg.version;\n }\n}\n\n/**\n * Get latest version from npm registry\n */\nasync function getLatestVersion(): Promise<string> {\n const { stdout } = await execAsync('npm view @defai.digital/automatosx version');\n return stdout.trim();\n}\n\n/**\n * Check if version a is newer than version b\n */\nfunction isNewer(a: string, b: string): boolean {\n const parseVersion = (v: string) => v.split('.').map(Number);\n const [aMajor = 0, aMinor = 0, aPatch = 0] = parseVersion(a);\n const [bMajor = 0, bMinor = 0, bPatch = 0] = parseVersion(b);\n\n if (aMajor !== bMajor) return aMajor > bMajor;\n if (aMinor !== bMinor) return aMinor > bMinor;\n return aPatch > bPatch;\n}\n\n/**\n * Show changelog between versions\n */\nasync function showChangelog(from: string, to: string): Promise<void> {\n try {\n console.log(chalk.cyan('What\\'s new:\\n'));\n\n // Fetch changelog from GitHub\n const { stdout } = await execAsync(\n `curl -s https://api.github.com/repos/defai-digital/automatosx/releases/tags/v${to}`\n );\n\n const release = JSON.parse(stdout);\n\n if (release.body) {\n // Parse and display first few lines of changelog\n const lines = release.body.split('\\n').slice(0, 10);\n lines.forEach((line: string) => {\n if (line.startsWith('#')) {\n console.log(chalk.bold(line));\n } else if (line.trim()) {\n console.log(chalk.gray(line));\n }\n });\n console.log(chalk.gray('\\n...'));\n console.log(chalk.gray(`Full changelog: https://github.com/defai-digital/automatosx/releases/tag/v${to}`));\n }\n } catch (error) {\n // If changelog fetch fails, continue silently\n logger.debug('Could not fetch changelog', { error: (error as Error).message });\n }\n}\n\n/**\n * Install update using npm\n */\nasync function installUpdate(version: string): Promise<void> {\n try {\n const { stdout, stderr } = await execAsync(\n `npm install -g @defai.digital/automatosx@${version}`,\n { maxBuffer: 10 * 1024 * 1024 }\n );\n\n if (stderr && !stderr.includes('npm warn')) {\n logger.warn('Update installation warnings', { stderr });\n }\n\n logger.debug('Update installation output', { stdout });\n } catch (error) {\n throw new Error(`Failed to install update: ${(error as Error).message}`);\n }\n}\n","/**\n * Workspace Command - Manage agent workspaces\n *\n * @since v4.7.0\n */\n\nimport type { CommandModule } from 'yargs';\nimport { WorkspaceManager } from '../../core/workspace-manager.js';\nimport { createSessionManager } from '../utils/session-utils.js';\nimport chalk from 'chalk';\nimport Table from 'cli-table3';\n\ninterface WorkspaceListOptions {\n session?: string;\n json?: boolean;\n}\n\ninterface WorkspaceStatsOptions {\n json?: boolean;\n}\n\ninterface WorkspaceCleanupOptions {\n olderThan?: number;\n confirm?: boolean;\n}\n\n/**\n * Workspace List Command\n */\nconst listCommand: CommandModule<Record<string, unknown>, WorkspaceListOptions> = {\n command: 'list',\n describe: 'List workspace files',\n\n builder: (yargs) => {\n return yargs\n .option('session', {\n describe: 'Session ID to list files for',\n type: 'string'\n })\n .option('json', {\n describe: 'Output as JSON',\n type: 'boolean',\n default: false\n });\n },\n\n handler: async (argv) => {\n try {\n const { detectProjectRoot } = await import('../../core/path-resolver.js');\n const projectDir = await detectProjectRoot(process.cwd());\n const workspaceManager = new WorkspaceManager(projectDir);\n\n if (argv.session) {\n const sessionManager = await createSessionManager();\n const session = await sessionManager.getSession(argv.session);\n\n if (!session) {\n console.log(chalk.red.bold(`\\n✗ Session not found: ${argv.session}\\n`));\n process.exit(1);\n }\n\n console.log(chalk.blue.bold(`\\n📁 Session Workspace Files\\n`));\n console.log(chalk.gray(`Session: ${argv.session}`));\n console.log(chalk.gray(`Task: ${session.task}\\n`));\n\n for (const agentName of session.agents) {\n const files = await workspaceManager.listSessionFiles(argv.session, agentName);\n\n if (files.length > 0) {\n console.log(chalk.cyan(`\\n${agentName}:`));\n files.forEach(file => {\n console.log(chalk.gray(` - ${file}`));\n });\n }\n }\n\n console.log();\n } else {\n const stats = await workspaceManager.getStats();\n\n if (argv.json) {\n console.log(JSON.stringify(stats, null, 2));\n process.exit(0);\n }\n\n console.log(chalk.blue.bold('\\n📊 Workspace Statistics\\n'));\n console.log(chalk.gray(`Session workspaces: ${chalk.white(stats.totalSessions)}`));\n console.log(chalk.gray(`Agent workspaces: ${chalk.white(stats.agentWorkspaces)}`));\n console.log();\n }\n\n process.exit(0);\n } catch (error) {\n console.error(chalk.red.bold('\\n✗ Failed to list workspaces\\n'));\n console.error(chalk.red((error as Error).message));\n process.exit(1);\n }\n }\n};\n\n/**\n * Workspace Stats Command\n */\nconst statsCommand: CommandModule<Record<string, unknown>, WorkspaceStatsOptions> = {\n command: 'stats',\n describe: 'Show workspace statistics',\n\n builder: (yargs) => {\n return yargs.option('json', {\n describe: 'Output as JSON',\n type: 'boolean',\n default: false\n });\n },\n\n handler: async (argv) => {\n try {\n const { detectProjectRoot } = await import('../../core/path-resolver.js');\n const projectDir = await detectProjectRoot(process.cwd());\n const workspaceManager = new WorkspaceManager(projectDir);\n\n const stats = await workspaceManager.getStats();\n\n if (argv.json) {\n console.log(JSON.stringify(stats, null, 2));\n process.exit(0);\n }\n\n console.log(chalk.blue.bold('\\n📊 Workspace Statistics\\n'));\n console.log(chalk.gray(`Session workspaces: ${chalk.white(stats.totalSessions)}`));\n console.log(chalk.gray(`Agent workspaces: ${chalk.white(stats.agentWorkspaces)}`));\n console.log(chalk.gray(`Total size: ${chalk.white((stats.totalSizeBytes / 1024 / 1024).toFixed(2))} MB`));\n console.log();\n\n process.exit(0);\n } catch (error) {\n console.error(chalk.red.bold('\\n✗ Failed to get workspace stats\\n'));\n console.error(chalk.red((error as Error).message));\n process.exit(1);\n }\n }\n};\n\n/**\n * Workspace Cleanup Command\n */\nconst cleanupCommand: CommandModule<Record<string, unknown>, WorkspaceCleanupOptions> = {\n command: 'cleanup',\n describe: 'Clean up old session workspaces',\n\n builder: (yargs) => {\n return yargs\n .option('older-than', {\n describe: 'Clean up sessions older than N days',\n type: 'number',\n default: 7\n })\n .option('confirm', {\n describe: 'Skip confirmation prompt',\n type: 'boolean',\n default: false\n });\n },\n\n handler: async (argv) => {\n try {\n const { detectProjectRoot } = await import('../../core/path-resolver.js');\n const projectDir = await detectProjectRoot(process.cwd());\n const workspaceManager = new WorkspaceManager(projectDir);\n const sessionManager = await createSessionManager();\n\n // Get active sessions\n const activeSessions = await sessionManager.getActiveSessions();\n const activeIds = activeSessions.map(s => s.id);\n\n if (!argv.confirm) {\n console.log(chalk.yellow(`\\n⚠ This will remove workspace files for inactive sessions`));\n console.log(chalk.gray(`Active sessions (${activeIds.length}) will be kept\\n`));\n console.log(chalk.gray('Run with --confirm to proceed\\n'));\n process.exit(0);\n }\n\n const removed = await workspaceManager.cleanupSessions(activeIds);\n\n console.log(chalk.green.bold(`\\n✓ Cleanup complete\\n`));\n console.log(chalk.gray(`Removed ${removed} session workspace(s)\\n`));\n\n process.exit(0);\n } catch (error) {\n console.error(chalk.red.bold('\\n✗ Failed to cleanup workspaces\\n'));\n console.error(chalk.red((error as Error).message));\n process.exit(1);\n }\n }\n};\n\n/**\n * Main Workspace Command\n */\nexport const workspaceCommand: CommandModule = {\n command: 'workspace <command>',\n describe: 'Manage agent workspaces',\n\n builder: (yargs) => {\n return yargs\n .command(listCommand)\n .command(statsCommand)\n .command(cleanupCommand)\n .demandCommand(1, 'You must specify a workspace command')\n .help();\n },\n\n handler: () => {\n // Parent command handler (not used, subcommands handle everything)\n }\n};\n","/**\n * Agent Command - Manage agents\n * @since v5.0.0\n */\n\nimport type { CommandModule } from 'yargs';\nimport { templatesCommand } from './templates.js';\nimport { createCommand } from './create.js';\nimport { listCommand } from './list.js';\nimport { showCommand } from './show.js';\nimport { removeCommand } from './remove.js';\n\nexport const agentCommand: CommandModule = {\n command: 'agent <command>',\n describe: 'Manage agents',\n\n builder: (yargs) => {\n return yargs\n .command(templatesCommand)\n .command(createCommand)\n .command(listCommand)\n .command(showCommand)\n .command(removeCommand)\n .demandCommand(1, 'You must provide a valid subcommand')\n .help();\n },\n\n handler: () => {\n // This will never be called because we have subcommands\n // Yargs will handle showing help automatically\n }\n};\n","/**\n * Agent Templates Command - List available agent templates\n * @since v5.0.0\n */\n\nimport type { CommandModule } from 'yargs';\nimport { readdir } from 'fs/promises';\nimport { join } from 'path';\nimport { existsSync } from 'fs';\nimport chalk from 'chalk';\n\ninterface TemplateInfo {\n name: string;\n team: string;\n description: string;\n}\n\nconst TEMPLATE_DESCRIPTIONS: Record<string, TemplateInfo> = {\n 'basic-agent': {\n name: 'basic-agent',\n team: 'core',\n description: 'Basic agent with minimal configuration'\n },\n 'developer': {\n name: 'developer',\n team: 'engineering',\n description: 'Software developer (code generation, review, testing)'\n },\n 'analyst': {\n name: 'analyst',\n team: 'business',\n description: 'Business analyst (requirements, user stories, strategy)'\n },\n 'designer': {\n name: 'designer',\n team: 'design',\n description: 'UI/UX designer (interface design, user experience)'\n },\n 'qa-specialist': {\n name: 'qa-specialist',\n team: 'core',\n description: 'QA specialist (test planning, automation, quality)'\n }\n};\n\nexport const templatesCommand: CommandModule = {\n command: 'templates',\n describe: 'List available agent templates',\n\n handler: async () => {\n try {\n console.log(chalk.blue.bold('\\n📋 Available Agent Templates\\n'));\n\n // Check for templates in project directory first\n const projectTemplatesDir = join(process.cwd(), '.automatosx', 'templates');\n const hasProjectTemplates = existsSync(projectTemplatesDir);\n\n // Default templates location (package examples)\n const defaultTemplatesDir = join(__dirname, '../../../../examples/templates');\n const hasDefaultTemplates = existsSync(defaultTemplatesDir);\n\n if (!hasProjectTemplates && !hasDefaultTemplates) {\n console.log(chalk.yellow('⚠ No templates found.'));\n console.log(chalk.gray('\\nRun \"ax init\" to set up default templates.\\n'));\n return;\n }\n\n // Use project templates if available, otherwise use defaults\n const templatesDir = hasProjectTemplates ? projectTemplatesDir : defaultTemplatesDir;\n const templateSource = hasProjectTemplates ? 'Project' : 'Default';\n\n const files = await readdir(templatesDir);\n const templates = files\n .filter(f => f.endsWith('.yaml'))\n .map(f => f.replace('.yaml', ''));\n\n if (templates.length === 0) {\n console.log(chalk.yellow('⚠ No templates found.\\n'));\n return;\n }\n\n console.log(chalk.gray(`Source: ${templateSource} (${templatesDir})\\n`));\n\n // Group by team\n const byTeam: Record<string, TemplateInfo[]> = {\n core: [],\n engineering: [],\n business: [],\n design: []\n };\n\n templates.forEach(template => {\n const info = TEMPLATE_DESCRIPTIONS[template] || {\n name: template,\n team: 'core',\n description: 'Custom template'\n };\n byTeam[info.team]?.push(info);\n });\n\n // Display by team\n const teamNames = {\n core: 'Core Team',\n engineering: 'Engineering Team',\n business: 'Business Team',\n design: 'Design Team'\n };\n\n for (const [team, name] of Object.entries(teamNames)) {\n const teamTemplates = byTeam[team];\n if (teamTemplates && teamTemplates.length > 0) {\n console.log(chalk.cyan.bold(`${name}:`));\n teamTemplates.forEach(t => {\n console.log(chalk.white(` ${t.name.padEnd(20)} - ${t.description}`));\n });\n console.log();\n }\n }\n\n console.log(chalk.gray('Usage: ax agent create <name> --template <template-name>\\n'));\n\n } catch (error) {\n console.error(chalk.red.bold('\\n✗ Error listing templates\\n'));\n console.error(chalk.red((error as Error).message));\n process.exit(1);\n }\n }\n};\n","/**\n * Agent Create Command - Create agent from template\n * @since v5.0.0\n */\n\nimport type { CommandModule } from 'yargs';\nimport { readFile, writeFile, mkdir } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { join } from 'path';\nimport { load as loadYaml } from 'js-yaml';\nimport chalk from 'chalk';\nimport * as readline from 'readline';\nimport { TemplateEngine, type TemplateVariables } from '../../../agents/template-engine.js';\nimport {\n listAvailableTemplates,\n listAvailableTeams,\n isValidAgentName,\n checkDisplayNameConflict,\n suggestValidAgentName\n} from './helpers.js';\n\ninterface CreateOptions {\n agent: string;\n template?: string;\n displayName?: string;\n role?: string;\n description?: string;\n team?: string;\n interactive?: boolean;\n}\n\nexport const createCommand: CommandModule<{}, CreateOptions> = {\n command: 'create <agent>',\n describe: 'Create a new agent from template',\n\n builder: (yargs) => {\n return yargs\n .positional('agent', {\n describe: 'Agent name (lowercase letters, numbers, and hyphens)',\n type: 'string',\n demandOption: true\n })\n .option('template', {\n describe: 'Template to use (run \"ax agent templates\" to see available)',\n type: 'string',\n alias: 't'\n })\n .option('display-name', {\n describe: 'Agent display name (friendly name)',\n type: 'string',\n alias: 'd'\n })\n .option('role', {\n describe: 'Agent role',\n type: 'string',\n alias: 'r'\n })\n .option('description', {\n describe: 'Agent description',\n type: 'string'\n })\n .option('team', {\n describe: 'Team name',\n type: 'string'\n })\n .option('interactive', {\n describe: 'Interactive mode (prompt for missing values)',\n type: 'boolean',\n alias: 'i',\n default: false\n });\n },\n\n handler: async (argv) => {\n try {\n const projectDir = process.cwd();\n const agentsDir = join(projectDir, '.automatosx', 'agents');\n const agentFile = join(agentsDir, `${argv.agent}.yaml`);\n\n // 1. Validate agent name format\n const nameValidation = isValidAgentName(argv.agent);\n if (!nameValidation.valid) {\n console.log(chalk.red.bold(`\\n✗ Invalid agent name: ${argv.agent}\\n`));\n console.log(chalk.red(nameValidation.error));\n const suggestion = suggestValidAgentName(argv.agent);\n if (suggestion !== argv.agent) {\n console.log(chalk.yellow(`\\n💡 Suggested name: ${suggestion}`));\n }\n console.log(chalk.gray('\\nAgent names must:'));\n console.log(chalk.gray(' • Start with a lowercase letter'));\n console.log(chalk.gray(' • Contain only lowercase letters, numbers, and hyphens'));\n console.log(chalk.gray(' • Be 2-50 characters long'));\n console.log(chalk.gray(' • Not contain consecutive hyphens\\n'));\n process.exit(1);\n }\n\n // 2. Check if agent already exists\n if (existsSync(agentFile)) {\n console.log(chalk.red.bold(`\\n✗ Agent already exists: ${argv.agent}\\n`));\n console.log(chalk.gray('Use a different name or remove the existing agent first.\\n'));\n process.exit(1);\n }\n\n // Ensure agents directory exists\n await mkdir(agentsDir, { recursive: true });\n\n // 3. Get template name\n let templateName = argv.template;\n if (!templateName) {\n if (argv.interactive) {\n // Interactive mode: ask user to select\n templateName = await askTemplate();\n } else {\n // Non-interactive mode: use default\n templateName = 'basic-agent';\n console.log(chalk.gray(`Using default template: ${templateName}`));\n }\n }\n\n // 4. Load template\n const templatePath = await findTemplate(templateName);\n const templateContent = await readFile(templatePath, 'utf-8');\n const templateYaml = loadYaml(templateContent) as any;\n\n // 5. Collect variables\n const variables: TemplateVariables = {\n AGENT_NAME: argv.agent,\n DISPLAY_NAME: argv.displayName || '',\n ROLE: argv.role || '',\n DESCRIPTION: argv.description || '',\n TEAM: argv.team || ''\n };\n\n // 6. Interactive mode - ask for missing values\n if (argv.interactive) {\n // Only ask in interactive mode\n if (!variables.DISPLAY_NAME) {\n variables.DISPLAY_NAME = await ask('Display Name', argv.agent);\n }\n\n if (!variables.ROLE && templateYaml.role?.includes('{{')) {\n variables.ROLE = await ask('Role', extractDefault(templateYaml.role) || 'AI Assistant');\n }\n\n if (!variables.DESCRIPTION && templateYaml.description?.includes('{{')) {\n variables.DESCRIPTION = await ask(\n 'Description',\n extractDefault(templateYaml.description) || 'A helpful AI assistant'\n );\n }\n\n if (!variables.TEAM && templateYaml.team?.includes('{{')) {\n variables.TEAM = await askTeam(extractDefault(templateYaml.team) || 'core');\n }\n } else {\n // Non-interactive mode: use defaults for missing values\n if (!variables.DISPLAY_NAME) {\n variables.DISPLAY_NAME = argv.agent;\n }\n if (!variables.ROLE && templateYaml.role?.includes('{{')) {\n variables.ROLE = extractDefault(templateYaml.role) || 'AI Assistant';\n }\n if (!variables.DESCRIPTION && templateYaml.description?.includes('{{')) {\n variables.DESCRIPTION = extractDefault(templateYaml.description) || 'A helpful AI assistant';\n }\n if (!variables.TEAM && templateYaml.team?.includes('{{')) {\n variables.TEAM = extractDefault(templateYaml.team) || 'core';\n }\n }\n\n // 7. Check displayName conflicts\n if (variables.DISPLAY_NAME) {\n const conflict = await checkDisplayNameConflict(variables.DISPLAY_NAME);\n if (conflict) {\n console.log(chalk.red.bold(`\\n✗ DisplayName conflict: \"${variables.DISPLAY_NAME}\" is already used by agent \"${conflict}\"\\n`));\n console.log(chalk.gray('Please choose a different displayName.\\n'));\n process.exit(1);\n }\n }\n\n // 8. Render template\n const engine = new TemplateEngine();\n const rendered = engine.render(templateContent, variables);\n\n // 9. Write agent file\n await writeFile(agentFile, rendered, 'utf-8');\n\n // 10. Success message\n console.log(chalk.green.bold(`\\n✓ Agent '${argv.agent}' created successfully\\n`));\n console.log(chalk.white(`Display Name: ${chalk.cyan(variables.DISPLAY_NAME)}`));\n console.log(chalk.white(`Team: ${chalk.cyan(variables.TEAM || 'core')}`));\n console.log(chalk.white(`Template: ${chalk.gray(templateName)}`));\n console.log(chalk.white(`File: ${chalk.gray(agentFile)}`));\n console.log();\n console.log(chalk.gray('Next steps:'));\n console.log(chalk.gray(' • View details: ax agent show ' + argv.agent));\n console.log(chalk.gray(' • Run agent: ax run ' + argv.agent + ' \"your task\"'));\n console.log(chalk.gray(' • Edit file: Open ' + agentFile + ' in your editor'));\n console.log();\n\n } catch (error) {\n console.error(chalk.red.bold('\\n✗ Error creating agent\\n'));\n console.error(chalk.red((error as Error).message));\n if ((error as Error).stack) {\n console.error(chalk.gray((error as Error).stack));\n }\n process.exit(1);\n }\n }\n};\n\n/**\n * Find template file\n */\nasync function findTemplate(name: string): Promise<string> {\n // Check project templates first\n const projectTemplate = join(process.cwd(), '.automatosx', 'templates', `${name}.yaml`);\n if (existsSync(projectTemplate)) {\n return projectTemplate;\n }\n\n // Check default templates\n const defaultTemplate = join(__dirname, '../../../../examples/templates', `${name}.yaml`);\n if (existsSync(defaultTemplate)) {\n return defaultTemplate;\n }\n\n throw new Error(`Template not found: ${name}\\nRun \"ax agent templates\" to see available templates.`);\n}\n\n/**\n * Ask for template selection\n */\nasync function askTemplate(): Promise<string> {\n const templates = await listAvailableTemplates();\n\n if (templates.length === 0) {\n throw new Error('No templates available. Please run \"ax init\" first.');\n }\n\n console.log(chalk.blue.bold('\\n📋 Available Templates:\\n'));\n templates.forEach((template, index) => {\n const desc = template.description || 'Custom template';\n console.log(chalk.white(` ${index + 1}. ${template.name.padEnd(20)} - ${desc}`));\n });\n console.log();\n\n const answer = await ask(`Select template (1-${templates.length})`, '1');\n const index = parseInt(answer) - 1;\n\n if (index >= 0 && index < templates.length) {\n return templates[index]?.name ?? templates[0]!.name;\n }\n\n return templates[0]!.name;\n}\n\n/**\n * Ask for team selection\n */\nasync function askTeam(defaultValue: string): Promise<string> {\n const teams = await listAvailableTeams();\n\n if (teams.length === 0) {\n throw new Error('No teams available. Please run \"ax init\" first.');\n }\n\n console.log(chalk.blue.bold('\\n👥 Available Teams:\\n'));\n teams.forEach((team, index) => {\n const desc = team.description || team.displayName;\n console.log(chalk.white(` ${index + 1}. ${team.name.padEnd(12)} - ${desc}`));\n });\n console.log();\n\n const defaultIndex = teams.findIndex(t => t.name === defaultValue) + 1;\n const answer = await ask(`Select team (1-${teams.length})`, defaultIndex > 0 ? defaultIndex.toString() : '1');\n const index = parseInt(answer) - 1;\n\n if (index >= 0 && index < teams.length) {\n return teams[index]?.name ?? defaultValue ?? 'core';\n }\n\n return defaultValue || teams[0]?.name || 'core';\n}\n\n/**\n * Extract default value from template variable\n */\nfunction extractDefault(value: string): string | undefined {\n if (!value || !value.includes('default:')) return undefined;\n\n const match = value.match(/default:\\s*([^}]+)/);\n return match?.[1]?.trim();\n}\n\n/**\n * Ask user for input\n */\nfunction ask(question: string, defaultValue?: string): Promise<string> {\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n });\n\n const prompt = defaultValue\n ? `${question} [${chalk.gray(defaultValue)}]: `\n : `${question}: `;\n\n return new Promise(resolve => {\n rl.question(prompt, answer => {\n rl.close();\n resolve(answer.trim() || defaultValue || '');\n });\n });\n}\n","/**\n * Agent Template Engine - v5.0+\n *\n * Provides variable substitution for agent templates.\n * Supports:\n * - Simple variables: {{AGENT_NAME}}\n * - Default values: {{ROLE | default: Software Developer}}\n * - Nested objects and arrays\n *\n * @module agents/template-engine\n * @since v5.0.0\n */\n\n/**\n * Template variables for agent creation\n */\nexport interface TemplateVariables {\n /** Agent name (required) */\n AGENT_NAME: string;\n\n /** Display name (required) */\n DISPLAY_NAME: string;\n\n /** Agent role (optional) */\n ROLE?: string;\n\n /** Agent description (optional) */\n DESCRIPTION?: string;\n\n /** Team name (optional) */\n TEAM?: string;\n\n /** Additional custom variables */\n [key: string]: string | undefined;\n}\n\n/**\n * Template Engine for agent configuration\n *\n * @example\n * ```typescript\n * const engine = new TemplateEngine();\n * const result = engine.render(template, {\n * AGENT_NAME: 'backend-api',\n * DISPLAY_NAME: 'Bob',\n * ROLE: 'Senior Backend Engineer'\n * });\n * ```\n */\nexport class TemplateEngine {\n /**\n * Regex for variable placeholders: {{VAR_NAME}} or {{VAR_NAME | default: value}}\n */\n private static readonly VARIABLE_REGEX = /\\{\\{([^}|]+)(?:\\s*\\|\\s*default:\\s*([^}]+))?\\}\\}/g;\n\n /**\n * Render template with variables\n *\n * @param template - Template string with {{VARIABLE}} placeholders\n * @param variables - Variables to substitute\n * @returns Rendered string\n *\n * @example\n * ```typescript\n * const result = engine.render(\n * 'Hello {{NAME | default: World}}!',\n * { NAME: 'Alice' }\n * );\n * // Result: \"Hello Alice!\"\n * ```\n */\n render(template: string, variables: TemplateVariables): string {\n return template.replace(\n TemplateEngine.VARIABLE_REGEX,\n (match, varName, defaultValue) => {\n const trimmedName = varName.trim();\n const value = variables[trimmedName];\n\n // Use provided value, or default, or keep original placeholder\n if (value !== undefined && value !== null) {\n return value;\n }\n\n if (defaultValue !== undefined) {\n return defaultValue.trim();\n }\n\n // Keep original placeholder if no value and no default\n return match;\n }\n );\n }\n\n /**\n * Render template object (YAML content parsed as object)\n *\n * Recursively processes all string values in the object.\n *\n * @param obj - Object to render (parsed YAML)\n * @param variables - Variables to substitute\n * @returns Rendered object\n *\n * @example\n * ```typescript\n * const template = {\n * name: '{{AGENT_NAME}}',\n * role: '{{ROLE | default: Developer}}'\n * };\n * const result = engine.renderObject(template, { AGENT_NAME: 'backend' });\n * // Result: { name: 'backend', role: 'Developer' }\n * ```\n */\n renderObject<T extends Record<string, any>>(\n obj: T,\n variables: TemplateVariables\n ): T {\n const result: any = Array.isArray(obj) ? [] : {};\n\n for (const key in obj) {\n const value = obj[key];\n\n if (typeof value === 'string') {\n // Render string values\n result[key] = this.render(value, variables);\n } else if (typeof value === 'object' && value !== null) {\n // Recursively render nested objects/arrays\n result[key] = this.renderObject(value, variables);\n } else {\n // Keep other types as-is\n result[key] = value;\n }\n }\n\n return result as T;\n }\n\n /**\n * Validate that all required variables are provided\n *\n * @param template - Template string\n * @param variables - Provided variables\n * @returns Array of missing required variable names\n *\n * @example\n * ```typescript\n * const missing = engine.validateVariables(\n * 'Name: {{NAME}}, Role: {{ROLE | default: Dev}}',\n * { ROLE: 'Engineer' }\n * );\n * // Result: ['NAME'] (ROLE is optional because it has default)\n * ```\n */\n validateVariables(\n template: string,\n variables: TemplateVariables\n ): string[] {\n const missing: string[] = [];\n const regex = new RegExp(TemplateEngine.VARIABLE_REGEX, 'g');\n\n let match: RegExpExecArray | null;\n while ((match = regex.exec(template)) !== null) {\n if (!match[1]) continue; // Skip if capture group is missing\n const varName = match[1].trim();\n const hasDefault = match[2] !== undefined;\n\n // Required if no default value and not provided\n if (!hasDefault && variables[varName] === undefined) {\n if (!missing.includes(varName)) {\n missing.push(varName);\n }\n }\n }\n\n return missing;\n }\n\n /**\n * Extract all variable names from template\n *\n * @param template - Template string\n * @returns Array of variable names (without {{}} and defaults)\n *\n * @example\n * ```typescript\n * const vars = engine.extractVariables('{{NAME}} and {{ROLE | default: Dev}}');\n * // Result: ['NAME', 'ROLE']\n * ```\n */\n extractVariables(template: string): string[] {\n const variables: string[] = [];\n const regex = new RegExp(TemplateEngine.VARIABLE_REGEX, 'g');\n\n let match: RegExpExecArray | null;\n while ((match = regex.exec(template)) !== null) {\n if (!match[1]) continue; // Skip if capture group is missing\n const varName = match[1].trim();\n if (!variables.includes(varName)) {\n variables.push(varName);\n }\n }\n\n return variables;\n }\n}\n\n/**\n * Singleton instance for convenience\n */\nexport const templateEngine = new TemplateEngine();\n","/**\n * Agent Command Helpers\n * Shared utilities for agent commands\n */\n\nimport { readdir } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { join, extname, dirname } from 'path';\nimport { fileURLToPath } from 'url';\nimport { ProfileLoader } from '../../../agents/profile-loader.js';\nimport { TeamManager } from '../../../core/team-manager.js';\nimport { logger } from '../../../utils/logger.js';\n\n// Get the directory of this file for ESM compatibility\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\n/**\n * Template information\n */\nexport interface TemplateInfo {\n name: string;\n path: string;\n description?: string;\n team?: string;\n}\n\n/**\n * Team information\n */\nexport interface TeamInfo {\n name: string;\n displayName: string;\n description?: string;\n}\n\n/**\n * List available templates (project + built-in)\n */\nexport async function listAvailableTemplates(): Promise<TemplateInfo[]> {\n const templates: TemplateInfo[] = [];\n\n // 1. Check project templates (.automatosx/templates/)\n const projectTemplatesDir = join(process.cwd(), '.automatosx', 'templates');\n if (existsSync(projectTemplatesDir)) {\n try {\n const files = await readdir(projectTemplatesDir);\n for (const file of files) {\n if (extname(file) === '.yaml' || extname(file) === '.yml') {\n const name = file.replace(/\\.(yaml|yml)$/, '');\n templates.push({\n name,\n path: join(projectTemplatesDir, file),\n description: 'Custom template'\n });\n }\n }\n } catch (error) {\n logger.debug('Failed to read project templates', { error });\n }\n }\n\n // 2. Check built-in templates (examples/templates/)\n // Note: In production, this should resolve to the correct path\n const builtinTemplatesDir = join(__dirname, '../../../../examples/templates');\n if (existsSync(builtinTemplatesDir)) {\n try {\n const files = await readdir(builtinTemplatesDir);\n for (const file of files) {\n if (extname(file) === '.yaml' || extname(file) === '.yml') {\n const name = file.replace(/\\.(yaml|yml)$/, '');\n\n // Skip if already added from project templates\n if (templates.find(t => t.name === name)) {\n continue;\n }\n\n // Map built-in templates to descriptions\n const descriptions: Record<string, string> = {\n 'basic-agent': 'Basic agent (core team)',\n 'developer': 'Software developer (engineering)',\n 'analyst': 'Business analyst (business)',\n 'designer': 'UI/UX designer (design)',\n 'qa-specialist': 'QA specialist (core)'\n };\n\n templates.push({\n name,\n path: join(builtinTemplatesDir, file),\n description: descriptions[name] || 'Built-in template'\n });\n }\n }\n } catch (error) {\n logger.debug('Failed to read built-in templates', { error });\n }\n }\n\n return templates.sort((a, b) => a.name.localeCompare(b.name));\n}\n\n/**\n * List available teams\n */\nexport async function listAvailableTeams(): Promise<TeamInfo[]> {\n const projectDir = process.cwd();\n const teamsDir = join(projectDir, '.automatosx', 'teams');\n\n const teamManager = new TeamManager(teamsDir);\n\n try {\n const teamNames = await teamManager.listTeams();\n const teams: TeamInfo[] = [];\n\n for (const name of teamNames) {\n try {\n const teamConfig = await teamManager.loadTeam(name);\n teams.push({\n name: teamConfig.name,\n displayName: teamConfig.displayName || teamConfig.name,\n description: teamConfig.description\n });\n } catch (error) {\n // If team fails to load, add basic info\n teams.push({\n name,\n displayName: name,\n description: undefined\n });\n }\n }\n\n return teams.sort((a, b) => a.name.localeCompare(b.name));\n } catch (error) {\n logger.warn('Failed to list teams, using defaults', { error });\n\n // Return default teams if listing fails\n return [\n { name: 'core', displayName: 'Core Team', description: 'Quality assurance, core functions' },\n { name: 'engineering', displayName: 'Engineering Team', description: 'Software development' },\n { name: 'business', displayName: 'Business Team', description: 'Business analysis, product' },\n { name: 'design', displayName: 'Design Team', description: 'UI/UX design' }\n ];\n }\n}\n\n/**\n * Validate agent name format\n * Rules:\n * - Only lowercase letters, numbers, and hyphens\n * - Must start with a letter\n * - No consecutive hyphens\n * - Length: 2-50 characters\n */\nexport function isValidAgentName(name: string): { valid: boolean; error?: string } {\n if (!name || typeof name !== 'string') {\n return { valid: false, error: 'Agent name is required' };\n }\n\n if (name.length < 2) {\n return { valid: false, error: 'Agent name must be at least 2 characters' };\n }\n\n if (name.length > 50) {\n return { valid: false, error: 'Agent name must be at most 50 characters' };\n }\n\n if (!/^[a-z]/.test(name)) {\n return { valid: false, error: 'Agent name must start with a lowercase letter' };\n }\n\n if (!/^[a-z0-9-]+$/.test(name)) {\n return {\n valid: false,\n error: 'Agent name must contain only lowercase letters, numbers, and hyphens'\n };\n }\n\n if (/--/.test(name)) {\n return { valid: false, error: 'Agent name cannot contain consecutive hyphens' };\n }\n\n if (name.endsWith('-')) {\n return { valid: false, error: 'Agent name cannot end with a hyphen' };\n }\n\n return { valid: true };\n}\n\n/**\n * Check if displayName conflicts with existing agents\n * Returns the conflicting agent name if found, undefined otherwise\n */\nexport async function checkDisplayNameConflict(\n displayName: string,\n excludeAgentName?: string\n): Promise<string | undefined> {\n if (!displayName) {\n return undefined;\n }\n\n const projectDir = process.cwd();\n const agentsDir = join(projectDir, '.automatosx', 'agents');\n const profileLoader = new ProfileLoader(agentsDir);\n\n try {\n // Build displayName map\n const allProfiles = await profileLoader.listProfiles();\n\n for (const profileName of allProfiles) {\n // Skip the agent we're updating (if provided)\n if (excludeAgentName && profileName === excludeAgentName) {\n continue;\n }\n\n try {\n const profile = await profileLoader.loadProfile(profileName);\n\n // Check if displayName matches (case-insensitive)\n if (profile.displayName?.toLowerCase() === displayName.toLowerCase()) {\n return profileName;\n }\n } catch (error) {\n // Skip profiles that fail to load\n logger.debug('Failed to load profile for displayName check', {\n profile: profileName,\n error\n });\n }\n }\n\n return undefined;\n } catch (error) {\n logger.warn('Failed to check displayName conflicts', { error });\n return undefined;\n }\n}\n\n/**\n * Suggest valid agent name from invalid input\n */\nexport function suggestValidAgentName(input: string): string {\n let suggestion = input.toLowerCase();\n\n // Replace invalid characters with hyphens\n suggestion = suggestion.replace(/[^a-z0-9-]/g, '-');\n\n // Remove consecutive hyphens\n suggestion = suggestion.replace(/-+/g, '-');\n\n // Remove leading/trailing hyphens\n suggestion = suggestion.replace(/^-+|-+$/g, '');\n\n // Minimum length check before adding prefix\n if (suggestion.length < 2) {\n return 'agent';\n }\n\n // Ensure it starts with a letter\n if (!/^[a-z]/.test(suggestion)) {\n suggestion = 'agent-' + suggestion;\n }\n\n // Limit length\n if (suggestion.length > 50) {\n suggestion = suggestion.substring(0, 50).replace(/-+$/, '');\n }\n\n return suggestion;\n}\n","/**\n * Agent List Command - List all agents\n * @since v5.0.0\n */\n\nimport type { CommandModule } from 'yargs';\nimport { ProfileLoader } from '../../../agents/profile-loader.js';\nimport { TeamManager } from '../../../core/team-manager.js';\nimport { join } from 'path';\nimport chalk from 'chalk';\n\ninterface ListOptions {\n byTeam?: string;\n}\n\nexport const listCommand: CommandModule<{}, ListOptions> = {\n command: 'list',\n describe: 'List all agents',\n\n builder: (yargs) => {\n return yargs\n .option('by-team', {\n describe: 'Filter agents by team',\n type: 'string',\n choices: ['core', 'engineering', 'business', 'design', 'research']\n });\n },\n\n handler: async (argv) => {\n try {\n const projectDir = process.cwd();\n const agentsDir = join(projectDir, '.automatosx', 'agents');\n const teamsDir = join(projectDir, '.automatosx', 'teams');\n\n // Initialize managers\n const teamManager = new TeamManager(teamsDir);\n const profileLoader = new ProfileLoader(agentsDir, undefined, teamManager);\n\n // List all agents\n const agentNames = await profileLoader.listProfiles();\n\n if (agentNames.length === 0) {\n console.log(chalk.yellow('\\n⚠ No agents found.\\n'));\n console.log(chalk.gray('Run \"ax agent create\" to create your first agent.\\n'));\n return;\n }\n\n console.log(chalk.blue.bold(`\\n🤖 Agents (${agentNames.length} total)\\n`));\n\n // Load all profiles\n const profiles = await Promise.all(\n agentNames.map(async name => {\n try {\n return await profileLoader.loadProfile(name);\n } catch (error) {\n return null;\n }\n })\n );\n\n // Group by team\n const byTeam: Record<string, typeof profiles> = {\n core: [],\n engineering: [],\n business: [],\n design: [],\n research: [],\n other: []\n };\n\n profiles.forEach(profile => {\n if (!profile) return;\n const team = profile.team || 'other';\n if (byTeam[team]) {\n byTeam[team]?.push(profile);\n } else {\n byTeam.other?.push(profile);\n }\n });\n\n // Filter by team if specified\n const teamsToShow = argv.byTeam\n ? [argv.byTeam]\n : ['core', 'engineering', 'business', 'design', 'research', 'other'];\n\n const teamNames: Record<string, string> = {\n core: 'Core Team',\n engineering: 'Engineering Team',\n business: 'Business Team',\n design: 'Design Team',\n research: 'Research Team',\n other: 'Other'\n };\n\n // Display by team\n for (const team of teamsToShow) {\n const teamAgents = byTeam[team];\n if (teamAgents && teamAgents.length > 0) {\n console.log(chalk.cyan.bold(`${teamNames[team]} (${teamAgents.length}):`));\n\n teamAgents.forEach(profile => {\n if (!profile) return;\n const displayName = profile.displayName ? ` (${profile.displayName})` : '';\n const role = profile.role ? chalk.gray(` - ${profile.role}`) : '';\n console.log(chalk.white(` ${profile.name}${displayName}${role}`));\n });\n\n console.log();\n }\n }\n\n console.log(chalk.gray('Usage: ax agent show <name> for details\\n'));\n\n } catch (error) {\n console.error(chalk.red.bold('\\n✗ Error listing agents\\n'));\n console.error(chalk.red((error as Error).message));\n process.exit(1);\n }\n }\n};\n","/**\n * Agent Show Command - Show agent details\n * @since v5.0.0\n */\n\nimport type { CommandModule } from 'yargs';\nimport { ProfileLoader } from '../../../agents/profile-loader.js';\nimport { TeamManager } from '../../../core/team-manager.js';\nimport { join } from 'path';\nimport chalk from 'chalk';\n\ninterface ShowOptions {\n agent: string;\n}\n\nexport const showCommand: CommandModule<{}, ShowOptions> = {\n command: 'show <agent>',\n describe: 'Show agent details',\n\n builder: (yargs) => {\n return yargs\n .positional('agent', {\n describe: 'Agent name',\n type: 'string',\n demandOption: true\n });\n },\n\n handler: async (argv) => {\n try {\n const projectDir = process.cwd();\n const agentsDir = join(projectDir, '.automatosx', 'agents');\n const teamsDir = join(projectDir, '.automatosx', 'teams');\n\n // Initialize managers\n const teamManager = new TeamManager(teamsDir);\n const profileLoader = new ProfileLoader(agentsDir, undefined, teamManager);\n\n // Resolve agent name (supports displayName)\n const resolvedName = await profileLoader.resolveAgentName(argv.agent);\n\n // Load profile using resolved name\n const profile = await profileLoader.loadProfile(resolvedName);\n\n console.log(chalk.blue.bold(`\\n🤖 Agent: ${profile.name}\\n`));\n\n // Basic info\n if (profile.displayName) {\n console.log(chalk.white(`Display Name: ${chalk.cyan(profile.displayName)}`));\n }\n if (profile.team) {\n console.log(chalk.white(`Team: ${chalk.cyan(profile.team)}`));\n }\n if (profile.role) {\n console.log(chalk.white(`Role: ${chalk.gray(profile.role)}`));\n }\n if (profile.description) {\n console.log(chalk.white(`Description: ${chalk.gray(profile.description)}`));\n }\n\n console.log();\n\n // Abilities\n if (profile.abilities && profile.abilities.length > 0) {\n console.log(chalk.cyan.bold('Abilities:'));\n profile.abilities.forEach(ability => {\n console.log(chalk.white(` • ${ability}`));\n });\n console.log();\n }\n\n // Configuration\n console.log(chalk.cyan.bold('Configuration:'));\n if (profile.provider) {\n console.log(chalk.white(` Provider: ${profile.provider}`));\n }\n if (profile.model) {\n console.log(chalk.white(` Model: ${profile.model}`));\n }\n if (profile.temperature !== undefined) {\n console.log(chalk.white(` Temperature: ${profile.temperature}`));\n }\n if (profile.maxTokens !== undefined) {\n console.log(chalk.white(` Max Tokens: ${profile.maxTokens}`));\n }\n console.log();\n\n // Orchestration\n if (profile.orchestration) {\n console.log(chalk.cyan.bold('Orchestration:'));\n\n const orch = profile.orchestration;\n\n if (orch.maxDelegationDepth !== undefined) {\n console.log(chalk.white(` Max Delegation Depth: ${orch.maxDelegationDepth}`));\n }\n\n if (orch.canReadWorkspaces && orch.canReadWorkspaces.length > 0) {\n console.log(chalk.white(` Can Read Workspaces: ${orch.canReadWorkspaces.join(', ')}`));\n }\n\n if (orch.canWriteToShared !== undefined) {\n console.log(chalk.white(` Can Write to Shared: ${orch.canWriteToShared ? 'Yes' : 'No'}`));\n }\n\n console.log();\n }\n\n // File location\n const filePath = join(agentsDir, `${argv.agent}.yaml`);\n console.log(chalk.gray(`File: ${filePath}`));\n console.log();\n\n } catch (error) {\n console.error(chalk.red.bold(`\\n✗ Agent not found: ${argv.agent}\\n`));\n console.error(chalk.red((error as Error).message));\n\n // Try to suggest similar agents\n try {\n const projectDir = process.cwd();\n const agentsDir = join(projectDir, '.automatosx', 'agents');\n const teamsDir = join(projectDir, '.automatosx', 'teams');\n const teamManager = new TeamManager(teamsDir);\n const profileLoader = new ProfileLoader(agentsDir, undefined, teamManager);\n\n const suggestions = await profileLoader.findSimilarAgents(argv.agent, 3);\n const closeSuggestions = suggestions.filter(s => s.distance <= 3);\n\n if (closeSuggestions.length > 0) {\n console.log(chalk.yellow('\\n💡 Did you mean:\\n'));\n closeSuggestions.forEach((s, i) => {\n const displayInfo = s.displayName ? `${s.displayName} (${s.name})` : s.name;\n const roleInfo = s.role ? ` - ${s.role}` : '';\n console.log(chalk.cyan(` ${i + 1}. ${displayInfo}${roleInfo}`));\n });\n console.log();\n } else {\n console.log(chalk.gray('\\nRun \"ax agent list\" to see available agents.\\n'));\n }\n } catch {\n console.log(chalk.gray('\\nRun \"ax agent list\" to see available agents.\\n'));\n }\n\n process.exit(1);\n }\n }\n};\n","/**\n * Agent Remove Command - Remove an agent\n * @since v5.0.0\n */\n\nimport type { CommandModule } from 'yargs';\nimport { unlink } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { join } from 'path';\nimport chalk from 'chalk';\nimport * as readline from 'readline';\nimport { ProfileLoader } from '../../../agents/profile-loader.js';\nimport { TeamManager } from '../../../core/team-manager.js';\n\ninterface RemoveOptions {\n agent: string;\n confirm?: boolean;\n}\n\nexport const removeCommand: CommandModule<{}, RemoveOptions> = {\n command: 'remove <agent>',\n describe: 'Remove an agent',\n aliases: ['rm', 'delete'],\n\n builder: (yargs) => {\n return yargs\n .positional('agent', {\n describe: 'Agent name',\n type: 'string',\n demandOption: true\n })\n .option('confirm', {\n describe: 'Skip confirmation prompt',\n type: 'boolean',\n alias: 'y'\n });\n },\n\n handler: async (argv) => {\n try {\n const projectDir = process.cwd();\n const agentsDir = join(projectDir, '.automatosx', 'agents');\n const teamsDir = join(projectDir, '.automatosx', 'teams');\n\n // Initialize managers\n const teamManager = new TeamManager(teamsDir);\n const profileLoader = new ProfileLoader(agentsDir, undefined, teamManager);\n\n // Resolve agent name (supports displayName)\n let resolvedName: string;\n try {\n resolvedName = await profileLoader.resolveAgentName(argv.agent);\n } catch (error) {\n console.log(chalk.red.bold(`\\n✗ Agent not found: ${argv.agent}\\n`));\n\n // Try to suggest similar agents\n try {\n const suggestions = await profileLoader.findSimilarAgents(argv.agent, 3);\n const closeSuggestions = suggestions.filter(s => s.distance <= 3);\n\n if (closeSuggestions.length > 0) {\n console.log(chalk.yellow('💡 Did you mean:\\n'));\n closeSuggestions.forEach((s, i) => {\n const displayInfo = s.displayName ? `${s.displayName} (${s.name})` : s.name;\n const roleInfo = s.role ? ` - ${s.role}` : '';\n console.log(chalk.cyan(` ${i + 1}. ${displayInfo}${roleInfo}`));\n });\n console.log();\n } else {\n console.log(chalk.gray('Run \"ax agent list\" to see available agents.\\n'));\n }\n } catch {\n console.log(chalk.gray('Run \"ax agent list\" to see available agents.\\n'));\n }\n\n process.exit(1);\n }\n\n const agentFile = join(agentsDir, `${resolvedName}.yaml`);\n\n // Check if agent file exists\n if (!existsSync(agentFile)) {\n console.log(chalk.red.bold(`\\n✗ Agent file not found: ${resolvedName}\\n`));\n console.log(chalk.gray('Run \"ax agent list\" to see available agents.\\n'));\n process.exit(1);\n }\n\n // Load profile to get display name for confirmation message\n const profile = await profileLoader.loadProfile(resolvedName);\n const displayInfo = profile.displayName ? `${profile.displayName} (${resolvedName})` : resolvedName;\n\n // Confirm deletion\n if (!argv.confirm) {\n const confirmed = await askConfirmation(\n `Are you sure you want to remove agent '${chalk.cyan(displayInfo)}'?`\n );\n\n if (!confirmed) {\n console.log(chalk.yellow('\\nCancelled.\\n'));\n process.exit(0);\n }\n }\n\n // Remove file\n await unlink(agentFile);\n\n console.log(chalk.green.bold(`\\n✓ Agent '${displayInfo}' removed successfully\\n`));\n console.log(chalk.gray(`Deleted: ${agentFile}\\n`));\n\n } catch (error) {\n console.error(chalk.red.bold('\\n✗ Error removing agent\\n'));\n console.error(chalk.red((error as Error).message));\n process.exit(1);\n }\n }\n};\n\n/**\n * Ask for user confirmation\n */\nfunction askConfirmation(question: string): Promise<boolean> {\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n });\n\n return new Promise(resolve => {\n rl.question(chalk.yellow(`\\n${question} (y/N): `), answer => {\n rl.close();\n resolve(answer.toLowerCase() === 'y' || answer.toLowerCase() === 'yes');\n });\n });\n}\n"],"mappings":";;;;;;;;;;;;AACA,OAAO,UAAU;AACjB,SAAS,qBAAqB;AAF9B,IAIM,aACA,YAEO;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AAA,IACd,UAAU,QAAQ;AAAA,IAClB,MAAM,QAAQ;AAAA,IACd,KAAK,QAAQ,IAAI;AAAA,IACjB,MAAM,QAAQ,KAAK,MAAM,CAAC;AAAA,EAC5B,CAAC;AACH;AAEA,IAAI,KAAK,OAAO;AACd,cAAY,OAAO;AACnB,UAAQ,IAAI,mBAAmB;AACjC;AAGA,IAAI,KAAK,QAAQ;AACf,UAAQ,IAAI,yBAAyB,KAAK;AAC1C,SAAO,MAAM,0BAA0B,EAAE,MAAM,KAAK,OAAO,CAAC;AAC9D;AAGA,IAAI,KAAK,OAAO;AACd,SAAO,MAAM,0BAA0B;AAAA,IACrC,SAASA;AAAA,IACT,SAAS,KAAK,EAAE,CAAC;AAAA,IACjB,SAAS;AAAA,MACP,OAAO,KAAK;AAAA,MACZ,OAAO,KAAK;AAAA,MACZ,QAAQ,KAAK;AAAA,IACf;AAAA,EACF,CAAC;AACH;AAEA,cAAc,KAAK,mBAAmB;AACtC,cAAc,QAAQ,iBAAiB,uBAAuB,mBAAmB;AAGjF,cAAc,KAAK,WAAW;AAC9B,cAAc,QAAQ,eAAe,aAAa,WAAW;AAG7D,IAAI,cAAc,UAAU,KAAK,KAAK,OAAO;AAC3C,UAAQ,MAAM,OAAO,cAAc,eAAe,IAAI,IAAI;AAC5D;","names":["PathError","resolve","dirname","path","PathError","createRequire","resolve","chalk","path","chalk","chalk","chalk","writeFile","existsSync","path","existsSync","path","validateConfig","writeFile","yargs","argv","resolve","fs","chalk","path","mkdir","writeFile","access","resolve","join","dirname","fileURLToPath","constants","chalk","__filename","fileURLToPath","__dirname","dirname","join","yargs","argv","resolve","chalk","checkExists","path","access","constants","mkdir","readdir","copyFile","writeFile","readFile","join","chalk","yargs","argv","join","chalk","existsSync","load","readFile","resolve","existsSync","dirname","dirname","existsSync","deletedCount","mkdir","writeFile","readFile","chalk","chalk","path","resolve","yargs","argv","chalk","createInterface","listCommand","mkdir","join","resolve","join","resolve","mkdir","provider","readFile","readdir","join","extname","dirname","fileURLToPath","load","__filename","fileURLToPath","__dirname","dirname","getPackageRoot","join","readdir","extname","readFile","load","readFile","readdir","join","extname","basename","dirname","fileURLToPath","__filename","fileURLToPath","__dirname","dirname","getPackageRoot","join","readFile","readdir","extname","basename","chalk","ora","resolve","chalk","ora","result","chalk","totalDuration","totalTokens","randomUUID","readFile","writeFile","mkdir","dirname","randomUUID","mkdir","dirname","writeFile","readFile","path","path","readFile","readdir","join","extname","basename","load","join","readFile","load","readdir","extname","basename","resolve","resolve","resolve","resolve","chalk","join","mkdir","chalk","yargs","argv","chalk","join","mkdir","resolve","join","chalk","Table","yargs","argv","listCommand","chalk","existsSync","readdir","join","require","statusCommand","yargs","argv","join","existsSync","chalk","readdir","readFile","chalk","yargs","argv","chalk","readline","resolve","readFile","dirname","join","fileURLToPath","__filename","__dirname","chalk","listCommand","yargs","argv","detectProjectRoot","statsCommand","readdir","join","existsSync","chalk","readFile","writeFile","mkdir","existsSync","join","loadYaml","chalk","readdir","existsSync","join","extname","dirname","fileURLToPath","__filename","fileURLToPath","__dirname","dirname","join","existsSync","readdir","extname","createCommand","yargs","argv","join","chalk","existsSync","mkdir","readFile","loadYaml","writeFile","index","resolve","join","chalk","listCommand","yargs","argv","join","chalk","yargs","argv","unlink","existsSync","join","chalk","readline","yargs","argv","join","chalk","displayInfo","existsSync","unlink","resolve","yargs","createCommand","listCommand","require","createRequire","VERSION","statusCommand"]}
1
+ {"version":3,"sources":["../node_modules/tsup/assets/esm_shims.js","../src/utils/logger.ts","../src/core/cache.ts","../src/types/path.ts","../src/core/path-resolver.ts","../src/providers/base-provider.ts","../src/providers/claude-provider.ts","../src/providers/gemini-provider.ts","../src/providers/openai-provider.ts","../src/cli/index.ts","../src/utils/performance.ts","../src/cli/commands/config.ts","../src/types/config.ts","../src/utils/error-formatter.ts","../src/utils/errors.ts","../src/utils/message-formatter.ts","../src/utils/config-validator.ts","../src/core/config.ts","../src/utils/deep-merge.ts","../src/core/validation-limits.ts","../src/cli/commands/init.ts","../src/cli/commands/list.ts","../src/cli/commands/mcp.ts","../src/mcp/server.ts","../src/mcp/types.ts","../src/core/router.ts","../src/core/memory-manager.ts","../src/types/memory.ts","../src/core/session-manager.ts","../src/types/orchestration.ts","../src/core/workspace-manager.ts","../src/agents/context-manager.ts","../src/agents/profile-loader.ts","../src/types/agent.ts","../src/agents/abilities-manager.ts","../src/core/team-manager.ts","../src/types/team.ts","../src/mcp/tools/run-agent.ts","../src/agents/executor.ts","../src/agents/delegation-parser.ts","../src/mcp/utils/validation.ts","../src/mcp/tools/list-agents.ts","../src/mcp/tools/search-memory.ts","../src/mcp/tools/get-status.ts","../src/mcp/tools/session-create.ts","../src/mcp/tools/session-list.ts","../src/mcp/tools/session-status.ts","../src/mcp/tools/session-complete.ts","../src/mcp/tools/session-fail.ts","../src/mcp/tools/memory-add.ts","../src/mcp/tools/memory-list.ts","../src/mcp/tools/memory-delete.ts","../src/mcp/tools/memory-export.ts","../src/mcp/tools/memory-import.ts","../src/mcp/tools/memory-stats.ts","../src/mcp/tools/memory-clear.ts","../src/cli/commands/memory.ts","../src/utils/progress.ts","../src/cli/commands/run.ts","../src/agents/stage-executor.ts","../src/agents/advanced-stage-executor.ts","../src/utils/output-formatter.ts","../src/cli/commands/session.ts","../src/cli/utils/session-utils.ts","../src/cli/commands/status.ts","../src/cli/commands/update.ts","../src/cli/commands/workspace.ts","../src/cli/commands/agent/index.ts","../src/cli/commands/agent/templates.ts","../src/cli/commands/agent/create.ts","../src/agents/template-engine.ts","../src/cli/commands/agent/helpers.ts","../src/cli/commands/agent/list.ts","../src/cli/commands/agent/show.ts","../src/cli/commands/agent/remove.ts"],"sourcesContent":["// Shim globals in esm bundle\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nconst getFilename = () => fileURLToPath(import.meta.url)\nconst getDirname = () => path.dirname(getFilename())\n\nexport const __dirname = /* @__PURE__ */ getDirname()\nexport const __filename = /* @__PURE__ */ getFilename()\n","/**\n * Enhanced Logger for AutomatosX\n *\n * Features:\n * - Structured logging (JSON mode)\n * - File output with rotation\n * - Secrets sanitization\n * - Multiple log levels\n * - Performance profiling\n */\n\nimport type { Logger, LogEntry, LoggerConfig } from '../types/logger.js';\nimport { LogLevel } from '../types/logger.js';\nimport { writeFile, appendFile, mkdir } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { dirname } from 'path';\n\nconst LOG_LEVELS: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3\n};\n\nconst COLORS = {\n debug: '\\x1b[36m', // Cyan\n info: '\\x1b[32m', // Green\n warn: '\\x1b[33m', // Yellow\n error: '\\x1b[31m', // Red\n reset: '\\x1b[0m'\n};\n\n// Sensitive field names to redact\nconst SENSITIVE_KEYS = [\n 'password',\n 'passwd',\n 'secret',\n 'token',\n 'apiKey',\n 'api_key',\n 'apikey',\n 'accessToken',\n 'access_token',\n 'refreshToken',\n 'refresh_token',\n 'privateKey',\n 'private_key',\n 'credential',\n 'credentials',\n 'auth',\n 'authorization'\n];\n\n/**\n * Sanitize object by redacting sensitive fields\n */\nfunction sanitizeObject(obj: any, maxDepth = 5, currentDepth = 0): any {\n // Prevent infinite recursion\n if (currentDepth > maxDepth) {\n return '[Max Depth Reached]';\n }\n\n // Handle null/undefined\n if (obj === null || obj === undefined) {\n return obj;\n }\n\n // Handle primitive types\n if (typeof obj !== 'object') {\n return obj;\n }\n\n // Handle arrays\n if (Array.isArray(obj)) {\n return obj.map(item => sanitizeObject(item, maxDepth, currentDepth + 1));\n }\n\n // Handle objects\n const sanitized: Record<string, any> = {};\n\n for (const [key, value] of Object.entries(obj)) {\n const lowerKey = key.toLowerCase();\n\n // Check if key contains sensitive keywords\n const isSensitive = SENSITIVE_KEYS.some(sensitiveKey =>\n lowerKey.includes(sensitiveKey.toLowerCase())\n );\n\n if (isSensitive) {\n sanitized[key] = '[REDACTED]';\n } else if (value && typeof value === 'object') {\n // Recursively sanitize nested objects\n sanitized[key] = sanitizeObject(value, maxDepth, currentDepth + 1);\n } else {\n sanitized[key] = value;\n }\n }\n\n return sanitized;\n}\n\nexport class SimpleLogger implements Logger {\n private config: LoggerConfig;\n private jsonMode: boolean;\n\n constructor(config: Partial<LoggerConfig> = {}) {\n this.config = {\n level: config.level || 'info',\n console: config.console ?? true,\n file: config.file\n };\n this.jsonMode = false;\n }\n\n /**\n * Enable JSON output mode\n */\n enableJSONMode(): void {\n this.jsonMode = true;\n }\n\n /**\n * Disable JSON output mode\n */\n disableJSONMode(): void {\n this.jsonMode = false;\n }\n\n /**\n * Check if JSON mode is enabled\n */\n isJSONMode(): boolean {\n return this.jsonMode;\n }\n\n debug(message: string, context?: Record<string, unknown>): void {\n this.log('debug', message, context);\n }\n\n info(message: string, context?: Record<string, unknown>): void {\n this.log('info', message, context);\n }\n\n warn(message: string, context?: Record<string, unknown>): void {\n this.log('warn', message, context);\n }\n\n error(message: string, context?: Record<string, unknown>): void {\n this.log('error', message, context);\n }\n\n setLevel(level: LogLevel): void {\n this.config.level = level;\n }\n\n getLevel(): LogLevel {\n return this.config.level;\n }\n\n private log(level: LogLevel, message: string, context?: Record<string, unknown>): void {\n // Check if this log level should be output\n if (LOG_LEVELS[level] < LOG_LEVELS[this.config.level]) {\n return;\n }\n\n // Sanitize context to remove sensitive data\n const sanitizedContext = context ? sanitizeObject(context) : undefined;\n\n const entry: LogEntry = {\n level,\n message,\n timestamp: new Date(),\n context: sanitizedContext\n };\n\n // Console output\n if (this.config.console) {\n this.logToConsole(entry);\n }\n\n // File output\n if (this.config.file) {\n this.logToFile(entry).catch(err => {\n // Silently fail to avoid infinite loop\n if (this.config.console) {\n console.error(`Failed to write to log file: ${err.message}`);\n }\n });\n }\n }\n\n private logToConsole(entry: LogEntry): void {\n // JSON mode - output raw JSON\n if (this.jsonMode) {\n const json = JSON.stringify({\n timestamp: entry.timestamp.toISOString(),\n level: entry.level,\n message: entry.message,\n context: entry.context\n });\n\n if (entry.level === 'error') {\n console.error(json);\n } else {\n console.log(json);\n }\n return;\n }\n\n // Human-readable mode\n const timestamp = entry.timestamp.toISOString();\n const color = COLORS[entry.level];\n const reset = COLORS.reset;\n const levelStr = entry.level.toUpperCase().padEnd(5);\n\n let logMessage = `${color}[${timestamp}] ${levelStr}${reset} ${entry.message}`;\n\n if (entry.context) {\n logMessage += `\\n${JSON.stringify(entry.context, null, 2)}`;\n }\n\n // Output to stderr to avoid polluting stdout (especially for JSON output)\n // This ensures CLI commands can output clean JSON to stdout\n if (entry.level === 'error') {\n console.error(logMessage);\n } else if (entry.level === 'warn') {\n console.warn(logMessage);\n } else {\n // info and debug also go to stderr\n console.error(logMessage);\n }\n }\n\n /**\n * Write log entry to file\n */\n private async logToFile(entry: LogEntry): Promise<void> {\n if (!this.config.file) {\n return;\n }\n\n // Ensure directory exists\n const dir = dirname(this.config.file);\n if (!existsSync(dir)) {\n await mkdir(dir, { recursive: true });\n }\n\n // Format entry as JSON (one line per entry)\n const json = JSON.stringify({\n timestamp: entry.timestamp.toISOString(),\n level: entry.level,\n message: entry.message,\n context: entry.context\n });\n\n // Append to file\n await appendFile(this.config.file, json + '\\n', 'utf-8');\n }\n}\n\n// Default logger instance\nexport const logger = new SimpleLogger();\n\n// Create logger with custom config\nexport function createLogger(config: Partial<LoggerConfig>): Logger {\n return new SimpleLogger(config);\n}\n\n// Set log level on default logger\nexport function setLogLevel(level: LogLevel): void {\n logger.setLevel(level);\n}\n\n// Get current log level\nexport function getLogLevel(): LogLevel {\n return logger.getLevel();\n}\n\n// Re-export LogLevel for convenience\nexport type { LogLevel };\n","/**\n * Advanced Caching System with TTL-based LRU eviction\n *\n * Features:\n * - Time-To-Live (TTL) expiration\n * - Least Recently Used (LRU) eviction\n * - Size limits\n * - Statistics tracking\n * - Automatic cleanup\n *\n * @module core/cache\n */\n\nimport { logger } from '../utils/logger.js';\n\n/**\n * Cache entry with metadata\n */\ninterface CacheEntry<T> {\n value: T;\n timestamp: number;\n hits: number;\n size: number; // Estimated size in bytes\n}\n\n/**\n * Cache statistics\n */\nexport interface CacheStats {\n hits: number;\n misses: number;\n sets: number;\n evictions: number;\n size: number;\n entries: number;\n hitRate: number;\n avgEntrySize: number;\n}\n\n/**\n * Cache configuration\n */\nexport interface CacheConfig {\n /** Maximum number of entries */\n maxEntries: number;\n /** Time-to-live in milliseconds (0 = no expiration) */\n ttl: number;\n /** Maximum cache size in bytes (0 = no limit) */\n maxSize?: number;\n /** Cleanup interval in milliseconds */\n cleanupInterval?: number;\n /** Enable debug logging */\n debug?: boolean;\n}\n\n/**\n * TTL-based LRU Cache\n *\n * Thread-safe caching with automatic expiration and eviction.\n *\n * @example\n * ```typescript\n * const cache = new TTLCache<string>({\n * maxEntries: 100,\n * ttl: 60000, // 1 minute\n * maxSize: 1024 * 1024 // 1MB\n * });\n *\n * cache.set('key', 'value');\n * const value = cache.get('key'); // 'value'\n *\n * // After 1 minute\n * cache.get('key'); // undefined (expired)\n * ```\n */\nexport class TTLCache<T> {\n private cache = new Map<string, CacheEntry<T>>();\n private config: Required<CacheConfig>;\n private stats = {\n hits: 0,\n misses: 0,\n sets: 0,\n evictions: 0\n };\n private cleanupTimer?: NodeJS.Timeout;\n private totalSize = 0;\n\n constructor(config: CacheConfig) {\n this.config = {\n maxEntries: config.maxEntries,\n ttl: config.ttl,\n maxSize: config.maxSize ?? 0,\n cleanupInterval: config.cleanupInterval ?? 60000, // 1 minute default\n debug: config.debug ?? false\n };\n\n // Start automatic cleanup\n if (this.config.cleanupInterval > 0) {\n this.startCleanup();\n }\n\n if (this.config.debug) {\n logger.debug('TTLCache initialized', {\n maxEntries: this.config.maxEntries,\n ttl: this.config.ttl,\n maxSize: this.config.maxSize,\n cleanupInterval: this.config.cleanupInterval\n });\n }\n }\n\n /**\n * Get value from cache\n *\n * @param key Cache key\n * @returns Cached value or undefined if not found/expired\n */\n get(key: string): T | undefined {\n const entry = this.cache.get(key);\n\n if (!entry) {\n this.stats.misses++;\n if (this.config.debug) {\n logger.debug('Cache miss', { key });\n }\n return undefined;\n }\n\n // Check if expired\n if (this.isExpired(entry)) {\n this.delete(key);\n this.stats.misses++;\n if (this.config.debug) {\n logger.debug('Cache expired', { key, age: Date.now() - entry.timestamp });\n }\n return undefined;\n }\n\n // Update LRU order (move to end)\n this.cache.delete(key);\n entry.hits++;\n this.cache.set(key, entry);\n\n this.stats.hits++;\n if (this.config.debug) {\n logger.debug('Cache hit', { key, hits: entry.hits });\n }\n\n return entry.value;\n }\n\n /**\n * Set value in cache\n *\n * @param key Cache key\n * @param value Value to cache\n * @param customTTL Optional custom TTL for this entry (ms)\n */\n set(key: string, value: T, customTTL?: number): void {\n const size = this.estimateSize(value);\n\n // Check size limit\n if (this.config.maxSize > 0 && size > this.config.maxSize) {\n logger.warn('Entry too large for cache', {\n key,\n size,\n maxSize: this.config.maxSize\n });\n return;\n }\n\n // Remove existing entry if present\n const existing = this.cache.get(key);\n if (existing) {\n this.totalSize -= existing.size;\n }\n\n // Evict entries if needed\n this.evictIfNeeded(size);\n\n // Create entry\n const entry: CacheEntry<T> = {\n value,\n timestamp: Date.now(),\n hits: 0,\n size\n };\n\n this.cache.set(key, entry);\n this.totalSize += size;\n this.stats.sets++;\n\n if (this.config.debug) {\n logger.debug('Cache set', {\n key,\n size,\n totalSize: this.totalSize,\n entries: this.cache.size\n });\n }\n }\n\n /**\n * Check if key exists and is not expired\n */\n has(key: string): boolean {\n const entry = this.cache.get(key);\n if (!entry) return false;\n if (this.isExpired(entry)) {\n this.delete(key);\n return false;\n }\n return true;\n }\n\n /**\n * Delete entry from cache\n */\n delete(key: string): boolean {\n const entry = this.cache.get(key);\n if (entry) {\n this.totalSize -= entry.size;\n this.cache.delete(key);\n return true;\n }\n return false;\n }\n\n /**\n * Clear all entries\n */\n clear(): void {\n this.cache.clear();\n this.totalSize = 0;\n if (this.config.debug) {\n logger.debug('Cache cleared');\n }\n }\n\n /**\n * Get cache statistics\n */\n getStats(): CacheStats {\n const total = this.stats.hits + this.stats.misses;\n return {\n hits: this.stats.hits,\n misses: this.stats.misses,\n sets: this.stats.sets,\n evictions: this.stats.evictions,\n size: this.totalSize,\n entries: this.cache.size,\n hitRate: total > 0 ? this.stats.hits / total : 0,\n avgEntrySize: this.cache.size > 0 ? this.totalSize / this.cache.size : 0\n };\n }\n\n /**\n * Reset statistics\n */\n resetStats(): void {\n this.stats = {\n hits: 0,\n misses: 0,\n sets: 0,\n evictions: 0\n };\n }\n\n /**\n * Get all keys\n */\n keys(): string[] {\n return Array.from(this.cache.keys());\n }\n\n /**\n * Get number of entries\n */\n get size(): number {\n return this.cache.size;\n }\n\n /**\n * Destroy cache and stop cleanup\n */\n destroy(): void {\n this.stopCleanup();\n this.clear();\n }\n\n /**\n * Check if entry is expired\n */\n private isExpired(entry: CacheEntry<T>): boolean {\n if (this.config.ttl === 0) return false;\n return Date.now() - entry.timestamp > this.config.ttl;\n }\n\n /**\n * Evict entries if needed to make room\n */\n private evictIfNeeded(newEntrySize: number): void {\n // Evict by entry count\n while (this.cache.size >= this.config.maxEntries) {\n this.evictOldest();\n }\n\n // Evict by size\n if (this.config.maxSize > 0) {\n while (\n this.totalSize + newEntrySize > this.config.maxSize &&\n this.cache.size > 0\n ) {\n this.evictOldest();\n }\n }\n }\n\n /**\n * Evict the oldest (LRU) entry\n */\n private evictOldest(): void {\n const firstKey = this.cache.keys().next().value;\n if (firstKey) {\n const entry = this.cache.get(firstKey);\n if (entry) {\n this.totalSize -= entry.size;\n }\n this.cache.delete(firstKey);\n this.stats.evictions++;\n\n if (this.config.debug) {\n logger.debug('Cache eviction (LRU)', {\n key: firstKey,\n entries: this.cache.size,\n totalSize: this.totalSize\n });\n }\n }\n }\n\n /**\n * Estimate size of value in bytes\n */\n private estimateSize(value: T): number {\n // Simple estimation based on JSON serialization\n // This is approximate but good enough for cache management\n try {\n const json = JSON.stringify(value);\n return json.length * 2; // ~2 bytes per character (UTF-16)\n } catch {\n // Fallback for non-serializable objects\n return 1024; // 1KB default\n }\n }\n\n /**\n * Start automatic cleanup timer\n */\n private startCleanup(): void {\n this.cleanupTimer = setInterval(() => {\n this.cleanup();\n }, this.config.cleanupInterval);\n\n // Don't prevent process exit\n if (this.cleanupTimer.unref) {\n this.cleanupTimer.unref();\n }\n }\n\n /**\n * Stop automatic cleanup timer\n */\n private stopCleanup(): void {\n if (this.cleanupTimer) {\n clearInterval(this.cleanupTimer);\n this.cleanupTimer = undefined;\n }\n }\n\n /**\n * Clean up expired entries\n */\n private cleanup(): void {\n const before = this.cache.size;\n let expired = 0;\n\n for (const [key, entry] of this.cache.entries()) {\n if (this.isExpired(entry)) {\n this.delete(key);\n expired++;\n }\n }\n\n if (this.config.debug && expired > 0) {\n logger.debug('Cache cleanup', {\n expired,\n before,\n after: this.cache.size,\n totalSize: this.totalSize\n });\n }\n }\n}\n\n/**\n * Provider response cache with intelligent invalidation\n *\n * Caches provider responses based on content hash to avoid\n * redundant API calls for identical requests.\n */\nexport class ProviderResponseCache {\n private cache: TTLCache<{\n response: string;\n usage?: {\n inputTokens: number;\n outputTokens: number;\n totalTokens: number;\n };\n }>;\n\n constructor(config?: Partial<CacheConfig>) {\n this.cache = new TTLCache({\n maxEntries: config?.maxEntries ?? 100,\n ttl: config?.ttl ?? 300000, // 5 minutes default\n maxSize: config?.maxSize ?? 10 * 1024 * 1024, // 10MB default\n cleanupInterval: config?.cleanupInterval ?? 60000,\n debug: config?.debug ?? false\n });\n }\n\n /**\n * Generate cache key from request parameters\n */\n private getCacheKey(\n provider: string,\n model: string,\n messages: any[],\n options?: Record<string, any>\n ): string {\n const payload = {\n provider,\n model,\n messages,\n options: options ?? {}\n };\n // Use JSON stringify for content-based hashing\n return this.hashString(JSON.stringify(payload));\n }\n\n /**\n * Simple string hash function\n */\n private hashString(str: string): string {\n let hash = 0;\n for (let i = 0; i < str.length; i++) {\n const char = str.charCodeAt(i);\n hash = (hash << 5) - hash + char;\n hash = hash & hash; // Convert to 32bit integer\n }\n return `cache_${Math.abs(hash).toString(36)}`;\n }\n\n /**\n * Get cached response\n */\n get(\n provider: string,\n model: string,\n messages: any[],\n options?: Record<string, any>\n ): { response: string; usage?: any } | undefined {\n const key = this.getCacheKey(provider, model, messages, options);\n return this.cache.get(key);\n }\n\n /**\n * Cache provider response\n */\n set(\n provider: string,\n model: string,\n messages: any[],\n response: string,\n options?: Record<string, any>,\n usage?: any\n ): void {\n const key = this.getCacheKey(provider, model, messages, options);\n this.cache.set(key, { response, usage });\n }\n\n /**\n * Get cache statistics\n */\n getStats(): CacheStats {\n return this.cache.getStats();\n }\n\n /**\n * Clear cache\n */\n clear(): void {\n this.cache.clear();\n }\n\n /**\n * Destroy cache\n */\n destroy(): void {\n this.cache.destroy();\n }\n}\n","/**\n * Path resolution types\n */\n\nexport type PathType =\n | 'agent_workspace'\n | 'user_project'\n | 'system_restricted'\n | 'outside_boundaries';\n\nexport interface PathResolverConfig {\n projectDir: string;\n workingDir: string;\n agentWorkspace: string;\n allowSystemAccess?: boolean;\n}\n\nexport interface PathContext {\n /** Auto-detect project root (priority: .git > package.json > cwd) */\n detectProjectRoot(startDir?: string): Promise<string>;\n\n /** Resolve paths relative to project root */\n resolveProjectPath(relativePath: string): string;\n\n /** Resolve paths relative to working directory */\n resolveWorkingPath(relativePath: string): string;\n\n /** Validate path safety (prevent path traversal) */\n validatePath(path: string, baseDir: string): boolean;\n\n /** Check if path is within allowed boundaries */\n isPathAllowed(path: string): boolean;\n}\n\nexport class PathError extends Error {\n constructor(\n message: string,\n public readonly context?: Record<string, unknown>\n ) {\n super(message);\n this.name = 'PathError';\n }\n}\n","/**\n * Path Resolution Module\n *\n * Handles path resolution for AutomatosX v4.0 with three directory contexts:\n * 1. Project Directory - User's project root (auto-detected)\n * 2. Working Directory - Command execution location\n * 3. Agent Workspace - Agent's isolated workspace\n *\n * @see PRD/16-path-resolution-strategy.md\n */\n\nimport { resolve, dirname, relative, isAbsolute, sep } from 'path';\nimport { findUp } from 'find-up';\nimport type { PathResolverConfig, PathType, PathContext } from '../types/path.js';\nimport { PathError } from '../types/path.js';\n\n/**\n * Check if a path is a Windows-style path (e.g., C:\\, D:\\)\n */\nfunction isWindowsPath(path: string): boolean {\n return /^[a-zA-Z]:[/\\\\]/.test(path);\n}\n\n/**\n * Project root detection\n * Priority: .git > package.json > other markers > fallback to cwd\n */\nexport async function detectProjectRoot(\n startDir: string = process.cwd()\n): Promise<string> {\n // Priority 1: Find .git directory\n const gitDir = await findUp('.git', {\n cwd: startDir,\n type: 'directory'\n });\n if (gitDir) {\n return dirname(gitDir);\n }\n\n // Priority 2: Find package.json\n const pkgJson = await findUp('package.json', {\n cwd: startDir\n });\n if (pkgJson) {\n return dirname(pkgJson);\n }\n\n // Priority 3: Find other project markers\n const markers = [\n 'pyproject.toml', // Python\n 'Cargo.toml', // Rust\n 'go.mod', // Go\n 'pom.xml', // Java/Maven\n 'build.gradle', // Java/Gradle\n '.automatosx' // AutomatosX marker\n ];\n\n for (const marker of markers) {\n const found = await findUp(marker, { cwd: startDir });\n if (found) {\n return dirname(found);\n }\n }\n\n // Priority 4: Fallback to startDir\n return startDir;\n}\n\n/**\n * Path Resolver\n * Provides safe path resolution with boundary validation\n */\nexport class PathResolver implements PathContext {\n private readonly config: PathResolverConfig;\n\n constructor(config: PathResolverConfig) {\n this.config = config;\n }\n\n /**\n * Auto-detect project root\n */\n async detectProjectRoot(startDir?: string): Promise<string> {\n return detectProjectRoot(startDir);\n }\n\n /**\n * Resolve user-provided path\n * - Absolute paths: validated within project\n * - Relative paths: resolved from workingDir\n */\n resolveUserPath(userPath: string): string {\n // Reject Windows paths on non-Windows platforms\n if (process.platform !== 'win32' && isWindowsPath(userPath)) {\n throw new PathError(\n `Windows paths are not supported on ${process.platform}`,\n { path: userPath, type: 'invalid_path' }\n );\n }\n\n // Handle absolute paths\n if (isAbsolute(userPath)) {\n const normalized = resolve(userPath);\n this.validateInProject(normalized);\n return normalized;\n }\n\n // Handle relative paths (relative to workingDir)\n const resolved = resolve(this.config.workingDir, userPath);\n this.validateInProject(resolved);\n return resolved;\n }\n\n /**\n * Resolve paths relative to project root\n */\n resolveProjectPath(relativePath: string): string {\n const resolved = resolve(this.config.projectDir, relativePath);\n this.validateInProject(resolved);\n return resolved;\n }\n\n /**\n * Resolve paths relative to working directory\n */\n resolveWorkingPath(relativePath: string): string {\n const resolved = resolve(this.config.workingDir, relativePath);\n this.validateInProject(resolved);\n return resolved;\n }\n\n /**\n * Resolve agent workspace path\n * - Always within agent workspace\n * - Full read/write access\n */\n resolveWorkspacePath(agentPath: string): string {\n return resolve(this.config.agentWorkspace, agentPath);\n }\n\n /**\n * Validate path is within allowed base directory\n */\n validatePath(path: string, baseDir: string): boolean {\n const normalized = resolve(path);\n const base = resolve(baseDir);\n\n // Check if path starts with baseDir\n // Use platform-specific separator to ensure correct comparison\n const pathWithSep = normalized + sep;\n const baseWithSep = base + sep;\n\n return pathWithSep.startsWith(baseWithSep) || normalized === base;\n }\n\n /**\n * Check if path is within allowed boundaries\n */\n isPathAllowed(path: string): boolean {\n const boundary = this.checkBoundaries(path);\n return boundary === 'agent_workspace' || boundary === 'user_project';\n }\n\n /**\n * Check which boundary a path belongs to\n */\n checkBoundaries(path: string): PathType {\n const normalized = resolve(path);\n\n // Check agent workspace first (more specific)\n if (this.validatePath(normalized, this.config.agentWorkspace)) {\n return 'agent_workspace';\n }\n\n // Check user project\n if (this.validatePath(normalized, this.config.projectDir)) {\n return 'user_project';\n }\n\n // Check system directories (platform-specific)\n const systemDirs = this.getSystemDirs();\n for (const sysDir of systemDirs) {\n if (this.validatePath(normalized, sysDir)) {\n return 'system_restricted';\n }\n }\n\n return 'outside_boundaries';\n }\n\n /**\n * Get relative path from project root\n */\n getRelativeToProject(path: string): string {\n const normalized = resolve(path);\n return relative(this.config.projectDir, normalized);\n }\n\n /**\n * Get relative path from working directory\n */\n getRelativeToWorking(path: string): string {\n const normalized = resolve(path);\n return relative(this.config.workingDir, normalized);\n }\n\n /**\n * Get agents directory path\n */\n getAgentsDirectory(): string {\n return resolve(this.config.projectDir, '.automatosx', 'agents');\n }\n\n /**\n * Get abilities directory path\n */\n getAbilitiesDirectory(): string {\n return resolve(this.config.projectDir, '.automatosx', 'abilities');\n }\n\n /**\n * Validate path is within project boundaries\n * @throws PathError if outside project\n */\n private validateInProject(path: string): void {\n const boundary = this.checkBoundaries(path);\n\n if (boundary === 'outside_boundaries' || boundary === 'system_restricted') {\n throw new PathError('Path outside project directory', {\n path,\n projectDir: this.config.projectDir,\n boundary\n });\n }\n }\n\n /**\n * Get system directories (platform-specific)\n */\n private getSystemDirs(): string[] {\n const platform = process.platform;\n\n if (platform === 'win32') {\n return [\n 'C:\\\\Windows',\n 'C:\\\\Program Files',\n 'C:\\\\Program Files (x86)'\n ];\n } else {\n return ['/etc', '/proc', '/sys', '/var', '/usr'];\n }\n }\n}\n","/**\n * BaseProvider - Abstract base class for all AI providers\n *\n * Provides common functionality:\n * - Rate limiting with token bucket algorithm\n * - Exponential backoff retry logic\n * - Health monitoring and circuit breaker\n * - Cost tracking and estimation\n * - Error categorization\n */\n\nimport type {\n Provider,\n ProviderConfig,\n ProviderCapabilities,\n ExecutionRequest,\n ExecutionResponse,\n HealthStatus,\n RateLimitStatus,\n Cost,\n UsageStats,\n EmbeddingOptions,\n RetryConfig\n} from '../types/provider.js';\nimport { logger } from '../utils/logger.js';\nimport { ProviderResponseCache } from '../core/cache.js';\n\nexport abstract class BaseProvider implements Provider {\n protected config: ProviderConfig;\n protected health: HealthStatus;\n protected usageStats: UsageStats;\n protected rateLimitState: {\n requests: number[]; // timestamps of recent requests\n tokens: number[]; // token usage with timestamps\n concurrentRequests: number;\n };\n protected responseCache: ProviderResponseCache;\n\n constructor(config: ProviderConfig) {\n this.config = config;\n this.health = {\n available: true,\n latencyMs: 0,\n errorRate: 0,\n consecutiveFailures: 0\n };\n this.usageStats = {\n totalRequests: 0,\n totalTokens: 0,\n totalCost: 0,\n averageLatencyMs: 0,\n errorCount: 0\n };\n this.rateLimitState = {\n requests: [],\n tokens: [],\n concurrentRequests: 0\n };\n // Initialize response cache with 5 minute TTL\n this.responseCache = new ProviderResponseCache({\n maxEntries: 100,\n ttl: 300000, // 5 minutes\n maxSize: 10 * 1024 * 1024, // 10MB\n debug: false\n });\n }\n\n // Abstract methods to be implemented by concrete providers\n abstract get version(): string;\n abstract get capabilities(): ProviderCapabilities;\n\n // Name and priority from config\n get name(): string {\n return this.config.name;\n }\n\n get priority(): number {\n return this.config.priority;\n }\n\n protected abstract executeRequest(request: ExecutionRequest): Promise<ExecutionResponse>;\n protected abstract generateEmbeddingInternal(text: string, options?: EmbeddingOptions): Promise<number[]>;\n\n /**\n * Build CLI arguments for execution\n * @param request Execution request containing parameters\n * @returns Array of CLI arguments\n */\n protected abstract buildCLIArgs(request: ExecutionRequest): string[];\n\n /**\n * Check if provider supports a specific parameter\n * @param param Parameter name to check\n * @returns true if parameter is supported\n */\n protected abstract supportsParameter(\n param: 'maxTokens' | 'temperature' | 'topP'\n ): boolean;\n\n // Health & Availability\n async isAvailable(): Promise<boolean> {\n if (!this.config.enabled || !this.health.available) {\n return false;\n }\n\n // In mock mode, always return true (for testing)\n if (process.env.AUTOMATOSX_MOCK_PROVIDERS === 'true') {\n return true;\n }\n\n // Check if CLI command actually exists\n return this.checkCLIAvailability();\n }\n\n /**\n * Check if the CLI command is available in the system\n */\n private async checkCLIAvailability(): Promise<boolean> {\n try {\n const { spawn } = await import('child_process');\n\n return new Promise<boolean>((resolve) => {\n // Try to spawn the command with --version or --help\n const child = spawn(this.config.command, ['--version'], {\n stdio: 'ignore',\n timeout: 5000\n });\n\n let resolved = false;\n\n child.on('close', (code) => {\n if (!resolved) {\n resolved = true;\n // Consider success if exit code is 0 or 1 (some CLIs return 1 for --version)\n resolve(code === 0 || code === 1);\n }\n });\n\n child.on('error', (error: NodeJS.ErrnoException) => {\n if (!resolved) {\n resolved = true;\n // ENOENT means command not found\n if (error.code === 'ENOENT') {\n logger.warn(`CLI command not found: ${this.config.command}`);\n resolve(false);\n } else {\n // Other errors might be temporary\n resolve(true);\n }\n }\n });\n\n // Timeout fallback\n setTimeout(() => {\n if (!resolved) {\n resolved = true;\n child.kill();\n resolve(false);\n }\n }, 5000);\n });\n } catch (error) {\n logger.error(`Error checking CLI availability: ${(error as Error).message}`);\n return false;\n }\n }\n\n async getHealth(): Promise<HealthStatus> {\n return { ...this.health };\n }\n\n // Execution with retry logic\n async execute(request: ExecutionRequest): Promise<ExecutionResponse> {\n if (!await this.isAvailable()) {\n throw new Error(`Provider ${this.name} is not available`);\n }\n\n // Check rate limits\n await this.waitForCapacity();\n\n // Check cache before executing\n const messages = this.requestToMessages(request);\n const cacheOptions = {\n temperature: request.temperature,\n maxTokens: request.maxTokens\n };\n const cached = this.responseCache.get(\n this.name,\n request.model || 'default',\n messages,\n cacheOptions\n );\n\n if (cached) {\n logger.debug('Provider cache hit', {\n provider: this.name,\n model: request.model\n });\n\n // Return cached response (reconstruct ExecutionResponse)\n return {\n content: cached.response,\n model: request.model || 'default',\n tokensUsed: cached.usage || {\n prompt: this.estimateTokens(request.prompt),\n completion: this.estimateTokens(cached.response),\n total: this.estimateTokens(request.prompt) + this.estimateTokens(cached.response)\n },\n latencyMs: 0, // Cached response has no latency\n finishReason: 'stop'\n };\n }\n\n const retryPolicy = this.config.retryPolicy ?? this.getDefaultRetryPolicy();\n let lastError: Error | undefined;\n\n for (let attempt = 1; attempt <= retryPolicy.maxAttempts; attempt++) {\n try {\n // Track concurrent requests\n this.rateLimitState.concurrentRequests++;\n const startTime = Date.now();\n\n const response = await this.executeWithTimeout(request);\n\n // Update metrics\n const latency = Date.now() - startTime;\n this.updateMetrics(response, latency);\n this.health.consecutiveFailures = 0;\n\n // Cache successful response\n this.responseCache.set(\n this.name,\n request.model || 'default',\n messages,\n response.content,\n cacheOptions,\n response.tokensUsed\n );\n\n return response;\n\n } catch (error) {\n lastError = error as Error;\n this.health.consecutiveFailures++;\n this.usageStats.errorCount++;\n\n logger.error(`Provider ${this.name} execution failed (attempt ${attempt})`, {\n error: lastError.message,\n attempt,\n maxAttempts: retryPolicy.maxAttempts\n });\n\n // Check if we should retry\n if (attempt < retryPolicy.maxAttempts && this.shouldRetry(lastError)) {\n const delay = this.getRetryDelay(attempt);\n logger.info(`Retrying after ${delay}ms...`);\n await this.sleep(delay);\n } else {\n break;\n }\n } finally {\n this.rateLimitState.concurrentRequests--;\n }\n }\n\n // All retries failed\n this.updateHealthAfterFailure();\n throw lastError || new Error('Execution failed');\n }\n\n // Embeddings\n async generateEmbedding(text: string, options?: EmbeddingOptions): Promise<number[]> {\n if (!this.capabilities.supportsEmbedding) {\n throw new Error(`Provider ${this.name} does not support embeddings`);\n }\n\n return this.generateEmbeddingInternal(text, options);\n }\n\n // Rate Limiting - Token Bucket Algorithm\n async checkRateLimit(): Promise<RateLimitStatus> {\n const now = Date.now();\n const oneMinuteAgo = now - 60000;\n\n // Clean old entries\n this.rateLimitState.requests = this.rateLimitState.requests.filter(t => t > oneMinuteAgo);\n this.rateLimitState.tokens = this.rateLimitState.tokens.filter(t => t > oneMinuteAgo);\n\n const limits = this.config.rateLimits;\n if (!limits) {\n return {\n hasCapacity: true,\n requestsRemaining: Infinity,\n tokensRemaining: Infinity,\n resetAtMs: now + 60000\n };\n }\n\n const requestsRemaining = limits.maxRequestsPerMinute - this.rateLimitState.requests.length;\n const tokensRemaining = limits.maxTokensPerMinute - this.rateLimitState.tokens.length;\n const concurrentOk = this.rateLimitState.concurrentRequests < limits.maxConcurrentRequests;\n\n return {\n hasCapacity: requestsRemaining > 0 && tokensRemaining > 0 && concurrentOk,\n requestsRemaining,\n tokensRemaining,\n resetAtMs: now + 60000\n };\n }\n\n async waitForCapacity(): Promise<void> {\n const maxWaitMs = 60000; // 1 minute max wait\n const startTime = Date.now();\n\n while (Date.now() - startTime < maxWaitMs) {\n const status = await this.checkRateLimit();\n\n if (status.hasCapacity) {\n // Reserve capacity\n this.rateLimitState.requests.push(Date.now());\n return;\n }\n\n // Wait until reset time\n const waitMs = Math.min(status.resetAtMs - Date.now(), 1000);\n await this.sleep(waitMs);\n }\n\n throw new Error(`Rate limit exceeded for provider ${this.name}`);\n }\n\n // Cost Management (to be overridden by providers with specific pricing)\n async estimateCost(request: ExecutionRequest): Promise<Cost> {\n // Default implementation - providers should override with actual pricing\n const estimatedTokens = this.estimateTokens(request.prompt);\n return {\n estimatedUsd: 0,\n tokensUsed: estimatedTokens\n };\n }\n\n async getUsageStats(): Promise<UsageStats> {\n return { ...this.usageStats };\n }\n\n // Error Handling\n shouldRetry(error: Error): boolean {\n // Default: retry on network errors, rate limits, timeouts\n const retryableErrors = [\n 'ECONNRESET',\n 'ETIMEDOUT',\n 'ENOTFOUND',\n 'rate_limit',\n 'timeout'\n ];\n\n return retryableErrors.some(msg =>\n error.message.toLowerCase().includes(msg.toLowerCase())\n );\n }\n\n getRetryDelay(attempt: number): number {\n const policy = this.config.retryPolicy ?? this.getDefaultRetryPolicy();\n const delay = policy.initialDelayMs * Math.pow(policy.backoffMultiplier, attempt - 1);\n return Math.min(delay, policy.maxDelayMs);\n }\n\n // Protected helper methods\n protected async executeWithTimeout(request: ExecutionRequest): Promise<ExecutionResponse> {\n const timeout = this.config.timeout;\n\n return Promise.race([\n this.executeRequest(request),\n this.createTimeoutPromise(timeout)\n ]);\n }\n\n protected createTimeoutPromise(timeoutMs: number): Promise<never> {\n return new Promise((_, reject) => {\n setTimeout(() => reject(new Error(`Request timeout after ${timeoutMs}ms`)), timeoutMs);\n });\n }\n\n protected updateMetrics(response: ExecutionResponse, latency: number): void {\n this.usageStats.totalRequests++;\n this.usageStats.totalTokens += response.tokensUsed.total;\n\n // Update average latency (running average)\n const totalLatency = this.usageStats.averageLatencyMs * (this.usageStats.totalRequests - 1);\n this.usageStats.averageLatencyMs = (totalLatency + latency) / this.usageStats.totalRequests;\n\n // Update health\n this.health.latencyMs = latency;\n this.health.errorRate = this.usageStats.errorCount / this.usageStats.totalRequests;\n\n // Track tokens for rate limiting\n for (let i = 0; i < response.tokensUsed.total; i++) {\n this.rateLimitState.tokens.push(Date.now());\n }\n }\n\n protected updateHealthAfterFailure(): void {\n // Circuit breaker: disable provider after too many consecutive failures\n if (this.health.consecutiveFailures >= 5) {\n this.health.available = false;\n logger.error(`Provider ${this.name} circuit breaker triggered (5 consecutive failures)`);\n\n // Auto-recover after 60 seconds\n setTimeout(() => {\n this.health.available = true;\n this.health.consecutiveFailures = 0;\n logger.info(`Provider ${this.name} circuit breaker reset`);\n }, 60000);\n }\n }\n\n protected estimateTokens(text: string): number {\n // Rough estimate: ~4 characters per token\n return Math.ceil(text.length / 4);\n }\n\n protected sleep(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n }\n\n /**\n * Convert ExecutionRequest to messages array for cache key generation\n */\n protected requestToMessages(request: ExecutionRequest): any[] {\n const messages: any[] = [];\n\n // Add system message if present\n if (request.systemPrompt) {\n messages.push({\n role: 'system',\n content: request.systemPrompt\n });\n }\n\n // Add user message\n messages.push({\n role: 'user',\n content: request.prompt\n });\n\n // Include context if present\n if (request.context && Object.keys(request.context).length > 0) {\n messages.push({\n role: 'context',\n content: request.context\n });\n }\n\n return messages;\n }\n\n protected getDefaultRetryPolicy(): RetryConfig {\n return {\n maxAttempts: 3,\n initialDelayMs: 1000,\n maxDelayMs: 10000,\n backoffMultiplier: 2\n };\n }\n}\n","/**\n * ClaudeProvider - Anthropic Claude AI Provider\n *\n * Uses Anthropic SDK for Claude models\n */\n\nimport { BaseProvider } from './base-provider.js';\nimport type {\n ProviderConfig,\n ProviderCapabilities,\n ExecutionRequest,\n ExecutionResponse,\n EmbeddingOptions,\n Cost\n} from '../types/provider.js';\n\nexport class ClaudeProvider extends BaseProvider {\n constructor(config: ProviderConfig) {\n super(config);\n }\n\n get version(): string {\n return '1.0.0';\n }\n\n get capabilities(): ProviderCapabilities {\n return {\n supportsStreaming: false,\n supportsEmbedding: false, // Claude doesn't provide embeddings directly\n supportsVision: true,\n maxContextTokens: 200000,\n supportedModels: [\n 'claude-3-5-sonnet-20241022',\n 'claude-3-5-haiku-20241022',\n 'claude-3-opus-20240229',\n 'claude-3-sonnet-20240229',\n 'claude-3-haiku-20240307'\n ]\n };\n }\n\n protected async executeRequest(request: ExecutionRequest): Promise<ExecutionResponse> {\n // For Phase 1, we use CLI-based execution (Claude Code CLI)\n // In future phases, we'll use the official Anthropic SDK\n\n const startTime = Date.now();\n\n try {\n // Build prompt with system prompt if provided\n let fullPrompt = request.prompt;\n if (request.systemPrompt) {\n fullPrompt = `System: ${request.systemPrompt}\\n\\nUser: ${request.prompt}`;\n }\n\n // Execute via CLI - let CLI use its own default model\n const response = await this.executeCLI(fullPrompt, request);\n\n const latency = Date.now() - startTime;\n\n return {\n content: response.content,\n model: request.model || 'claude-default', // CLI decides actual model\n tokensUsed: {\n prompt: this.estimateTokens(fullPrompt),\n completion: this.estimateTokens(response.content),\n total: this.estimateTokens(fullPrompt) + this.estimateTokens(response.content)\n },\n latencyMs: latency,\n finishReason: 'stop'\n };\n } catch (error) {\n throw new Error(`Claude execution failed: ${(error as Error).message}`);\n }\n }\n\n protected async generateEmbeddingInternal(_text: string, _options?: EmbeddingOptions): Promise<number[]> {\n throw new Error('Claude does not support embeddings directly. Use OpenAI or Voyage AI for embeddings.');\n }\n\n override async estimateCost(request: ExecutionRequest): Promise<Cost> {\n // Claude pricing (as of 2024)\n const pricing: Record<string, { input: number; output: number }> = {\n 'claude-3-5-sonnet-20241022': { input: 3.00, output: 15.00 }, // per 1M tokens\n 'claude-3-5-haiku-20241022': { input: 0.80, output: 4.00 },\n 'claude-3-opus-20240229': { input: 15.00, output: 75.00 },\n 'claude-3-sonnet-20240229': { input: 3.00, output: 15.00 },\n 'claude-3-haiku-20240307': { input: 0.25, output: 1.25 }\n };\n\n // Use sonnet pricing as default estimate when model not specified\n const defaultPricing = { input: 3.00, output: 15.00 };\n const modelPricing = request.model ? (pricing[request.model] ?? defaultPricing) : defaultPricing;\n\n const inputTokens = this.estimateTokens(request.prompt);\n const outputTokens = request.maxTokens ?? 4096;\n\n const inputCost = (inputTokens / 1_000_000) * modelPricing.input;\n const outputCost = (outputTokens / 1_000_000) * modelPricing.output;\n\n return {\n estimatedUsd: inputCost + outputCost,\n tokensUsed: inputTokens + outputTokens\n };\n }\n\n // CLI execution helper (Phase 1 implementation)\n private async executeCLI(prompt: string, request: ExecutionRequest): Promise<{ content: string }> {\n // Check if running in production mode (real CLI) or test mode (mock)\n const useMock = process.env.AUTOMATOSX_MOCK_PROVIDERS === 'true';\n\n if (useMock) {\n // Mock mode for testing\n return Promise.resolve({\n content: `[Mock Response from Claude]\\n\\nTask received: ${prompt.substring(0, 100)}...\\n\\nThis is a placeholder response. Set AUTOMATOSX_MOCK_PROVIDERS=false to use real CLI.`\n });\n }\n\n // Real CLI execution\n return this.executeRealCLI(prompt, request);\n }\n\n /**\n * Execute real CLI command via spawn\n *\n * Claude Code CLI syntax: echo \"prompt\" | claude --print\n * Uses --print flag for non-interactive output\n * Prompt is passed via stdin (not as positional argument)\n * Model selection is delegated to CLI's own defaults\n */\n private async executeRealCLI(prompt: string, request: ExecutionRequest): Promise<{ content: string }> {\n const { spawn } = await import('child_process');\n\n return new Promise((resolve, reject) => {\n let stdout = '';\n let stderr = '';\n let hasTimedOut = false;\n\n // Build CLI arguments using the new buildCLIArgs method\n const args = this.buildCLIArgs(request);\n\n // NOTE: Do NOT add prompt as positional argument\n // Claude CLI expects prompt via stdin or --prompt flag\n // We use stdin to avoid command-line length limits\n\n let child: ReturnType<typeof spawn>;\n\n try {\n child = spawn(this.config.command, args, {\n stdio: ['pipe', 'pipe', 'pipe'], // Use pipe for stdin\n env: process.env\n });\n } catch (error) {\n const err = error as NodeJS.ErrnoException;\n if (err.code === 'ENOENT') {\n reject(new Error(\n `Claude CLI not found. Please ensure Claude Code is installed and '${this.config.command}' is in your PATH.\\n` +\n `Install from: https://claude.ai/download`\n ));\n } else {\n reject(new Error(`Failed to start Claude CLI: ${err.message}`));\n }\n return;\n }\n\n // Write prompt to stdin and close it\n // This is how Claude CLI expects to receive the prompt\n try {\n child.stdin?.write(prompt);\n child.stdin?.end();\n } catch (error) {\n reject(new Error(`Failed to write prompt to Claude CLI stdin: ${(error as Error).message}`));\n return;\n }\n\n // v5.0.7: Handle abort signal for proper timeout cancellation\n if (request.signal) {\n request.signal.addEventListener('abort', () => {\n hasTimedOut = true;\n child.kill('SIGTERM');\n // Force kill after 5 seconds if SIGTERM doesn't work\n setTimeout(() => {\n if (!child.killed) {\n child.kill('SIGKILL');\n }\n }, 5000);\n reject(new Error('Execution aborted by timeout'));\n });\n }\n\n // Collect stdout\n child.stdout?.on('data', (data) => {\n stdout += data.toString();\n });\n\n // Collect stderr\n child.stderr?.on('data', (data) => {\n stderr += data.toString();\n });\n\n // Handle process exit\n child.on('close', (code) => {\n if (hasTimedOut) {\n return; // Timeout already handled\n }\n\n if (code !== 0) {\n const errorMsg = stderr || 'No error message';\n\n // Parse common error patterns\n if (errorMsg.toLowerCase().includes('network') ||\n errorMsg.toLowerCase().includes('connection') ||\n errorMsg.toLowerCase().includes('econnrefused') ||\n errorMsg.toLowerCase().includes('enotfound')) {\n reject(new Error(\n `Network connection error: Unable to reach Claude API.\\n` +\n `Please check your internet connection and try again.\\n` +\n `Details: ${errorMsg}`\n ));\n } else if (errorMsg.toLowerCase().includes('authentication') ||\n errorMsg.toLowerCase().includes('unauthorized') ||\n errorMsg.toLowerCase().includes('api key')) {\n reject(new Error(\n `Authentication failed: Please check your Claude API credentials.\\n` +\n `Details: ${errorMsg}`\n ));\n } else if (errorMsg.toLowerCase().includes('rate limit') ||\n errorMsg.toLowerCase().includes('quota')) {\n reject(new Error(\n `Rate limit exceeded: Please wait a moment and try again.\\n` +\n `Details: ${errorMsg}`\n ));\n } else {\n reject(new Error(`Claude CLI exited with code ${code}: ${errorMsg}`));\n }\n } else {\n if (!stdout.trim()) {\n reject(new Error('Claude CLI returned empty response'));\n } else {\n resolve({ content: stdout.trim() });\n }\n }\n });\n\n // Handle process errors\n child.on('error', (error) => {\n const err = error as NodeJS.ErrnoException;\n\n if (err.code === 'ENOENT') {\n reject(new Error(\n `Claude CLI command '${this.config.command}' not found.\\n` +\n `Please install Claude Code from https://claude.ai/download`\n ));\n } else if (err.code === 'EACCES') {\n reject(new Error(\n `Permission denied: Cannot execute '${this.config.command}'.\\n` +\n `Please check file permissions.`\n ));\n } else {\n reject(new Error(`Failed to execute Claude CLI: ${err.message}`));\n }\n });\n\n // Set timeout\n const timeout = setTimeout(() => {\n hasTimedOut = true;\n child.kill('SIGTERM');\n\n // Force kill after 5 seconds if still running\n setTimeout(() => {\n if (child.killed === false) {\n child.kill('SIGKILL');\n }\n }, 5000);\n\n reject(new Error(\n `Request timeout after ${this.config.timeout / 1000} seconds.\\n` +\n `This may be due to:\\n` +\n `- Slow network connection\\n` +\n `- Large request requiring more processing time\\n` +\n `- Claude API being overloaded\\n` +\n `Try again or use --timeout option to increase the limit.`\n ));\n }, this.config.timeout);\n\n child.on('close', () => {\n clearTimeout(timeout);\n });\n });\n }\n\n override shouldRetry(error: Error): boolean {\n // Claude-specific retry logic\n const claudeRetryableErrors = [\n 'overloaded_error',\n 'rate_limit_error',\n 'timeout',\n 'connection_error',\n 'internal_server_error',\n 'network connection error',\n 'econnrefused',\n 'econnreset',\n 'etimedout',\n 'enotfound'\n ];\n\n const message = error.message.toLowerCase();\n const isRetryable = claudeRetryableErrors.some(err => message.includes(err)) || super.shouldRetry(error);\n\n // Don't retry authentication errors or missing CLI\n if (message.includes('authentication') ||\n message.includes('api key') ||\n message.includes('not found') ||\n message.includes('permission denied')) {\n return false;\n }\n\n return isRetryable;\n }\n\n /**\n * Build CLI arguments for Claude Code CLI\n * Currently does not support parameter passing via CLI\n * Claude Code uses its own optimal defaults\n */\n protected buildCLIArgs(request: ExecutionRequest): string[] {\n // Claude Code CLI uses --print for non-interactive output\n const args: string[] = ['--print'];\n\n // Enable file operation tools (v5.0.6 fix)\n // Allow Read, Write, Edit, and Bash tools for agent operations\n args.push('--allowedTools', 'Read Write Edit Bash Glob Grep');\n\n // Allow access to current working directory and tmp folder\n args.push('--add-dir', process.cwd());\n\n // Claude Code CLI does not support parameter configuration via CLI flags\n // It uses provider-optimized defaults for best results\n //\n // Future implementation (if Claude adds support):\n // if (request.temperature !== undefined) {\n // args.push('--temperature', String(request.temperature));\n // }\n // if (request.maxTokens !== undefined) {\n // args.push('--max-tokens', String(request.maxTokens));\n // }\n\n return args;\n }\n\n /**\n * Check if Claude provider supports a specific parameter\n * Currently all parameters are unsupported via CLI\n */\n protected supportsParameter(\n param: 'maxTokens' | 'temperature' | 'topP'\n ): boolean {\n // Claude Code CLI does not support parameter configuration\n // Uses provider-optimized defaults instead\n return false;\n }\n}\n","/**\n * GeminiProvider - Google Gemini AI Provider\n *\n * Uses Google Generative AI SDK for Gemini models\n */\n\nimport { BaseProvider } from './base-provider.js';\nimport type {\n ProviderConfig,\n ProviderCapabilities,\n ExecutionRequest,\n ExecutionResponse,\n EmbeddingOptions,\n Cost\n} from '../types/provider.js';\n\nexport class GeminiProvider extends BaseProvider {\n constructor(config: ProviderConfig) {\n super(config);\n }\n\n get version(): string {\n return '1.0.0';\n }\n\n get capabilities(): ProviderCapabilities {\n return {\n supportsStreaming: false,\n supportsEmbedding: true,\n supportsVision: true,\n maxContextTokens: 1000000, // Gemini 1.5 Pro has 1M context window\n supportedModels: [\n 'gemini-2.0-flash-exp',\n 'gemini-1.5-pro',\n 'gemini-1.5-flash',\n 'gemini-1.0-pro'\n ]\n };\n }\n\n protected async executeRequest(request: ExecutionRequest): Promise<ExecutionResponse> {\n const startTime = Date.now();\n\n try {\n // Build prompt with system prompt if provided\n let fullPrompt = request.prompt;\n if (request.systemPrompt) {\n fullPrompt = `${request.systemPrompt}\\n\\n${request.prompt}`;\n }\n\n // Execute via CLI - let CLI use its own default model\n const response = await this.executeCLI(fullPrompt, request);\n\n const latency = Date.now() - startTime;\n\n return {\n content: response.content,\n model: request.model || 'gemini-default', // CLI decides actual model\n tokensUsed: {\n prompt: this.estimateTokens(fullPrompt),\n completion: this.estimateTokens(response.content),\n total: this.estimateTokens(fullPrompt) + this.estimateTokens(response.content)\n },\n latencyMs: latency,\n finishReason: 'stop'\n };\n } catch (error) {\n throw new Error(`Gemini execution failed: ${(error as Error).message}`);\n }\n }\n\n protected async generateEmbeddingInternal(_text: string, options?: EmbeddingOptions): Promise<number[]> {\n try {\n // NOTE: Legacy mock implementation for testing purposes only\n // Vector search was removed in v4.11.0 (switched to SQLite FTS5)\n // This method is retained for interface compatibility and test coverage\n // Gemini supports embeddings via embedding-001 model (not implemented in mock)\n const dimensions = options?.dimensions || 768;\n return Array(dimensions).fill(0).map(() => Math.random());\n } catch (error) {\n throw new Error(`Gemini embedding generation failed: ${(error as Error).message}`);\n }\n }\n\n override async estimateCost(request: ExecutionRequest): Promise<Cost> {\n // Gemini pricing (as of 2024)\n const pricing: Record<string, { input: number; output: number }> = {\n 'gemini-2.0-flash-exp': { input: 0, output: 0 }, // Free during preview\n 'gemini-1.5-pro': { input: 3.50, output: 10.50 }, // per 1M tokens\n 'gemini-1.5-flash': { input: 0.35, output: 1.05 },\n 'gemini-1.0-pro': { input: 0.50, output: 1.50 }\n };\n\n // Use gemini-2.0-flash-exp pricing as default estimate when model not specified\n const defaultPricing = { input: 0, output: 0 };\n const modelPricing = request.model ? (pricing[request.model] ?? defaultPricing) : defaultPricing;\n\n const inputTokens = this.estimateTokens(request.prompt);\n const outputTokens = request.maxTokens ?? 4096;\n\n const inputCost = (inputTokens / 1_000_000) * modelPricing.input;\n const outputCost = (outputTokens / 1_000_000) * modelPricing.output;\n\n return {\n estimatedUsd: inputCost + outputCost,\n tokensUsed: inputTokens + outputTokens\n };\n }\n\n // CLI execution helper (Phase 1 implementation)\n private async executeCLI(prompt: string, request: ExecutionRequest): Promise<{ content: string }> {\n // Check if running in production mode (real CLI) or test mode (mock)\n const useMock = process.env.AUTOMATOSX_MOCK_PROVIDERS === 'true';\n\n if (useMock) {\n // Mock mode for testing\n return Promise.resolve({\n content: `[Mock Response from Gemini]\\n\\nTask received: ${prompt.substring(0, 100)}...\\n\\nThis is a placeholder response. Set AUTOMATOSX_MOCK_PROVIDERS=false to use real CLI.`\n });\n }\n\n // Real CLI execution\n return this.executeRealCLI(prompt, request);\n }\n\n /**\n * Execute real CLI command via spawn\n *\n * Gemini CLI syntax: gemini \"prompt\"\n * Model selection is delegated to CLI's own defaults\n */\n private async executeRealCLI(prompt: string, request: ExecutionRequest): Promise<{ content: string }> {\n const { spawn } = await import('child_process');\n\n return new Promise((resolve, reject) => {\n let stdout = '';\n let stderr = '';\n let hasTimedOut = false;\n\n // Build CLI arguments for Gemini CLI\n // Note: Gemini CLI uses positional prompt, not --prompt flag\n // Do NOT pass --model - let CLI use its own default\n const args: string[] = [];\n\n // Enable file operation tools (v5.0.6 fix)\n // This allows agents to create, modify, and delete files\n args.push('--approval-mode', 'auto_edit');\n\n // Add prompt as positional argument (not as flag)\n args.push(prompt);\n\n // Note: Gemini CLI doesn't support temperature and maxTokens via CLI flags\n // These parameters are configured in the Gemini settings.json instead\n\n // Spawn the CLI process\n const child = spawn(this.config.command, args, {\n stdio: ['pipe', 'pipe', 'pipe'],\n env: process.env\n });\n\n // v5.0.7: Handle abort signal for proper timeout cancellation\n if (request.signal) {\n request.signal.addEventListener('abort', () => {\n hasTimedOut = true;\n child.kill('SIGTERM');\n // Force kill after 5 seconds if SIGTERM doesn't work\n setTimeout(() => {\n if (!child.killed) {\n child.kill('SIGKILL');\n }\n }, 5000);\n reject(new Error('Execution aborted by timeout'));\n });\n }\n\n // Collect stdout\n child.stdout?.on('data', (data) => {\n stdout += data.toString();\n });\n\n // Collect stderr\n child.stderr?.on('data', (data) => {\n stderr += data.toString();\n });\n\n // Handle process exit\n child.on('close', (code) => {\n if (hasTimedOut) {\n return; // Timeout already handled\n }\n if (code !== 0) {\n reject(new Error(`Gemini CLI exited with code ${code}: ${stderr}`));\n } else {\n resolve({ content: stdout.trim() });\n }\n });\n\n // Handle process errors\n child.on('error', (error) => {\n reject(new Error(`Failed to spawn Gemini CLI: ${error.message}`));\n });\n\n // Set timeout\n const timeout = setTimeout(() => {\n child.kill('SIGTERM');\n reject(new Error('Gemini CLI execution timeout'));\n }, this.config.timeout);\n\n child.on('close', () => {\n clearTimeout(timeout);\n });\n });\n }\n\n override shouldRetry(error: Error): boolean {\n // Gemini-specific retry logic\n const geminiRetryableErrors = [\n 'resource_exhausted',\n 'unavailable',\n 'deadline_exceeded',\n 'internal',\n 'rate_limit'\n ];\n\n const message = error.message.toLowerCase();\n return geminiRetryableErrors.some(err => message.includes(err)) || super.shouldRetry(error);\n }\n\n /**\n * Build CLI arguments for Gemini CLI\n * Currently does not support parameter passing via CLI\n *\n * @see https://github.com/google-gemini/gemini-cli/issues/5280\n * Blocked: Waiting for Gemini CLI to add support for maxTokens and temperature parameters\n * When implemented, this method will be updated to support parameter passing\n */\n protected buildCLIArgs(_request: ExecutionRequest): string[] {\n const args: string[] = [];\n\n // Gemini CLI currently does not support parameter passing\n // Parameters would need to be configured in ~/.gemini/settings.json\n //\n // Future implementation (when Gemini CLI adds support):\n // if (_request.temperature !== undefined) {\n // args.push('--temperature', String(_request.temperature));\n // }\n // if (_request.maxTokens !== undefined) {\n // args.push('--max-tokens', String(_request.maxTokens));\n // }\n // if (_request.topP !== undefined) {\n // args.push('--top-p', String(_request.topP));\n // }\n\n return args;\n }\n\n /**\n * Check if Gemini provider supports a specific parameter\n * Currently all parameters are unsupported\n * See: https://github.com/google-gemini/gemini-cli/issues/5280\n */\n protected supportsParameter(\n _param: 'maxTokens' | 'temperature' | 'topP'\n ): boolean {\n // Gemini CLI does not support any parameters yet\n // This will return true once Issue #5280 is resolved\n return false;\n }\n}\n","/**\n * OpenAIProvider - OpenAI AI Provider\n *\n * Uses OpenAI API for GPT models\n */\n\nimport { BaseProvider } from './base-provider.js';\nimport type {\n ProviderConfig,\n ProviderCapabilities,\n ExecutionRequest,\n ExecutionResponse,\n EmbeddingOptions,\n Cost\n} from '../types/provider.js';\n\nexport class OpenAIProvider extends BaseProvider {\n constructor(config: ProviderConfig) {\n super(config);\n }\n\n get version(): string {\n return '1.0.0';\n }\n\n get capabilities(): ProviderCapabilities {\n return {\n supportsStreaming: false,\n supportsEmbedding: true,\n supportsVision: true,\n maxContextTokens: 128000, // GPT-4 Turbo/GPT-4o has 128k context\n supportedModels: [\n 'gpt-4o',\n 'gpt-4o-mini',\n 'gpt-4-turbo',\n 'gpt-4',\n 'gpt-3.5-turbo',\n 'o1-preview',\n 'o1-mini'\n ]\n };\n }\n\n protected async executeRequest(request: ExecutionRequest): Promise<ExecutionResponse> {\n const startTime = Date.now();\n\n try {\n // Build prompt with system prompt if provided\n let fullPrompt = request.prompt;\n if (request.systemPrompt) {\n fullPrompt = `System: ${request.systemPrompt}\\n\\nUser: ${request.prompt}`;\n }\n\n // Execute via CLI - let CLI use its own default model\n const response = await this.executeCLI(fullPrompt, request);\n\n const latency = Date.now() - startTime;\n\n return {\n content: response.content,\n model: request.model || 'openai-default', // CLI decides actual model\n tokensUsed: {\n prompt: this.estimateTokens(fullPrompt),\n completion: this.estimateTokens(response.content),\n total: this.estimateTokens(fullPrompt) + this.estimateTokens(response.content)\n },\n latencyMs: latency,\n finishReason: 'stop'\n };\n } catch (error) {\n throw new Error(`OpenAI execution failed: ${(error as Error).message}`);\n }\n }\n\n protected async generateEmbeddingInternal(_text: string, options?: EmbeddingOptions): Promise<number[]> {\n try {\n // NOTE: Legacy mock implementation for testing purposes only\n // Vector search was removed in v4.11.0 (switched to SQLite FTS5)\n // This method is retained for interface compatibility and test coverage\n // OpenAI supports embeddings via text-embedding models (not implemented in mock)\n const dimensions = options?.dimensions || 1536;\n return Array(dimensions).fill(0).map(() => Math.random());\n } catch (error) {\n throw new Error(`OpenAI embedding generation failed: ${(error as Error).message}`);\n }\n }\n\n override async estimateCost(request: ExecutionRequest): Promise<Cost> {\n // OpenAI pricing (as of 2024)\n const pricing: Record<string, { input: number; output: number }> = {\n 'gpt-4o': { input: 2.50, output: 10.00 }, // per 1M tokens\n 'gpt-4o-mini': { input: 0.15, output: 0.60 },\n 'gpt-4-turbo': { input: 10.00, output: 30.00 },\n 'gpt-4': { input: 30.00, output: 60.00 },\n 'gpt-3.5-turbo': { input: 0.50, output: 1.50 },\n 'o1-preview': { input: 15.00, output: 60.00 },\n 'o1-mini': { input: 3.00, output: 12.00 }\n };\n\n // Use gpt-4o pricing as default estimate when model not specified\n const defaultPricing = { input: 2.50, output: 10.00 };\n const modelPricing = request.model ? (pricing[request.model] ?? defaultPricing) : defaultPricing;\n\n const inputTokens = this.estimateTokens(request.prompt);\n const outputTokens = request.maxTokens ?? 4096;\n\n const inputCost = (inputTokens / 1_000_000) * modelPricing.input;\n const outputCost = (outputTokens / 1_000_000) * modelPricing.output;\n\n return {\n estimatedUsd: inputCost + outputCost,\n tokensUsed: inputTokens + outputTokens\n };\n }\n\n // CLI execution helper (Phase 1 implementation)\n private async executeCLI(prompt: string, request: ExecutionRequest): Promise<{ content: string }> {\n // Check if running in production mode (real CLI) or test mode (mock)\n const useMock = process.env.AUTOMATOSX_MOCK_PROVIDERS === 'true';\n\n if (useMock) {\n // Mock mode for testing\n return Promise.resolve({\n content: `[Mock Response from OpenAI]\\n\\nTask received: ${prompt.substring(0, 100)}...\\n\\nThis is a placeholder response. Set AUTOMATOSX_MOCK_PROVIDERS=false to use real CLI.`\n });\n }\n\n // Real CLI execution\n return this.executeRealCLI(prompt, request);\n }\n\n /**\n * Execute real CLI command via spawn\n *\n * Codex CLI syntax: codex exec [OPTIONS] [PROMPT]\n * Model and other parameters are passed via -c (config override) or specific flags\n */\n private async executeRealCLI(prompt: string, request: ExecutionRequest): Promise<{ content: string }> {\n const { spawn } = await import('child_process');\n\n return new Promise((resolve, reject) => {\n let stdout = '';\n let stderr = '';\n let hasTimedOut = false;\n\n // Build CLI arguments using the new buildCLIArgs method\n const args = this.buildCLIArgs(request);\n\n // Add prompt as last argument\n args.push(prompt);\n\n // Spawn the CLI process\n const child = spawn(this.config.command, args, {\n stdio: ['pipe', 'pipe', 'pipe'],\n env: process.env\n });\n\n // v5.0.7: Handle abort signal for proper timeout cancellation\n if (request.signal) {\n request.signal.addEventListener('abort', () => {\n hasTimedOut = true;\n child.kill('SIGTERM');\n // Force kill after 5 seconds if SIGTERM doesn't work\n setTimeout(() => {\n if (!child.killed) {\n child.kill('SIGKILL');\n }\n }, 5000);\n reject(new Error('Execution aborted by timeout'));\n });\n }\n\n // Collect stdout\n child.stdout?.on('data', (data) => {\n stdout += data.toString();\n });\n\n // Collect stderr\n child.stderr?.on('data', (data) => {\n stderr += data.toString();\n });\n\n // Handle process exit\n child.on('close', (code) => {\n if (hasTimedOut) {\n return; // Already rejected by timeout\n }\n\n if (code !== 0) {\n reject(new Error(`OpenAI CLI exited with code ${code}: ${stderr}`));\n } else {\n resolve({ content: stdout.trim() });\n }\n });\n\n // Handle process errors\n child.on('error', (error) => {\n if (!hasTimedOut) {\n reject(new Error(`Failed to spawn OpenAI CLI: ${error.message}`));\n }\n });\n\n // Set timeout\n const timeout = setTimeout(() => {\n hasTimedOut = true;\n child.kill('SIGTERM');\n\n // Give it a moment to terminate gracefully\n setTimeout(() => {\n if (!child.killed) {\n child.kill('SIGKILL');\n }\n }, 1000);\n\n reject(new Error(`OpenAI CLI execution timeout after ${this.config.timeout}ms`));\n }, this.config.timeout);\n\n child.on('close', () => {\n clearTimeout(timeout);\n });\n });\n }\n\n override shouldRetry(error: Error): boolean {\n // OpenAI-specific retry logic\n const openaiRetryableErrors = [\n 'rate_limit',\n 'server_error',\n 'timeout',\n 'connection_error',\n 'service_unavailable',\n 'internal_error'\n ];\n\n const message = error.message.toLowerCase();\n return openaiRetryableErrors.some(err => message.includes(err)) || super.shouldRetry(error);\n }\n\n /**\n * Build CLI arguments for OpenAI Codex CLI\n * Supports: maxTokens, temperature\n */\n protected buildCLIArgs(request: ExecutionRequest): string[] {\n const args: string[] = ['exec'];\n\n // Add model if specified\n if (request.model) {\n args.push('-m', request.model);\n }\n\n // Add temperature via config override if specified\n if (request.temperature !== undefined) {\n args.push('-c', `temperature=${request.temperature}`);\n }\n\n // Add max tokens via config override if specified\n if (request.maxTokens !== undefined) {\n args.push('-c', `max_tokens=${request.maxTokens}`);\n }\n\n return args;\n }\n\n /**\n * Check if OpenAI provider supports a specific parameter\n * OpenAI Codex CLI supports maxTokens and temperature via -c flags\n */\n protected supportsParameter(\n param: 'maxTokens' | 'temperature' | 'topP'\n ): boolean {\n // OpenAI Codex CLI supports maxTokens and temperature\n return param === 'maxTokens' || param === 'temperature';\n }\n}\n","/**\n * AutomatosX CLI Entry Point\n *\n * Provides command-line interface for AutomatosX agent orchestration platform.\n *\n * Global Options:\n * - --debug: Enable debug mode with verbose output\n * - --quiet: Suppress non-essential output\n * - --config: Path to custom config file\n */\n\nimport yargs from 'yargs';\nimport { hideBin } from 'yargs/helpers';\nimport { createRequire } from 'module';\nimport { logger, setLogLevel } from '../utils/logger.js';\nimport { globalTracker } from '../utils/performance.js';\n\n// Read version from version.json (single source of truth)\nconst require = createRequire(import.meta.url);\nlet VERSION = 'unknown';\ntry {\n // Try to load from same directory first (when built to dist/)\n const versionData = require('../version.json');\n VERSION = versionData.version || 'unknown';\n} catch (err) {\n // Fallback: try parent directory (development mode)\n try {\n const versionData = require('../../version.json');\n VERSION = versionData.version || 'unknown';\n } catch (err2) {\n // Final fallback: package.json\n try {\n const packageJson = require('../../package.json');\n VERSION = packageJson.version || 'unknown';\n } catch (err3) {\n logger.debug('Version file not found, using fallback');\n }\n }\n}\n\n// Import all commands directly (lazy loading broke command options)\nimport { configCommand } from './commands/config.js';\nimport { initCommand } from './commands/init.js';\nimport { listCommand } from './commands/list.js';\nimport { mcpCommand } from './commands/mcp.js';\nimport { memoryCommand } from './commands/memory.js';\nimport { runCommand } from './commands/run.js';\nimport { sessionCommand } from './commands/session.js';\nimport { statusCommand } from './commands/status.js';\nimport { updateCommand } from './commands/update.js';\nimport { workspaceCommand } from './commands/workspace.js';\nimport { agentCommand } from './commands/agent/index.js';\n\n// Mark CLI startup\nglobalTracker.mark('cli_start');\n\n// Parse CLI arguments\nglobalTracker.mark('yargs_parse_start');\nconst argv = await yargs(hideBin(process.argv))\n .scriptName('automatosx')\n .usage('$0 <command> [options]')\n .usage('\\nAI Agent Orchestration Platform')\n .example('$0 init', 'Initialize project')\n .example('$0 agent create backend --template developer', 'Create agent from template')\n .example('$0 agent list', 'List all agents')\n .example('$0 run assistant \"Hello\"', 'Run assistant agent')\n .example('$0 session create \"Build API\" backend', 'Create multi-agent session')\n .example('$0 session list', 'List all sessions')\n .example('$0 workspace stats', 'Show workspace statistics')\n .example('$0 list agents', 'List available agents')\n .example('$0 memory search \"topic\"', 'Search memory')\n .example('$0 config --list', 'View configuration')\n .example('$0 mcp', 'Start MCP server for Claude Code')\n .example('$0 update', 'Update to latest version')\n\n // Global options\n .option('debug', {\n alias: 'd',\n type: 'boolean',\n description: 'Enable debug mode with verbose output',\n global: true\n })\n .option('quiet', {\n alias: 'q',\n type: 'boolean',\n description: 'Suppress non-essential output',\n global: true\n })\n .option('config', {\n alias: 'c',\n type: 'string',\n description: 'Path to custom config file',\n global: true\n })\n\n // Commands\n .command(initCommand)\n .command(agentCommand)\n .command(listCommand)\n .command(runCommand)\n .command(sessionCommand)\n .command(workspaceCommand)\n .command(configCommand)\n .command(statusCommand)\n .command(memoryCommand)\n .command(mcpCommand)\n .command(updateCommand)\n\n // Configuration\n .demandCommand(1, 'You must provide a command. Run --help for usage.')\n .help()\n .version(VERSION)\n .alias('h', 'help')\n .alias('v', 'version')\n .strict()\n .wrap(Math.min(120, yargs().terminalWidth()))\n .parse();\n\nglobalTracker.mark('yargs_parse_end');\nglobalTracker.measure('yargs_parsing', 'yargs_parse_start', 'yargs_parse_end');\n\n// Apply global options\nglobalTracker.mark('options_setup_start');\n\nif (argv.debug) {\n setLogLevel('debug');\n process.env.AUTOMATOSX_DEBUG = 'true';\n logger.debug('Debug mode enabled', {\n node: process.version,\n platform: process.platform,\n arch: process.arch,\n cwd: process.cwd(),\n argv: process.argv.slice(2)\n });\n}\n\nif (argv.quiet) {\n setLogLevel('error');\n process.env.AUTOMATOSX_QUIET = 'true';\n}\n\n// Store global options in process.env for access by commands\nif (argv.config) {\n process.env.AUTOMATOSX_CONFIG_PATH = argv.config as string;\n logger.debug('Custom config path set', { path: argv.config });\n}\n\n// Log startup info in debug mode\nif (argv.debug) {\n logger.debug('AutomatosX CLI started', {\n version: VERSION,\n command: argv._[0],\n options: {\n debug: argv.debug,\n quiet: argv.quiet,\n config: argv.config\n }\n });\n}\n\nglobalTracker.mark('options_setup_end');\nglobalTracker.measure('options_setup', 'options_setup_start', 'options_setup_end');\n\n// Mark CLI ready\nglobalTracker.mark('cli_ready');\nglobalTracker.measure('cli_startup', 'cli_start', 'cli_ready');\n\n// Output profile report if enabled\nif (globalTracker.isEnabled() && argv.debug) {\n console.error('\\n' + globalTracker.generateReport() + '\\n');\n}\n","/**\n * Performance Tracking Utilities\n *\n * Provides lightweight performance measurement and profiling tools.\n */\n\nexport interface PerformanceMark {\n name: string;\n timestamp: number;\n duration?: number;\n}\n\nexport interface PerformanceMetrics {\n marks: PerformanceMark[];\n totalDuration: number;\n breakdown: Record<string, number>;\n}\n\n/**\n * Performance tracker for profiling application startup and operations\n */\nexport class PerformanceTracker {\n private marks: Map<string, number> = new Map();\n private measurements: PerformanceMark[] = [];\n private startTime: number;\n private enabled: boolean;\n\n constructor(enabled: boolean = false) {\n this.enabled = enabled || process.env.AUTOMATOSX_PROFILE === 'true';\n this.startTime = performance.now();\n }\n\n /**\n * Mark a point in time\n */\n mark(name: string): void {\n if (!this.enabled) return;\n\n const timestamp = performance.now() - this.startTime;\n this.marks.set(name, timestamp);\n }\n\n /**\n * Measure duration between two marks\n */\n measure(name: string, startMark: string, endMark?: string): number | undefined {\n if (!this.enabled) return undefined;\n\n const start = this.marks.get(startMark);\n if (!start) return undefined;\n\n const end = endMark ? this.marks.get(endMark) : performance.now() - this.startTime;\n if (end === undefined) return undefined;\n\n const duration = end - start;\n this.measurements.push({\n name,\n timestamp: start,\n duration\n });\n\n return duration;\n }\n\n /**\n * Get all measurements\n */\n getMeasurements(): PerformanceMark[] {\n return [...this.measurements];\n }\n\n /**\n * Get performance metrics summary\n */\n getMetrics(): PerformanceMetrics {\n const totalDuration = performance.now() - this.startTime;\n const breakdown: Record<string, number> = {};\n\n for (const measurement of this.measurements) {\n if (measurement.duration !== undefined) {\n breakdown[measurement.name] = measurement.duration;\n }\n }\n\n return {\n marks: this.getMeasurements(),\n totalDuration,\n breakdown\n };\n }\n\n /**\n * Generate formatted report\n */\n generateReport(): string {\n const metrics = this.getMetrics();\n const lines: string[] = [];\n\n lines.push('=== Performance Profile ===');\n lines.push(`Total Duration: ${metrics.totalDuration.toFixed(2)}ms`);\n lines.push('');\n lines.push('Breakdown:');\n\n // Sort by duration (descending)\n const sorted = Object.entries(metrics.breakdown)\n .sort(([, a], [, b]) => b - a);\n\n for (const [name, duration] of sorted) {\n const percentage = (duration / metrics.totalDuration * 100).toFixed(1);\n lines.push(` ${name.padEnd(40)} ${duration.toFixed(2)}ms (${percentage}%)`);\n }\n\n return lines.join('\\n');\n }\n\n /**\n * Clear all measurements\n */\n clear(): void {\n this.marks.clear();\n this.measurements = [];\n this.startTime = performance.now();\n }\n\n /**\n * Check if profiling is enabled\n */\n isEnabled(): boolean {\n return this.enabled;\n }\n}\n\n/**\n * Global performance tracker instance\n */\nexport const globalTracker = new PerformanceTracker(\n process.env.AUTOMATOSX_PROFILE === 'true'\n);\n\n/**\n * Measure async function execution time\n */\nexport async function measureAsync<T>(\n name: string,\n fn: () => Promise<T>\n): Promise<T> {\n if (!globalTracker.isEnabled()) {\n return fn();\n }\n\n const startMark = `${name}_start`;\n const endMark = `${name}_end`;\n\n globalTracker.mark(startMark);\n try {\n const result = await fn();\n globalTracker.mark(endMark);\n globalTracker.measure(name, startMark, endMark);\n return result;\n } catch (error) {\n globalTracker.mark(endMark);\n globalTracker.measure(`${name}_error`, startMark, endMark);\n throw error;\n }\n}\n\n/**\n * Measure sync function execution time\n */\nexport function measureSync<T>(\n name: string,\n fn: () => T\n): T {\n if (!globalTracker.isEnabled()) {\n return fn();\n }\n\n const startMark = `${name}_start`;\n const endMark = `${name}_end`;\n\n globalTracker.mark(startMark);\n try {\n const result = fn();\n globalTracker.mark(endMark);\n globalTracker.measure(name, startMark, endMark);\n return result;\n } catch (error) {\n globalTracker.mark(endMark);\n globalTracker.measure(`${name}_error`, startMark, endMark);\n throw error;\n }\n}\n","/**\n * Config Command - Manage AutomatosX configuration\n */\n\nimport type { CommandModule } from 'yargs';\nimport { access } from 'fs/promises';\nimport { resolve } from 'path';\nimport { constants } from 'fs';\nimport chalk from 'chalk';\nimport { DEFAULT_CONFIG } from '../../types/config.js';\nimport type { AutomatosXConfig } from '../../types/config.js';\nimport { logger } from '../../utils/logger.js';\nimport { printError } from '../../utils/error-formatter.js';\nimport { printSuccess, formatInfo, formatKeyValue, formatWarning } from '../../utils/message-formatter.js';\nimport { validateConfig, formatValidationErrors } from '../../utils/config-validator.js';\nimport { loadConfigFile, saveConfigFile } from '../../core/config.js';\n\ninterface ConfigOptions {\n get?: string;\n set?: string;\n value?: string;\n list?: boolean;\n reset?: boolean;\n validate?: boolean;\n verbose?: boolean;\n}\n\nexport const configCommand: CommandModule<Record<string, unknown>, ConfigOptions> = {\n command: 'config',\n describe: 'Manage AutomatosX configuration',\n\n builder: (yargs) => {\n return yargs\n .option('get', {\n alias: 'g',\n describe: 'Get configuration value',\n type: 'string'\n })\n .option('set', {\n alias: 's',\n describe: 'Set configuration key',\n type: 'string'\n })\n .option('value', {\n describe: 'Value to set',\n type: 'string'\n })\n .option('list', {\n alias: 'l',\n describe: 'List all configuration',\n type: 'boolean',\n default: false\n })\n .option('reset', {\n alias: 'r',\n describe: 'Reset to default configuration',\n type: 'boolean',\n default: false\n })\n .option('validate', {\n describe: 'Validate configuration',\n type: 'boolean',\n default: false\n })\n .option('verbose', {\n describe: 'Show detailed output',\n type: 'boolean',\n default: false\n })\n .example('$0 config --list', 'List all configuration')\n .example('$0 config --get logging.level', 'Get log level')\n .example('$0 config --set logging.level --value debug', 'Set log level to debug')\n .example('$0 config --validate', 'Validate configuration')\n .example('$0 config --reset', 'Reset to default configuration');\n },\n\n handler: async (argv) => {\n try {\n // Debug: Print received arguments (only in debug mode)\n if (process.env.AUTOMATOSX_DEBUG) {\n console.error('[DEBUG] Config handler argv:', {\n config: (argv as any).config,\n c: (argv as any).c,\n all: Object.keys(argv)\n });\n }\n\n // Support multiple config path sources (priority order)\n let configPath: string;\n\n if ((argv as any).config) {\n configPath = (argv as any).config;\n } else if ((argv as any).c) {\n configPath = (argv as any).c;\n } else if (process.env.AUTOMATOSX_CONFIG) {\n configPath = process.env.AUTOMATOSX_CONFIG;\n } else {\n // Check in priority order: project root config, then hidden dir config\n const projectConfig = resolve(process.cwd(), 'automatosx.config.json');\n const hiddenConfig = resolve(process.cwd(), '.automatosx', 'config.json');\n\n const fs = await import('fs');\n if (fs.existsSync(projectConfig)) {\n configPath = projectConfig;\n } else if (fs.existsSync(hiddenConfig)) {\n configPath = hiddenConfig;\n } else {\n // Default to project config (for error message)\n configPath = projectConfig;\n }\n }\n\n if (process.env.AUTOMATOSX_DEBUG) {\n console.error('[DEBUG] Resolved config path:', configPath);\n }\n\n // Check if config exists\n const exists = await checkExists(configPath);\n if (!exists) {\n console.log(chalk.yellow('⚠️ Configuration file not found'));\n console.log(chalk.gray(` Searched at: ${configPath}`));\n console.log(chalk.gray(' Run \"automatosx init\" to create configuration\\n'));\n process.exit(1);\n }\n\n // Load config (supports both YAML and JSON)\n const config = await loadConfigFile(configPath);\n\n // Handle operations\n if (argv.reset) {\n await resetConfig(configPath, argv.verbose || false);\n } else if (argv.validate) {\n await validateConfigFile(config, argv.verbose || false);\n } else if (argv.list) {\n await listConfig(config, argv.verbose || false);\n } else if (argv.get) {\n await getConfig(config, argv.get, argv.verbose || false);\n } else if (argv.set && argv.value !== undefined) {\n await setConfig(configPath, config, argv.set, argv.value, argv.verbose || false);\n } else if (argv.set && argv.value === undefined) {\n console.log(chalk.red('❌ Error: --value is required when using --set\\n'));\n process.exit(1);\n } else {\n // Default: show config path\n console.log(formatInfo('Configuration file:'));\n console.log(chalk.gray(` ${configPath}\\n`));\n }\n\n } catch (error) {\n printError(error, {\n verbose: argv.verbose || false,\n showCode: true,\n showSuggestions: true,\n colors: true\n });\n logger.error('Config command failed', { error: (error as Error).message });\n process.exit(1);\n }\n }\n};\n\n/**\n * Check if file exists\n */\nasync function checkExists(path: string): Promise<boolean> {\n try {\n await access(path, constants.F_OK);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Validate configuration file\n */\nasync function validateConfigFile(\n config: AutomatosXConfig,\n verbose: boolean\n): Promise<void> {\n console.log(chalk.cyan('\\n🔍 Validating configuration...\\n'));\n\n const result = validateConfig(config);\n\n if (result.valid) {\n printSuccess('Configuration is valid');\n\n if (verbose) {\n console.log(chalk.gray('\\nValidation checks passed:'));\n console.log(chalk.gray(' ✓ All required fields present'));\n console.log(chalk.gray(' ✓ All field types correct'));\n console.log(chalk.gray(' ✓ All values within valid ranges'));\n console.log(chalk.gray(' ✓ At least one provider enabled'));\n }\n } else {\n console.log(formatWarning(`Found ${result.errors.length} validation error(s)\\n`));\n console.log(formatValidationErrors(result.errors));\n console.log();\n\n logger.warn('Configuration validation failed', {\n errorCount: result.errors.length,\n errors: result.errors\n });\n\n process.exit(1);\n }\n\n console.log();\n}\n\n/**\n * Reset configuration to defaults\n */\nasync function resetConfig(path: string, verbose: boolean): Promise<void> {\n const config = {\n ...DEFAULT_CONFIG,\n $schema: './schema/config.json',\n version: '5.0.0' // v5.0+ with YAML support\n };\n\n await saveConfigFile(path, config);\n printSuccess('Configuration reset to defaults');\n\n if (verbose) {\n console.log(chalk.gray(`\\nConfig file: ${path}\\n`));\n }\n\n logger.info('Configuration reset', { path });\n}\n\n/**\n * List all configuration\n */\nasync function listConfig(config: AutomatosXConfig, verbose: boolean): Promise<void> {\n console.log(chalk.bold.cyan('\\n📋 AutomatosX Configuration\\n'));\n\n // Providers Section\n console.log(chalk.bold.white('┌─────────────────────────────────────────────────────'));\n console.log(chalk.bold.white('│ ') + chalk.bold.cyan('Providers'));\n console.log(chalk.bold.white('└─────────────────────────────────────────────────────\\n'));\n\n // Provider table\n const providers = Object.entries(config.providers);\n const maxNameLength = Math.max(...providers.map(([name]) => name.length));\n\n providers.forEach(([name, provider]) => {\n const status = provider.enabled ? chalk.green('✓ Enabled ') : chalk.gray('✗ Disabled');\n const paddedName = name.padEnd(maxNameLength + 2);\n console.log(` ${chalk.bold(paddedName)} ${status}`);\n\n if (verbose) {\n console.log(chalk.gray(` │ Priority: ${provider.priority.toString().padStart(2)} │ Timeout: ${provider.timeout}ms`));\n console.log(chalk.gray(` │ Command: ${provider.command}`));\n console.log(chalk.gray(' └─────────────────────────────────────────────────'));\n }\n });\n\n // Memory Section\n console.log(chalk.bold.white('\\n┌─────────────────────────────────────────────────────'));\n console.log(chalk.bold.white('│ ') + chalk.bold.cyan('Memory'));\n console.log(chalk.bold.white('└─────────────────────────────────────────────────────\\n'));\n\n console.log(formatKeyValue(' Max Entries ', chalk.yellow(config.memory.maxEntries.toString())));\n console.log(formatKeyValue(' Persist Path ', chalk.blue(config.memory.persistPath)));\n\n if (verbose) {\n console.log(formatKeyValue(' Auto Cleanup ', config.memory.autoCleanup ? chalk.green('✓ Enabled') : chalk.gray('✗ Disabled')));\n console.log(formatKeyValue(' Cleanup Days ', chalk.yellow(config.memory.cleanupDays.toString())));\n }\n\n // Workspace Section\n console.log(chalk.bold.white('\\n┌─────────────────────────────────────────────────────'));\n console.log(chalk.bold.white('│ ') + chalk.bold.cyan('Workspace'));\n console.log(chalk.bold.white('└─────────────────────────────────────────────────────\\n'));\n\n console.log(formatKeyValue(' Base Path ', chalk.blue(config.workspace.basePath)));\n console.log(formatKeyValue(' Auto Cleanup ', config.workspace.autoCleanup ? chalk.green('✓ Enabled') : chalk.gray('✗ Disabled')));\n\n if (verbose) {\n console.log(formatKeyValue(' Cleanup Days ', chalk.yellow(config.workspace.cleanupDays.toString())));\n console.log(formatKeyValue(' Max Files ', chalk.yellow(config.workspace.maxFiles.toString())));\n }\n\n // Logging Section\n console.log(chalk.bold.white('\\n┌─────────────────────────────────────────────────────'));\n console.log(chalk.bold.white('│ ') + chalk.bold.cyan('Logging'));\n console.log(chalk.bold.white('└─────────────────────────────────────────────────────\\n'));\n\n const levelColor = getLevelColor(config.logging.level);\n console.log(formatKeyValue(' Level ', levelColor(config.logging.level)));\n console.log(formatKeyValue(' Path ', chalk.blue(config.logging.path)));\n\n if (verbose) {\n console.log(formatKeyValue(' Console ', config.logging.console ? chalk.green('✓ Enabled') : chalk.gray('✗ Disabled')));\n }\n\n console.log();\n}\n\n/**\n * Get color for log level\n */\nfunction getLevelColor(level: string): (text: string) => string {\n switch (level) {\n case 'debug':\n return chalk.magenta;\n case 'info':\n return chalk.cyan;\n case 'warn':\n return chalk.yellow;\n case 'error':\n return chalk.red;\n default:\n return chalk.white;\n }\n}\n\n/**\n * Get configuration value\n */\nasync function getConfig(\n config: AutomatosXConfig,\n key: string,\n verbose: boolean\n): Promise<void> {\n const value = getNestedValue(config, key);\n\n if (value === undefined) {\n console.log(chalk.yellow(`⚠️ Configuration key not found: ${key}\\n`));\n process.exit(1);\n }\n\n if (verbose) {\n console.log(formatKeyValue(key, typeof value === 'object' ? JSON.stringify(value, null, 2) : String(value)));\n } else {\n if (typeof value === 'object') {\n console.log(JSON.stringify(value, null, 2));\n } else {\n console.log(value);\n }\n }\n}\n\n/**\n * Set configuration value\n */\nasync function setConfig(\n path: string,\n config: AutomatosXConfig,\n key: string,\n value: string,\n verbose: boolean\n): Promise<void> {\n // Parse value (try JSON first, then use as string)\n let parsedValue: any = value;\n try {\n parsedValue = JSON.parse(value);\n } catch {\n // Use as string if not valid JSON\n }\n\n // Set nested value\n const updated = setNestedValue(config, key, parsedValue);\n\n if (!updated) {\n console.log(chalk.yellow(`⚠️ Configuration key not found: ${key}\\n`));\n process.exit(1);\n }\n\n // Validate updated config\n const validationResult = validateConfig(config);\n if (!validationResult.valid) {\n console.log(chalk.red('\\n❌ Validation failed after update:\\n'));\n console.log(formatValidationErrors(validationResult.errors));\n console.log();\n process.exit(1);\n }\n\n // Save config (supports both YAML and JSON)\n await saveConfigFile(path, config);\n printSuccess(`Configuration updated: ${key} = ${value}`);\n\n if (verbose) {\n console.log(chalk.gray(`\\nConfig file: ${path}`));\n console.log(chalk.gray('Configuration validated successfully\\n'));\n }\n\n logger.info('Configuration updated', { key, value });\n}\n\n/**\n * Get nested object value by dot notation\n */\nfunction getNestedValue(obj: any, path: string): any {\n return path.split('.').reduce((current, key) => current?.[key], obj);\n}\n\n/**\n * Set nested object value by dot notation\n */\nfunction setNestedValue(obj: any, path: string, value: any): boolean {\n const keys = path.split('.');\n const lastKey = keys.pop();\n\n if (!lastKey) return false;\n\n const target = keys.reduce((current, key) => {\n if (current?.[key] === undefined) return undefined;\n return current[key];\n }, obj);\n\n if (target === undefined) return false;\n\n target[lastKey] = value;\n return true;\n}\n","/**\n * Configuration types for AutomatosX v5.0+\n *\n * Complete configuration system with YAML support.\n * All hardcoded values moved to configuration.\n */\n\nimport type { LogLevel } from './logger.js';\n\n// ========================================\n// Provider Configuration\n// ========================================\n\nexport interface ProviderHealthCheckConfig {\n enabled: boolean;\n interval: number; // milliseconds\n timeout: number; // milliseconds\n}\n\n/**\n * Provider default model parameters (v5.0+)\n */\nexport interface ProviderDefaultsConfig {\n maxTokens?: number; // Default max output tokens\n temperature?: number; // Default temperature (0-1)\n topP?: number; // Default top_p (0-1)\n}\n\nexport interface ProviderConfig {\n enabled: boolean;\n priority: number;\n timeout: number;\n command: string;\n healthCheck?: ProviderHealthCheckConfig;\n defaults?: ProviderDefaultsConfig; // v5.0: Default model parameters\n}\n\n// ========================================\n// Execution Configuration\n// ========================================\n\nexport interface RetryConfig {\n maxAttempts: number;\n initialDelay: number; // milliseconds\n maxDelay: number; // milliseconds\n backoffFactor: number; // exponential backoff multiplier\n retryableErrors?: string[]; // error codes/messages that trigger retry (optional, has defaults)\n}\n\nexport interface ExecutionProviderConfig {\n maxWaitMs: number; // max wait time for provider response\n fallbackDelay?: number; // v5.0: delay before trying fallback provider (ms)\n}\n\nexport interface ExecutionConfig {\n defaultTimeout: number; // default execution timeout (ms)\n retry: RetryConfig;\n provider: ExecutionProviderConfig;\n}\n\n// ========================================\n// Orchestration Configuration\n// ========================================\n\nexport interface SessionConfig {\n maxSessions: number; // max sessions in memory\n maxMetadataSize: number; // max metadata size (bytes)\n saveDebounce: number; // save debounce delay (ms)\n cleanupAfterDays: number; // cleanup old sessions after N days\n maxUuidAttempts: number; // max UUID generation attempts\n persistPath: string; // session persistence path\n}\n\nexport interface DelegationConfig {\n maxDepth: number; // max delegation chain depth\n timeout: number; // delegation timeout (ms)\n enableCycleDetection: boolean;\n}\n\nexport interface WorkspaceSystemConfig {\n maxFileSize: number; // max file size (bytes)\n maxFiles: number; // max files per workspace\n cleanupAfterDays: number; // cleanup old workspaces after N days\n autoCleanup: boolean;\n permissions: number; // Unix permissions (e.g., 0o700)\n basePath: string;\n}\n\nexport interface OrchestrationConfigSystem {\n session: SessionConfig;\n delegation: DelegationConfig;\n workspace: WorkspaceSystemConfig;\n}\n\n// ========================================\n// Memory Configuration\n// ========================================\n\nexport interface MemorySearchConfig {\n defaultLimit: number; // default search result limit\n maxLimit: number; // max search result limit\n timeout: number; // search timeout (ms)\n}\n\nexport interface MemoryConfig {\n maxEntries: number;\n persistPath: string;\n autoCleanup: boolean;\n cleanupDays: number;\n search?: MemorySearchConfig; // Optional for backward compatibility\n}\n\n// ========================================\n// Abilities Configuration\n// ========================================\n\nexport interface AbilitiesCacheConfig {\n enabled: boolean;\n maxEntries: number;\n ttl: number; // time to live (ms)\n maxSize: number; // max cache size (bytes)\n cleanupInterval: number; // cleanup interval (ms)\n}\n\nexport interface AbilitiesLimitsConfig {\n maxFileSize: number; // max ability file size (bytes)\n}\n\nexport interface AbilitiesConfig {\n basePath: string;\n fallbackPath: string;\n cache: AbilitiesCacheConfig;\n limits: AbilitiesLimitsConfig;\n}\n\n// ========================================\n// Logging Configuration\n// ========================================\n\nexport interface LoggingRetentionConfig {\n maxSizeBytes: number;\n maxAgeDays: number;\n compress: boolean;\n}\n\nexport interface LoggingConfig {\n level: LogLevel;\n path: string;\n console: boolean;\n retention?: LoggingRetentionConfig; // Optional for backward compatibility\n}\n\n// ========================================\n// Performance Configuration\n// ========================================\n\nexport interface CacheConfig {\n enabled: boolean;\n maxEntries: number;\n ttl: number; // time to live (ms)\n cleanupInterval: number; // cleanup interval (ms)\n}\n\nexport interface ProfileCacheConfig extends CacheConfig {}\n\nexport interface TeamCacheConfig extends CacheConfig {}\n\nexport interface ProviderCacheConfig extends CacheConfig {}\n\nexport interface RateLimitConfig {\n enabled: boolean;\n requestsPerMinute: number;\n burstSize: number;\n}\n\nexport interface PerformanceConfig {\n profileCache: ProfileCacheConfig;\n teamCache: TeamCacheConfig;\n providerCache: ProviderCacheConfig;\n rateLimit: RateLimitConfig;\n}\n\n// ========================================\n// Advanced Configuration\n// ========================================\n\nexport interface EmbeddingConfig {\n timeout: number;\n retryDelay: number;\n dimensions: number;\n maxRetries: number;\n}\n\nexport interface SecurityConfig {\n enablePathValidation: boolean;\n allowedExtensions: string[];\n}\n\nexport interface DevelopmentConfig {\n mockProviders: boolean;\n profileMode: boolean;\n}\n\nexport interface AdvancedConfig {\n embedding?: EmbeddingConfig;\n security: SecurityConfig;\n development: DevelopmentConfig;\n}\n\n// ========================================\n// Integration Configuration (v5.5+ VS Code)\n// ========================================\n\nexport interface VSCodeIntegrationConfig {\n enabled: boolean;\n apiPort: number;\n autoStart: boolean;\n outputPanel: boolean;\n notifications: boolean;\n}\n\nexport interface IntegrationConfig {\n vscode: VSCodeIntegrationConfig;\n}\n\n// ========================================\n// CLI Configuration (Optional)\n// ========================================\n\nexport interface CLIRunConfig {\n defaultMemory: boolean;\n defaultSaveMemory: boolean;\n defaultFormat: 'text' | 'json' | 'markdown';\n defaultVerbose: boolean;\n}\n\nexport interface CLISessionConfig {\n defaultShowAgents: boolean;\n}\n\nexport interface CLIMemoryConfig {\n defaultLimit: number;\n}\n\nexport interface CLIConfig {\n run: CLIRunConfig;\n session: CLISessionConfig;\n memory: CLIMemoryConfig;\n}\n\n// ========================================\n// Legacy (for backward compatibility)\n// ========================================\n\nexport interface WorkspaceConfig {\n basePath: string;\n autoCleanup: boolean;\n cleanupDays: number;\n maxFiles: number;\n}\n\nexport interface OpenAIConfig {\n apiKey?: string;\n model?: string;\n}\n\n// ========================================\n// Main Configuration\n// ========================================\n\nexport interface AutomatosXConfig {\n $schema?: string;\n version?: string;\n providers: Record<string, ProviderConfig>;\n execution?: ExecutionConfig;\n orchestration?: OrchestrationConfigSystem;\n memory: MemoryConfig;\n abilities?: AbilitiesConfig;\n workspace: WorkspaceConfig; // legacy, kept for backward compatibility\n logging: LoggingConfig;\n performance?: PerformanceConfig;\n advanced?: AdvancedConfig;\n integration?: IntegrationConfig;\n cli?: CLIConfig;\n openai?: OpenAIConfig; // legacy\n}\n\n// ========================================\n// Default Configuration\n// ========================================\n\nexport const DEFAULT_CONFIG: AutomatosXConfig = {\n providers: {\n 'claude-code': {\n enabled: true,\n priority: 3,\n timeout: 1500000, // 25 minutes (v5.1.0: increased from 15 min based on user feedback)\n command: 'claude',\n healthCheck: {\n enabled: true,\n interval: 300000, // 5 minutes (v5.0: reduced frequency from 1 min)\n timeout: 5000 // 5 seconds\n }\n // v5.0.5: Removed defaults - let provider CLI use optimal defaults\n // Users can still set provider.defaults in config for specific needs\n },\n 'gemini-cli': {\n enabled: true,\n priority: 2,\n timeout: 1500000, // 25 minutes (v5.1.0: increased from 15 min based on user feedback)\n command: 'gemini',\n healthCheck: {\n enabled: true,\n interval: 300000, // 5 minutes (v5.0: reduced frequency)\n timeout: 5000\n }\n // v5.0.5: Removed defaults - let provider CLI use optimal defaults\n },\n 'openai': {\n enabled: true,\n priority: 1,\n timeout: 1500000, // 25 minutes (v5.1.0: increased from 15 min based on user feedback)\n command: 'codex',\n healthCheck: {\n enabled: true,\n interval: 300000, // 5 minutes (v5.0: reduced frequency)\n timeout: 5000\n }\n // v5.0.5: Removed defaults - let provider CLI use optimal defaults\n }\n },\n\n execution: {\n defaultTimeout: 1500000, // 25 minutes (v5.1.0: increased from 15 min based on user feedback)\n retry: {\n maxAttempts: 3,\n initialDelay: 1000, // 1 second\n maxDelay: 10000, // 10 seconds\n backoffFactor: 2,\n retryableErrors: [\n 'ECONNREFUSED',\n 'ETIMEDOUT',\n 'ENOTFOUND',\n 'rate_limit',\n 'overloaded',\n 'timeout'\n ]\n },\n provider: {\n maxWaitMs: 60000, // 1 minute\n fallbackDelay: 5000 // v5.0: Wait 5s before trying fallback provider\n }\n },\n\n orchestration: {\n session: {\n maxSessions: 100,\n maxMetadataSize: 10240, // 10 KB\n saveDebounce: 1000, // 1 second (v5.0: increased from 100ms to reduce I/O)\n cleanupAfterDays: 7,\n maxUuidAttempts: 100,\n persistPath: '.automatosx/sessions'\n },\n delegation: {\n maxDepth: 2,\n timeout: 1500000, // 25 minutes (v5.1.0: increased from 15 min based on user feedback)\n enableCycleDetection: true\n },\n workspace: {\n maxFileSize: 10485760, // 10 MB\n maxFiles: 100,\n cleanupAfterDays: 7,\n autoCleanup: true,\n permissions: 0o700,\n basePath: '.automatosx/workspaces'\n }\n },\n\n memory: {\n maxEntries: 10000,\n persistPath: '.automatosx/memory',\n autoCleanup: true,\n cleanupDays: 30,\n search: {\n defaultLimit: 10,\n maxLimit: 100,\n timeout: 5000 // 5 seconds\n }\n },\n\n abilities: {\n basePath: '.automatosx/abilities',\n fallbackPath: 'examples/abilities',\n cache: {\n enabled: true,\n maxEntries: 50,\n ttl: 600000, // 10 minutes\n maxSize: 5242880, // 5 MB\n cleanupInterval: 120000 // 2 minutes\n },\n limits: {\n maxFileSize: 524288 // 500 KB\n }\n },\n\n workspace: {\n basePath: '.automatosx/workspaces',\n autoCleanup: true,\n cleanupDays: 7,\n maxFiles: 100\n },\n\n logging: {\n level: 'info',\n path: '.automatosx/logs',\n console: true,\n retention: {\n maxSizeBytes: 104857600, // 100 MB\n maxAgeDays: 30,\n compress: true\n }\n },\n\n performance: {\n profileCache: {\n enabled: true,\n maxEntries: 20,\n ttl: 600000, // 10 minutes (v5.0: standardized from 5 min)\n cleanupInterval: 120000 // 2 minutes (v5.0: standardized)\n },\n teamCache: {\n enabled: true,\n maxEntries: 10,\n ttl: 600000, // 10 minutes\n cleanupInterval: 120000 // 2 minutes\n },\n providerCache: {\n enabled: true, // v5.0: enabled by default (safe for deterministic responses)\n maxEntries: 100,\n ttl: 600000, // 10 minutes (v5.0: reduced from 1 hour)\n cleanupInterval: 120000 // 2 minutes (v5.0: standardized)\n },\n rateLimit: {\n enabled: false, // Keep disabled by default (opt-in)\n requestsPerMinute: 60,\n burstSize: 10\n }\n },\n\n advanced: {\n embedding: {\n timeout: 30000,\n retryDelay: 1000,\n dimensions: 1536,\n maxRetries: 3\n },\n security: {\n enablePathValidation: true,\n allowedExtensions: [\n '.ts', '.js', '.tsx', '.jsx',\n '.py', '.go', '.rs', '.java',\n '.yaml', '.yml', '.json', '.toml',\n '.md', '.txt', '.csv'\n ]\n },\n development: {\n mockProviders: false,\n profileMode: false\n }\n },\n\n integration: {\n vscode: {\n enabled: false, // v5.5+ will enable\n apiPort: 3000,\n autoStart: true,\n outputPanel: true,\n notifications: true\n }\n },\n\n cli: {\n run: {\n defaultMemory: true,\n defaultSaveMemory: true,\n defaultFormat: 'text',\n defaultVerbose: false\n },\n session: {\n defaultShowAgents: true\n },\n memory: {\n defaultLimit: 10\n }\n }\n};\n","/**\n * Error Formatter - Format errors for CLI display\n *\n * Provides consistent, user-friendly error formatting with:\n * - Color-coded output\n * - Error code display\n * - Actionable suggestions\n * - Context information (in debug mode)\n */\n\nimport chalk from 'chalk';\nimport type { BaseError } from './errors.js';\nimport { toBaseError } from './errors.js';\n\nexport interface FormatOptions {\n /**\n * Show verbose error details (stack trace, context)\n */\n verbose?: boolean;\n\n /**\n * Show error code\n */\n showCode?: boolean;\n\n /**\n * Show suggestions\n */\n showSuggestions?: boolean;\n\n /**\n * Use colors in output\n */\n colors?: boolean;\n}\n\n/**\n * Format error for CLI display\n */\nexport function formatError(error: unknown, options: FormatOptions = {}): string {\n const {\n verbose = false,\n showCode = true,\n showSuggestions = true,\n colors = true\n } = options;\n\n const baseError = toBaseError(error);\n const lines: string[] = [];\n\n // Header\n const header = colors\n ? chalk.red.bold('\\n❌ Error')\n : '\\n✗ Error';\n lines.push(header);\n\n // Error code\n if (showCode) {\n const codeText = colors\n ? chalk.gray(`[${baseError.code}]`)\n : `[${baseError.code}]`;\n lines.push(codeText);\n }\n\n // Error message\n const message = colors\n ? chalk.red(baseError.message)\n : baseError.message;\n lines.push('\\n' + message);\n\n // Suggestions\n if (showSuggestions && baseError.suggestions.length > 0) {\n lines.push('');\n const suggestionsHeader = colors\n ? chalk.cyan('💡 Suggestions:')\n : 'Suggestions:';\n lines.push(suggestionsHeader);\n\n baseError.suggestions.forEach((suggestion, i) => {\n const bullet = colors\n ? chalk.gray(` ${i + 1}.`)\n : ` ${i + 1}.`;\n lines.push(`${bullet} ${suggestion}`);\n });\n }\n\n // Context (verbose mode)\n if (verbose && baseError.context) {\n lines.push('');\n const contextHeader = colors\n ? chalk.gray('📋 Context:')\n : 'Context:';\n lines.push(contextHeader);\n\n const contextStr = JSON.stringify(baseError.context, null, 2);\n const formatted = colors\n ? chalk.gray(contextStr.split('\\n').map(line => ' ' + line).join('\\n'))\n : contextStr.split('\\n').map(line => ' ' + line).join('\\n');\n lines.push(formatted);\n }\n\n // Stack trace (verbose mode)\n if (verbose && baseError.stack) {\n lines.push('');\n const stackHeader = colors\n ? chalk.gray('🔍 Stack Trace:')\n : 'Stack Trace:';\n lines.push(stackHeader);\n\n const stack = baseError.stack.split('\\n').slice(1); // Skip first line (message)\n const formatted = colors\n ? chalk.gray(stack.map(line => ' ' + line).join('\\n'))\n : stack.map(line => ' ' + line).join('\\n');\n lines.push(formatted);\n }\n\n // Footer\n lines.push('');\n\n return lines.join('\\n');\n}\n\n/**\n * Format error for JSON output\n */\nexport function formatErrorJSON(error: unknown): string {\n const baseError = toBaseError(error);\n return JSON.stringify(baseError.toJSON(), null, 2);\n}\n\n/**\n * Format error summary (one line)\n */\nexport function formatErrorSummary(error: unknown, options: FormatOptions = {}): string {\n const { colors = true } = options;\n const baseError = toBaseError(error);\n\n const code = colors\n ? chalk.gray(`[${baseError.code}]`)\n : `[${baseError.code}]`;\n\n const message = colors\n ? chalk.red(baseError.message)\n : baseError.message;\n\n return `${code} ${message}`;\n}\n\n/**\n * Format multiple errors as a list\n */\nexport function formatErrorList(errors: unknown[], options: FormatOptions = {}): string {\n const { colors = true } = options;\n const lines: string[] = [];\n\n const header = colors\n ? chalk.red.bold(`\\n❌ ${errors.length} Error(s) Occurred\\n`)\n : `\\n✗ ${errors.length} Error(s) Occurred\\n`;\n lines.push(header);\n\n errors.forEach((error, i) => {\n const baseError = toBaseError(error);\n const num = colors\n ? chalk.gray(`${i + 1}.`)\n : `${i + 1}.`;\n const summary = formatErrorSummary(baseError, { colors });\n lines.push(`${num} ${summary}`);\n });\n\n lines.push('');\n return lines.join('\\n');\n}\n\n/**\n * Print error to console\n */\nexport function printError(error: unknown, options: FormatOptions = {}): void {\n const formatted = formatError(error, options);\n console.error(formatted);\n}\n\n/**\n * Print error summary to console\n */\nexport function printErrorSummary(error: unknown, options: FormatOptions = {}): void {\n const formatted = formatErrorSummary(error, options);\n console.error(formatted);\n}\n\n/**\n * Print multiple errors to console\n */\nexport function printErrorList(errors: unknown[], options: FormatOptions = {}): void {\n const formatted = formatErrorList(errors, options);\n console.error(formatted);\n}\n","/**\n * Error Hierarchy - Structured error classes with error codes\n *\n * All errors extend BaseError with:\n * - Error code (for programmatic handling)\n * - User-friendly message\n * - Actionable suggestions\n * - Additional context\n */\n\nexport enum ErrorCode {\n // Configuration Errors (1000-1099)\n CONFIG_NOT_FOUND = 'E1000',\n CONFIG_INVALID = 'E1001',\n CONFIG_PARSE_ERROR = 'E1002',\n CONFIG_VALIDATION_ERROR = 'E1003',\n\n // Path Errors (1100-1199)\n PATH_TRAVERSAL = 'E1100',\n PATH_NOT_FOUND = 'E1101',\n PATH_ACCESS_DENIED = 'E1102',\n PATH_INVALID = 'E1103',\n\n // Memory Errors (1200-1299)\n MEMORY_NOT_INITIALIZED = 'E1200',\n MEMORY_DATABASE_ERROR = 'E1201',\n MEMORY_EMBEDDING_ERROR = 'E1202',\n MEMORY_QUERY_ERROR = 'E1203',\n MEMORY_IMPORT_ERROR = 'E1204',\n MEMORY_EXPORT_ERROR = 'E1205',\n\n // Provider Errors (1300-1399)\n PROVIDER_NOT_FOUND = 'E1300',\n PROVIDER_UNAVAILABLE = 'E1301',\n PROVIDER_TIMEOUT = 'E1302',\n PROVIDER_RATE_LIMIT = 'E1303',\n PROVIDER_AUTH_ERROR = 'E1304',\n PROVIDER_EXEC_ERROR = 'E1305',\n PROVIDER_NO_AVAILABLE = 'E1306',\n\n // Agent Errors (1400-1499)\n AGENT_PROFILE_NOT_FOUND = 'E1400',\n AGENT_PROFILE_INVALID = 'E1401',\n AGENT_ABILITY_NOT_FOUND = 'E1402',\n AGENT_EXECUTION_ERROR = 'E1403',\n AGENT_CONTEXT_ERROR = 'E1404',\n\n // Validation Errors (1500-1599)\n VALIDATION_FAILED = 'E1500',\n VALIDATION_SCHEMA_ERROR = 'E1501',\n VALIDATION_TYPE_ERROR = 'E1502',\n VALIDATION_CONSTRAINT_ERROR = 'E1503',\n\n // File System Errors (1600-1699)\n FILE_NOT_FOUND = 'E1600',\n FILE_READ_ERROR = 'E1601',\n FILE_WRITE_ERROR = 'E1602',\n FILE_PERMISSION_ERROR = 'E1603',\n\n // CLI Errors (1700-1799)\n CLI_INVALID_COMMAND = 'E1700',\n CLI_INVALID_ARGUMENT = 'E1701',\n CLI_MISSING_ARGUMENT = 'E1702',\n CLI_UNKNOWN_ERROR = 'E1703',\n\n // Unknown/Generic (9999)\n UNKNOWN_ERROR = 'E9999'\n}\n\n/**\n * Base error class with error code and suggestions\n */\nexport class BaseError extends Error {\n public readonly code: ErrorCode;\n public readonly suggestions: string[];\n public readonly context?: Record<string, unknown>;\n public readonly isOperational: boolean;\n\n constructor(\n message: string,\n code: ErrorCode,\n suggestions: string[] = [],\n context?: Record<string, unknown>,\n isOperational: boolean = true\n ) {\n super(message);\n this.name = this.constructor.name;\n this.code = code;\n this.suggestions = suggestions;\n this.context = context;\n this.isOperational = isOperational;\n\n // Maintains proper stack trace\n Error.captureStackTrace(this, this.constructor);\n }\n\n /**\n * Get formatted error message for display\n */\n getFormattedMessage(): string {\n let formatted = `[${this.code}] ${this.message}`;\n\n if (this.suggestions.length > 0) {\n formatted += '\\n\\nSuggestions:';\n this.suggestions.forEach((suggestion, i) => {\n formatted += `\\n ${i + 1}. ${suggestion}`;\n });\n }\n\n return formatted;\n }\n\n /**\n * Get error details as object\n */\n toJSON(): Record<string, unknown> {\n return {\n name: this.name,\n code: this.code,\n message: this.message,\n suggestions: this.suggestions,\n context: this.context,\n isOperational: this.isOperational,\n stack: this.stack\n };\n }\n}\n\n/**\n * Configuration Errors\n */\nexport class ConfigError extends BaseError {\n constructor(\n message: string,\n code: ErrorCode = ErrorCode.CONFIG_INVALID,\n suggestions: string[] = [],\n context?: Record<string, unknown>\n ) {\n super(message, code, suggestions, context);\n }\n\n static notFound(path: string): ConfigError {\n return new ConfigError(\n `Configuration file not found: ${path}`,\n ErrorCode.CONFIG_NOT_FOUND,\n [\n 'Run \"automatosx init\" to create a new configuration',\n 'Specify a custom config path with --config option',\n 'Check that you are in a valid AutomatosX project directory'\n ],\n { path }\n );\n }\n\n static invalid(reason: string, context?: Record<string, unknown>): ConfigError {\n return new ConfigError(\n `Invalid configuration: ${reason}`,\n ErrorCode.CONFIG_INVALID,\n [\n 'Check your automatosx.config.json for syntax errors',\n 'Validate against the schema in documentation',\n 'Reset to default with \"automatosx init --force\"'\n ],\n context\n );\n }\n\n static parseError(error: Error, path: string): ConfigError {\n return new ConfigError(\n `Failed to parse configuration: ${error.message}`,\n ErrorCode.CONFIG_PARSE_ERROR,\n [\n 'Check JSON syntax in your config file',\n 'Use a JSON validator to find syntax errors',\n 'Reset to default with \"automatosx init --force\"'\n ],\n { path, originalError: error.message }\n );\n }\n}\n\n/**\n * Path Errors\n */\nexport class PathError extends BaseError {\n constructor(\n message: string,\n code: ErrorCode = ErrorCode.PATH_INVALID,\n suggestions: string[] = [],\n context?: Record<string, unknown>,\n isOperational: boolean = true\n ) {\n super(message, code, suggestions, context, isOperational);\n }\n\n static traversal(path: string): PathError {\n return new PathError(\n `Path traversal attempt detected: ${path}`,\n ErrorCode.PATH_TRAVERSAL,\n [\n 'Use relative paths within the project directory',\n 'Avoid using \"..\" in file paths',\n 'Check your file path for security issues'\n ],\n { path },\n false // Security error, not operational\n );\n }\n\n static notFound(path: string, type: string = 'Path'): PathError {\n return new PathError(\n `${type} not found: ${path}`,\n ErrorCode.PATH_NOT_FOUND,\n [\n 'Check that the path exists and is accessible',\n 'Verify you have the correct permissions',\n `Use \"automatosx list\" to see available ${type.toLowerCase()}s`\n ],\n { path, type }\n );\n }\n}\n\n/**\n * Memory Errors\n */\nexport class MemoryError extends BaseError {\n constructor(\n message: string,\n code: ErrorCode = ErrorCode.MEMORY_DATABASE_ERROR,\n suggestions: string[] = [],\n context?: Record<string, unknown>\n ) {\n super(message, code, suggestions, context);\n }\n\n static notInitialized(): MemoryError {\n return new MemoryError(\n 'Memory system not initialized',\n ErrorCode.MEMORY_NOT_INITIALIZED,\n [\n 'Run \"automatosx init\" to initialize the project',\n 'Check that .automatosx/memory directory exists',\n 'Verify file permissions on the memory database'\n ]\n );\n }\n\n static embeddingError(reason: string): MemoryError {\n return new MemoryError(\n `Embedding provider error: ${reason}`,\n ErrorCode.MEMORY_EMBEDDING_ERROR,\n [\n 'Set OPENAI_API_KEY environment variable',\n 'Configure embedding provider in automatosx.config.json',\n 'Check your API key is valid and has credits'\n ],\n { reason }\n );\n }\n\n static queryError(query: string, error: Error): MemoryError {\n return new MemoryError(\n `Memory query failed: ${error.message}`,\n ErrorCode.MEMORY_QUERY_ERROR,\n [\n 'Check your query syntax',\n 'Verify memory database is not corrupted',\n 'Try rebuilding memory index with \"automatosx memory rebuild\"'\n ],\n { query, originalError: error.message }\n );\n }\n}\n\n/**\n * Provider Errors\n */\nexport class ProviderError extends BaseError {\n constructor(\n message: string,\n code: ErrorCode = ErrorCode.PROVIDER_UNAVAILABLE,\n suggestions: string[] = [],\n context?: Record<string, unknown>\n ) {\n super(message, code, suggestions, context);\n }\n\n static notFound(providerName: string): ProviderError {\n return new ProviderError(\n `Provider \"${providerName}\" not found`,\n ErrorCode.PROVIDER_NOT_FOUND,\n [\n 'Check available providers with \"automatosx list providers\"',\n 'Verify provider is enabled in automatosx.config.json',\n 'Install the provider CLI if not already installed'\n ],\n { providerName }\n );\n }\n\n static unavailable(providerName: string, reason?: string): ProviderError {\n const msg = reason\n ? `Provider \"${providerName}\" unavailable: ${reason}`\n : `Provider \"${providerName}\" is unavailable`;\n\n return new ProviderError(\n msg,\n ErrorCode.PROVIDER_UNAVAILABLE,\n [\n 'Check that the provider CLI is installed and in your PATH',\n 'Verify provider configuration in automatosx.config.json',\n 'Try running the provider CLI directly to diagnose issues',\n 'Check system status with \"automatosx status --verbose\"'\n ],\n { providerName, reason }\n );\n }\n\n static timeout(providerName: string, timeoutMs: number): ProviderError {\n return new ProviderError(\n `Provider \"${providerName}\" timed out after ${timeoutMs}ms`,\n ErrorCode.PROVIDER_TIMEOUT,\n [\n 'Increase timeout in automatosx.config.json',\n 'Try a simpler prompt or reduce context size',\n 'Check your network connection',\n 'Verify the provider service is responsive'\n ],\n { providerName, timeoutMs }\n );\n }\n\n static noAvailableProviders(): ProviderError {\n return new ProviderError(\n 'No AI providers are available',\n ErrorCode.PROVIDER_NO_AVAILABLE,\n [\n 'Install at least one provider CLI (Claude or Gemini)',\n 'Enable providers in automatosx.config.json',\n 'Check provider status with \"automatosx status\"',\n 'Verify provider CLIs are in your PATH'\n ]\n );\n }\n\n static executionError(providerName: string, error: Error): ProviderError {\n return new ProviderError(\n `Provider \"${providerName}\" execution failed: ${error.message}`,\n ErrorCode.PROVIDER_EXEC_ERROR,\n [\n 'Check that the provider CLI is installed correctly',\n 'Verify you have necessary API keys configured',\n 'Try running the provider CLI directly to diagnose',\n 'Check error logs with --debug flag'\n ],\n { providerName, originalError: error.message }\n );\n }\n}\n\n/**\n * Agent Errors\n */\nexport class AgentError extends BaseError {\n constructor(\n message: string,\n code: ErrorCode = ErrorCode.AGENT_EXECUTION_ERROR,\n suggestions: string[] = [],\n context?: Record<string, unknown>\n ) {\n super(message, code, suggestions, context);\n }\n\n static profileNotFound(agentName: string): AgentError {\n return new AgentError(\n `Agent profile \"${agentName}\" not found`,\n ErrorCode.AGENT_PROFILE_NOT_FOUND,\n [\n 'List available agents with \"automatosx list agents\"',\n 'Create agent profile in .automatosx/agents/',\n 'Check spelling of agent name',\n 'Use example agents from examples/agents/ directory'\n ],\n { agentName }\n );\n }\n\n static profileInvalid(agentName: string, reason: string): AgentError {\n return new AgentError(\n `Agent profile \"${agentName}\" is invalid: ${reason}`,\n ErrorCode.AGENT_PROFILE_INVALID,\n [\n 'Check YAML syntax in agent profile',\n 'Validate required fields (name, provider, abilities)',\n 'Refer to example agents in examples/agents/',\n 'See documentation for agent profile schema'\n ],\n { agentName, reason }\n );\n }\n\n static abilityNotFound(abilityName: string, agentName: string): AgentError {\n return new AgentError(\n `Ability \"${abilityName}\" not found for agent \"${agentName}\"`,\n ErrorCode.AGENT_ABILITY_NOT_FOUND,\n [\n 'List available abilities with \"automatosx list abilities\"',\n 'Create ability file in .automatosx/abilities/',\n 'Check spelling of ability name in agent profile',\n 'Use example abilities from examples/abilities/'\n ],\n { abilityName, agentName }\n );\n }\n\n static executionError(agentName: string, error: Error): AgentError {\n return new AgentError(\n `Agent \"${agentName}\" execution failed: ${error.message}`,\n ErrorCode.AGENT_EXECUTION_ERROR,\n [\n 'Check provider is available and configured',\n 'Verify agent profile is valid',\n 'Try simpler task to isolate the issue',\n 'Run with --debug flag for detailed logs'\n ],\n { agentName, originalError: error.message }\n );\n }\n}\n\n/**\n * Validation Errors\n */\nexport class ValidationError extends BaseError {\n constructor(\n message: string,\n code: ErrorCode = ErrorCode.VALIDATION_FAILED,\n suggestions: string[] = [],\n context?: Record<string, unknown>\n ) {\n super(message, code, suggestions, context);\n }\n\n static failed(field: string, reason: string): ValidationError {\n return new ValidationError(\n `Validation failed for \"${field}\": ${reason}`,\n ErrorCode.VALIDATION_FAILED,\n [\n 'Check the value meets required constraints',\n 'Refer to documentation for valid formats',\n 'Use --help to see expected formats'\n ],\n { field, reason }\n );\n }\n\n static typeError(field: string, expected: string, actual: string): ValidationError {\n return new ValidationError(\n `Type error for \"${field}\": expected ${expected}, got ${actual}`,\n ErrorCode.VALIDATION_TYPE_ERROR,\n [\n `Provide a valid ${expected} value`,\n 'Check your input format',\n 'Use --help for usage examples'\n ],\n { field, expected, actual }\n );\n }\n}\n\n/**\n * Helper function to convert unknown errors to BaseError\n */\nexport function toBaseError(error: unknown): BaseError {\n if (error instanceof BaseError) {\n return error;\n }\n\n if (error instanceof Error) {\n return new BaseError(\n error.message,\n ErrorCode.UNKNOWN_ERROR,\n ['Check error details for more information'],\n { originalError: error.name, stack: error.stack }\n );\n }\n\n return new BaseError(\n String(error),\n ErrorCode.UNKNOWN_ERROR,\n ['An unexpected error occurred']\n );\n}\n\n/**\n * Check if error is operational (expected) or programming error\n */\nexport function isOperationalError(error: unknown): boolean {\n if (error instanceof BaseError) {\n return error.isOperational;\n }\n return false;\n}\n","/**\n * Message Formatter - Standardized CLI messages\n *\n * Provides consistent success/failure/info message formatting\n */\n\nimport chalk from 'chalk';\n\nexport interface MessageOptions {\n /**\n * Use colors\n */\n colors?: boolean;\n\n /**\n * Prefix with icon\n */\n icon?: boolean;\n}\n\n/**\n * Format success message\n */\nexport function formatSuccess(message: string, options: MessageOptions = {}): string {\n const { colors = true, icon = true } = options;\n\n const iconStr = icon ? '✓ ' : '';\n\n return colors\n ? chalk.green(`${iconStr}${message}`)\n : `${iconStr}${message}`;\n}\n\n/**\n * Format failure message\n */\nexport function formatFailure(message: string, options: MessageOptions = {}): string {\n const { colors = true, icon = true } = options;\n\n const iconStr = icon ? '✗ ' : '';\n\n return colors\n ? chalk.red(`${iconStr}${message}`)\n : `${iconStr}${message}`;\n}\n\n/**\n * Format warning message\n */\nexport function formatWarning(message: string, options: MessageOptions = {}): string {\n const { colors = true, icon = true } = options;\n\n const iconStr = icon ? '⚠ ' : '';\n\n return colors\n ? chalk.yellow(`${iconStr}${message}`)\n : `${iconStr}${message}`;\n}\n\n/**\n * Format info message\n */\nexport function formatInfo(message: string, options: MessageOptions = {}): string {\n const { colors = true, icon = true } = options;\n\n const iconStr = icon ? 'ℹ ' : '';\n\n return colors\n ? chalk.blue(`${iconStr}${message}`)\n : `${iconStr}${message}`;\n}\n\n/**\n * Print success message\n */\nexport function printSuccess(message: string, options: MessageOptions = {}): void {\n console.log(formatSuccess(message, options));\n}\n\n/**\n * Print failure message\n */\nexport function printFailure(message: string, options: MessageOptions = {}): void {\n console.log(formatFailure(message, options));\n}\n\n/**\n * Print warning message\n */\nexport function printWarning(message: string, options: MessageOptions = {}): void {\n console.log(formatWarning(message, options));\n}\n\n/**\n * Print info message\n */\nexport function printInfo(message: string, options: MessageOptions = {}): void {\n console.log(formatInfo(message, options));\n}\n\n/**\n * Format step message (for multi-step operations)\n */\nexport function formatStep(step: string, options: MessageOptions = {}): string {\n const { colors = true } = options;\n\n return colors\n ? chalk.gray(` ${step}`)\n : ` ${step}`;\n}\n\n/**\n * Format section header\n */\nexport function formatHeader(header: string, options: MessageOptions = {}): string {\n const { colors = true } = options;\n\n return colors\n ? chalk.bold.cyan(`\\n${header}`)\n : `\\n${header}`;\n}\n\n/**\n * Format key-value pair\n */\nexport function formatKeyValue(key: string, value: string, options: MessageOptions = {}): string {\n const { colors = true } = options;\n\n const formattedKey = colors ? chalk.gray(`${key}:`) : `${key}:`;\n const formattedValue = colors ? chalk.white(value) : value;\n\n return `${formattedKey} ${formattedValue}`;\n}\n\n/**\n * Print completion message with stats\n */\nexport function printCompletion(\n message: string,\n stats: Record<string, string | number>,\n options: MessageOptions = {}\n): void {\n printSuccess(message, options);\n\n Object.entries(stats).forEach(([key, value]) => {\n console.log(`- ${key}: ${value}`);\n });\n}\n","/**\n * Configuration Validator\n *\n * Validates AutomatosX configuration against schema\n */\n\nimport type { AutomatosXConfig, ProviderConfig, MemoryConfig, WorkspaceConfig, LoggingConfig } from '../types/config.js';\nimport type { LogLevel } from '../types/logger.js';\n\nexport interface ValidationError {\n path: string;\n message: string;\n value?: any;\n}\n\nexport interface ValidationResult {\n valid: boolean;\n errors: ValidationError[];\n}\n\n/**\n * Validate entire configuration\n */\nexport function validateConfig(config: any): ValidationResult {\n const errors: ValidationError[] = [];\n\n // Check required top-level fields\n if (!config.providers) {\n errors.push({\n path: 'providers',\n message: 'Required field \"providers\" is missing'\n });\n } else {\n errors.push(...validateProviders(config.providers));\n }\n\n if (!config.memory) {\n errors.push({\n path: 'memory',\n message: 'Required field \"memory\" is missing'\n });\n } else {\n errors.push(...validateMemory(config.memory));\n }\n\n if (!config.workspace) {\n errors.push({\n path: 'workspace',\n message: 'Required field \"workspace\" is missing'\n });\n } else {\n errors.push(...validateWorkspace(config.workspace));\n }\n\n if (!config.logging) {\n errors.push({\n path: 'logging',\n message: 'Required field \"logging\" is missing'\n });\n } else {\n errors.push(...validateLogging(config.logging));\n }\n\n return {\n valid: errors.length === 0,\n errors\n };\n}\n\n/**\n * Validate providers configuration\n */\nfunction validateProviders(providers: any): ValidationError[] {\n const errors: ValidationError[] = [];\n\n if (typeof providers !== 'object' || providers === null) {\n errors.push({\n path: 'providers',\n message: 'Providers must be an object',\n value: providers\n });\n return errors;\n }\n\n const providerNames = Object.keys(providers);\n if (providerNames.length === 0) {\n errors.push({\n path: 'providers',\n message: 'At least one provider must be configured'\n });\n }\n\n // Validate each provider\n for (const [name, provider] of Object.entries(providers)) {\n errors.push(...validateProvider(name, provider as any));\n }\n\n // Check for at least one enabled provider\n const hasEnabledProvider = providerNames.some(name => providers[name]?.enabled === true);\n if (!hasEnabledProvider) {\n errors.push({\n path: 'providers',\n message: 'At least one provider must be enabled'\n });\n }\n\n return errors;\n}\n\n/**\n * Validate single provider configuration\n */\nfunction validateProvider(name: string, provider: any): ValidationError[] {\n const errors: ValidationError[] = [];\n const basePath = `providers.${name}`;\n\n if (typeof provider !== 'object' || provider === null) {\n errors.push({\n path: basePath,\n message: 'Provider must be an object',\n value: provider\n });\n return errors;\n }\n\n // Required fields\n if (typeof provider.enabled !== 'boolean') {\n errors.push({\n path: `${basePath}.enabled`,\n message: 'enabled must be a boolean',\n value: provider.enabled\n });\n }\n\n if (typeof provider.priority !== 'number') {\n errors.push({\n path: `${basePath}.priority`,\n message: 'priority must be a number',\n value: provider.priority\n });\n } else if (provider.priority < 1) {\n errors.push({\n path: `${basePath}.priority`,\n message: 'priority must be >= 1',\n value: provider.priority\n });\n }\n\n if (typeof provider.timeout !== 'number') {\n errors.push({\n path: `${basePath}.timeout`,\n message: 'timeout must be a number',\n value: provider.timeout\n });\n } else if (provider.timeout < 1000) {\n errors.push({\n path: `${basePath}.timeout`,\n message: 'timeout must be >= 1000ms',\n value: provider.timeout\n });\n }\n\n if (typeof provider.command !== 'string') {\n errors.push({\n path: `${basePath}.command`,\n message: 'command must be a string',\n value: provider.command\n });\n } else if (provider.command.trim() === '') {\n errors.push({\n path: `${basePath}.command`,\n message: 'command cannot be empty',\n value: provider.command\n });\n }\n\n return errors;\n}\n\n/**\n * Validate memory configuration\n */\nfunction validateMemory(memory: any): ValidationError[] {\n const errors: ValidationError[] = [];\n const basePath = 'memory';\n\n if (typeof memory !== 'object' || memory === null) {\n errors.push({\n path: basePath,\n message: 'Memory must be an object',\n value: memory\n });\n return errors;\n }\n\n // maxEntries\n if (typeof memory.maxEntries !== 'number') {\n errors.push({\n path: `${basePath}.maxEntries`,\n message: 'maxEntries must be a number',\n value: memory.maxEntries\n });\n } else if (memory.maxEntries < 100) {\n errors.push({\n path: `${basePath}.maxEntries`,\n message: 'maxEntries must be >= 100',\n value: memory.maxEntries\n });\n }\n\n // persistPath\n if (typeof memory.persistPath !== 'string') {\n errors.push({\n path: `${basePath}.persistPath`,\n message: 'persistPath must be a string',\n value: memory.persistPath\n });\n } else if (memory.persistPath.trim() === '') {\n errors.push({\n path: `${basePath}.persistPath`,\n message: 'persistPath cannot be empty',\n value: memory.persistPath\n });\n }\n\n // autoCleanup\n if (typeof memory.autoCleanup !== 'boolean') {\n errors.push({\n path: `${basePath}.autoCleanup`,\n message: 'autoCleanup must be a boolean',\n value: memory.autoCleanup\n });\n }\n\n // cleanupDays\n if (typeof memory.cleanupDays !== 'number') {\n errors.push({\n path: `${basePath}.cleanupDays`,\n message: 'cleanupDays must be a number',\n value: memory.cleanupDays\n });\n } else if (memory.cleanupDays < 1) {\n errors.push({\n path: `${basePath}.cleanupDays`,\n message: 'cleanupDays must be >= 1',\n value: memory.cleanupDays\n });\n }\n\n return errors;\n}\n\n/**\n * Validate workspace configuration\n */\nfunction validateWorkspace(workspace: any): ValidationError[] {\n const errors: ValidationError[] = [];\n const basePath = 'workspace';\n\n if (typeof workspace !== 'object' || workspace === null) {\n errors.push({\n path: basePath,\n message: 'Workspace must be an object',\n value: workspace\n });\n return errors;\n }\n\n // basePath\n if (typeof workspace.basePath !== 'string') {\n errors.push({\n path: `${basePath}.basePath`,\n message: 'basePath must be a string',\n value: workspace.basePath\n });\n } else if (workspace.basePath.trim() === '') {\n errors.push({\n path: `${basePath}.basePath`,\n message: 'basePath cannot be empty',\n value: workspace.basePath\n });\n }\n\n // autoCleanup\n if (typeof workspace.autoCleanup !== 'boolean') {\n errors.push({\n path: `${basePath}.autoCleanup`,\n message: 'autoCleanup must be a boolean',\n value: workspace.autoCleanup\n });\n }\n\n // cleanupDays\n if (typeof workspace.cleanupDays !== 'number') {\n errors.push({\n path: `${basePath}.cleanupDays`,\n message: 'cleanupDays must be a number',\n value: workspace.cleanupDays\n });\n } else if (workspace.cleanupDays < 1) {\n errors.push({\n path: `${basePath}.cleanupDays`,\n message: 'cleanupDays must be >= 1',\n value: workspace.cleanupDays\n });\n }\n\n // maxFiles\n if (typeof workspace.maxFiles !== 'number') {\n errors.push({\n path: `${basePath}.maxFiles`,\n message: 'maxFiles must be a number',\n value: workspace.maxFiles\n });\n } else if (workspace.maxFiles < 1) {\n errors.push({\n path: `${basePath}.maxFiles`,\n message: 'maxFiles must be >= 1',\n value: workspace.maxFiles\n });\n }\n\n return errors;\n}\n\n/**\n * Validate logging configuration\n */\nfunction validateLogging(logging: any): ValidationError[] {\n const errors: ValidationError[] = [];\n const basePath = 'logging';\n\n if (typeof logging !== 'object' || logging === null) {\n errors.push({\n path: basePath,\n message: 'Logging must be an object',\n value: logging\n });\n return errors;\n }\n\n // level\n const validLevels: LogLevel[] = ['debug', 'info', 'warn', 'error'];\n if (typeof logging.level !== 'string') {\n errors.push({\n path: `${basePath}.level`,\n message: 'level must be a string',\n value: logging.level\n });\n } else if (!validLevels.includes(logging.level as LogLevel)) {\n errors.push({\n path: `${basePath}.level`,\n message: `level must be one of: ${validLevels.join(', ')}`,\n value: logging.level\n });\n }\n\n // path\n if (typeof logging.path !== 'string') {\n errors.push({\n path: `${basePath}.path`,\n message: 'path must be a string',\n value: logging.path\n });\n } else if (logging.path.trim() === '') {\n errors.push({\n path: `${basePath}.path`,\n message: 'path cannot be empty',\n value: logging.path\n });\n }\n\n // console\n if (typeof logging.console !== 'boolean') {\n errors.push({\n path: `${basePath}.console`,\n message: 'console must be a boolean',\n value: logging.console\n });\n }\n\n return errors;\n}\n\n/**\n * Format validation errors for display\n */\nexport function formatValidationErrors(errors: ValidationError[]): string {\n if (errors.length === 0) {\n return 'No validation errors';\n }\n\n const lines: string[] = ['Configuration validation failed:\\n'];\n\n errors.forEach((error, index) => {\n lines.push(` ${index + 1}. ${error.path}: ${error.message}`);\n if (error.value !== undefined) {\n lines.push(` Current value: ${JSON.stringify(error.value)}`);\n }\n });\n\n return lines.join('\\n');\n}\n","/**\n * Configuration Management - v5.0+\n *\n * Supports both YAML and JSON configuration files.\n * Priority: .automatosx/config.yaml > automatosx.config.yaml >\n * .automatosx/config.json > automatosx.config.json >\n * ~/.automatosx/config.yaml > ~/.automatosx/config.json >\n * DEFAULT_CONFIG\n */\n\nimport { readFile, writeFile } from 'fs/promises';\nimport { resolve, join, extname } from 'path';\nimport { existsSync } from 'fs';\nimport { load as loadYaml, dump as dumpYaml } from 'js-yaml';\nimport type {\n AutomatosXConfig,\n MemorySearchConfig,\n LoggingRetentionConfig\n} from '../types/config.js';\nimport { DEFAULT_CONFIG } from '../types/config.js';\nimport { ConfigError, ErrorCode } from '../utils/errors.js';\nimport { logger } from '../utils/logger.js';\nimport { deepMerge } from '../utils/deep-merge.js';\nimport {\n VALIDATION_LIMITS,\n isValidRelativePath,\n isValidCommand,\n isValidName,\n isValidExtension,\n isPositiveInteger,\n isNonNegativeInteger,\n inRange\n} from './validation-limits.js';\nimport { TTLCache } from './cache.js';\n\n/**\n * Configuration cache (process-level)\n *\n * Caches loaded configurations by project directory to avoid\n * repeated file system access and parsing on every execution.\n *\n * TTL: 60 seconds (config rarely changes during execution)\n * Max entries: 10 (one per project directory)\n */\nconst configCache = new TTLCache<AutomatosXConfig>({\n ttl: 60000, // 60 seconds\n maxEntries: 10 // Support multiple project directories\n});\n\n/**\n * Load configuration from file with caching\n *\n * Checks cache first to avoid repeated file system access and parsing.\n * Cache TTL: 60 seconds.\n *\n * Priority:\n * 1. .automatosx/config.yaml (highest)\n * 2. .automatosx/config.json\n * 3. automatosx.config.yaml\n * 4. automatosx.config.json\n * 5. ~/.automatosx/config.yaml\n * 6. ~/.automatosx/config.json\n * 7. DEFAULT_CONFIG (fallback)\n */\nexport async function loadConfig(projectDir: string): Promise<AutomatosXConfig> {\n // Check cache first\n const cached = configCache.get(projectDir);\n if (cached) {\n logger.debug('Config loaded from cache', { projectDir });\n return cached;\n }\n\n // Load from file system\n const config = await loadConfigUncached(projectDir);\n\n // Cache the result\n configCache.set(projectDir, config);\n logger.debug('Config cached', { projectDir, ttl: 60000 });\n\n return config;\n}\n\n/**\n * Load configuration from file without caching\n *\n * Internal function used by loadConfig(). Do not call directly unless\n * you specifically need to bypass the cache.\n */\nasync function loadConfigUncached(projectDir: string): Promise<AutomatosXConfig> {\n // Try project configs in priority order\n const projectConfigs = [\n resolve(projectDir, '.automatosx', 'config.yaml'),\n resolve(projectDir, '.automatosx', 'config.json'),\n resolve(projectDir, 'automatosx.config.yaml'),\n resolve(projectDir, 'automatosx.config.json')\n ];\n\n for (const configPath of projectConfigs) {\n if (existsSync(configPath)) {\n logger.debug('Loading config from path', { path: configPath });\n return await loadConfigFile(configPath);\n }\n }\n\n // Try user home config\n const homeDir = process.env.HOME || process.env.USERPROFILE || '';\n const userConfigs = [\n resolve(homeDir, '.automatosx', 'config.yaml'),\n resolve(homeDir, '.automatosx', 'config.json')\n ];\n\n for (const configPath of userConfigs) {\n if (existsSync(configPath)) {\n logger.debug('Loading config from path', { path: configPath });\n return await loadConfigFile(configPath);\n }\n }\n\n // Default config\n logger.debug('Using DEFAULT_CONFIG');\n return DEFAULT_CONFIG;\n}\n\n/**\n * Load and parse config file (supports both YAML and JSON)\n *\n * @param path - Path to config file\n * @returns Parsed and validated configuration\n *\n * @throws {ConfigError} If file not found, parse fails, or validation fails\n */\nexport async function loadConfigFile(path: string): Promise<AutomatosXConfig> {\n try {\n const content = await readFile(path, 'utf-8');\n\n // Security: File size limit (prevent DoS)\n if (content.length > VALIDATION_LIMITS.MAX_CONFIG_FILE_SIZE) {\n throw ConfigError.parseError(\n new Error(`Config file too large (max ${VALIDATION_LIMITS.MAX_CONFIG_FILE_SIZE / 1024}KB, got ${Math.ceil(content.length / 1024)}KB)`),\n path\n );\n }\n\n const ext = extname(path).toLowerCase();\n\n let userConfig: any;\n try {\n if (ext === '.yaml' || ext === '.yml') {\n // Parse YAML\n userConfig = loadYaml(content);\n } else {\n // Parse JSON\n userConfig = JSON.parse(content);\n }\n } catch (parseError) {\n throw ConfigError.parseError(parseError as Error, path);\n }\n\n // Merge with defaults (deep merge)\n const config = mergeConfig(DEFAULT_CONFIG, userConfig);\n\n // Validate merged config\n const validationErrors = validateConfig(config);\n if (validationErrors.length > 0) {\n throw ConfigError.invalid(\n validationErrors.join('; '),\n { path, errors: validationErrors }\n );\n }\n\n logger.info('Config loaded successfully', { path, format: ext });\n return config;\n } catch (error) {\n // Re-throw ConfigError as-is\n if (error instanceof ConfigError) {\n throw error;\n }\n\n // Handle file system errors\n if ((error as any).code === 'ENOENT') {\n throw ConfigError.notFound(path);\n }\n\n if ((error as any).code === 'EACCES') {\n throw new ConfigError(\n `Permission denied reading config: ${path}`,\n ErrorCode.CONFIG_PARSE_ERROR,\n [\n 'Check file permissions',\n 'Run with appropriate user privileges',\n 'Verify the file is accessible'\n ],\n { path, error: (error as Error).message }\n );\n }\n\n // Unknown error\n throw new ConfigError(\n `Failed to load config: ${(error as Error).message}`,\n ErrorCode.CONFIG_PARSE_ERROR,\n ['Check file format and permissions'],\n { path, originalError: (error as Error).message }\n );\n }\n}\n\n/**\n * Deep merge configs (handles all v5.0+ config sections)\n *\n * Uses generic deepMerge utility for consistent, type-safe merging.\n *\n * Merge behavior:\n * - null = explicitly disable feature\n * - undefined = use default value\n * - objects = recursively merge\n * - arrays/primitives = replace\n */\nfunction mergeConfig(\n defaults: AutomatosXConfig,\n user: Partial<AutomatosXConfig>\n): AutomatosXConfig {\n return deepMerge(defaults, user);\n}\n\n/**\n * Validate config (comprehensive validation for v5.0+)\n *\n * Validates all configuration values with:\n * - Security checks (path traversal, command injection, name injection)\n * - Resource limits (prevent DoS attacks)\n * - Type validation (prevent type confusion)\n * - Range validation (min/max values)\n */\nexport function validateConfig(config: AutomatosXConfig): string[] {\n const errors: string[] = [];\n\n // Validate providers\n for (const [name, provider] of Object.entries(config.providers)) {\n // NEW: Validate provider name (prevent name injection)\n if (!isValidName(name)) {\n errors.push(`Provider \"${name}\": name invalid (use alphanumeric, dash, underscore only, max 50 chars)`);\n }\n\n // NEW: Validate command (prevent command injection)\n if (!provider.command) {\n errors.push(`Provider ${name}: command is required`);\n } else if (!isValidCommand(provider.command)) {\n errors.push(`Provider ${name}: command invalid (alphanumeric, dash, underscore only, max 100 chars, no shell metacharacters)`);\n }\n\n // Existing: Min validation + NEW: Max validation\n if (!isPositiveInteger(provider.priority)) {\n errors.push(`Provider ${name}: priority must be a positive integer`);\n }\n\n if (!isPositiveInteger(provider.timeout)) {\n errors.push(`Provider ${name}: timeout must be a positive integer`);\n } else {\n if (provider.timeout < VALIDATION_LIMITS.MIN_TIMEOUT) {\n errors.push(`Provider ${name}: timeout must be >= ${VALIDATION_LIMITS.MIN_TIMEOUT}ms`);\n }\n if (provider.timeout > VALIDATION_LIMITS.MAX_TIMEOUT) {\n errors.push(`Provider ${name}: timeout must be <= ${VALIDATION_LIMITS.MAX_TIMEOUT}ms (1 hour max)`);\n }\n }\n\n if (provider.healthCheck) {\n if (!isPositiveInteger(provider.healthCheck.interval)) {\n errors.push(`Provider ${name}: healthCheck.interval must be a positive integer`);\n } else {\n if (provider.healthCheck.interval < VALIDATION_LIMITS.MIN_INTERVAL) {\n errors.push(`Provider ${name}: healthCheck.interval must be >= ${VALIDATION_LIMITS.MIN_INTERVAL}ms`);\n }\n if (provider.healthCheck.interval > VALIDATION_LIMITS.MAX_TIMEOUT) {\n errors.push(`Provider ${name}: healthCheck.interval must be <= ${VALIDATION_LIMITS.MAX_TIMEOUT}ms`);\n }\n }\n\n if (!isPositiveInteger(provider.healthCheck.timeout)) {\n errors.push(`Provider ${name}: healthCheck.timeout must be a positive integer`);\n } else {\n if (provider.healthCheck.timeout < 100) {\n errors.push(`Provider ${name}: healthCheck.timeout must be >= 100ms`);\n }\n if (provider.healthCheck.timeout > VALIDATION_LIMITS.MAX_TIMEOUT) {\n errors.push(`Provider ${name}: healthCheck.timeout must be <= ${VALIDATION_LIMITS.MAX_TIMEOUT}ms`);\n }\n }\n }\n }\n\n // Validate execution\n if (config.execution) {\n // defaultTimeout\n if (!isPositiveInteger(config.execution.defaultTimeout)) {\n errors.push('Execution: defaultTimeout must be a positive integer');\n } else {\n if (config.execution.defaultTimeout < VALIDATION_LIMITS.MIN_TIMEOUT) {\n errors.push(`Execution: defaultTimeout must be >= ${VALIDATION_LIMITS.MIN_TIMEOUT}ms`);\n }\n if (config.execution.defaultTimeout > VALIDATION_LIMITS.MAX_TIMEOUT) {\n errors.push(`Execution: defaultTimeout must be <= ${VALIDATION_LIMITS.MAX_TIMEOUT}ms (1 hour max)`);\n }\n }\n\n // retry.maxAttempts\n if (!isPositiveInteger(config.execution.retry.maxAttempts)) {\n errors.push('Execution: retry.maxAttempts must be a positive integer');\n } else if (config.execution.retry.maxAttempts > 10) {\n errors.push('Execution: retry.maxAttempts must be <= 10 (reasonable retry limit)');\n }\n\n // retry.initialDelay\n if (!isNonNegativeInteger(config.execution.retry.initialDelay)) {\n errors.push('Execution: retry.initialDelay must be a non-negative integer');\n } else if (config.execution.retry.initialDelay > VALIDATION_LIMITS.MAX_TIMEOUT) {\n errors.push(`Execution: retry.initialDelay must be <= ${VALIDATION_LIMITS.MAX_TIMEOUT}ms`);\n }\n\n // retry.maxDelay\n if (!isPositiveInteger(config.execution.retry.maxDelay)) {\n errors.push('Execution: retry.maxDelay must be a positive integer');\n } else {\n if (config.execution.retry.maxDelay < config.execution.retry.initialDelay) {\n errors.push('Execution: retry.maxDelay must be >= initialDelay');\n }\n if (config.execution.retry.maxDelay > VALIDATION_LIMITS.MAX_TIMEOUT) {\n errors.push(`Execution: retry.maxDelay must be <= ${VALIDATION_LIMITS.MAX_TIMEOUT}ms`);\n }\n }\n\n // retry.backoffFactor\n if (typeof config.execution.retry.backoffFactor !== 'number' || config.execution.retry.backoffFactor < VALIDATION_LIMITS.MIN_BACKOFF_FACTOR) {\n errors.push(`Execution: retry.backoffFactor must be >= ${VALIDATION_LIMITS.MIN_BACKOFF_FACTOR}`);\n } else if (config.execution.retry.backoffFactor > VALIDATION_LIMITS.MAX_BACKOFF_FACTOR) {\n errors.push(`Execution: retry.backoffFactor must be <= ${VALIDATION_LIMITS.MAX_BACKOFF_FACTOR}`);\n }\n\n // provider.maxWaitMs\n if (!isPositiveInteger(config.execution.provider.maxWaitMs)) {\n errors.push('Execution: provider.maxWaitMs must be a positive integer');\n } else {\n if (config.execution.provider.maxWaitMs < VALIDATION_LIMITS.MIN_TIMEOUT) {\n errors.push(`Execution: provider.maxWaitMs must be >= ${VALIDATION_LIMITS.MIN_TIMEOUT}ms`);\n }\n if (config.execution.provider.maxWaitMs > VALIDATION_LIMITS.MAX_TIMEOUT) {\n errors.push(`Execution: provider.maxWaitMs must be <= ${VALIDATION_LIMITS.MAX_TIMEOUT}ms`);\n }\n }\n }\n\n // Validate orchestration\n if (config.orchestration) {\n // session.maxSessions\n if (!isPositiveInteger(config.orchestration.session.maxSessions)) {\n errors.push('Orchestration: session.maxSessions must be a positive integer');\n } else {\n if (config.orchestration.session.maxSessions > VALIDATION_LIMITS.MAX_SESSIONS) {\n errors.push(`Orchestration: session.maxSessions must be <= ${VALIDATION_LIMITS.MAX_SESSIONS}`);\n }\n }\n\n // session.maxMetadataSize\n if (!isPositiveInteger(config.orchestration.session.maxMetadataSize)) {\n errors.push('Orchestration: session.maxMetadataSize must be a positive integer');\n } else {\n if (config.orchestration.session.maxMetadataSize < VALIDATION_LIMITS.MIN_BYTES) {\n errors.push(`Orchestration: session.maxMetadataSize must be >= ${VALIDATION_LIMITS.MIN_BYTES} bytes`);\n }\n if (config.orchestration.session.maxMetadataSize > VALIDATION_LIMITS.MAX_FILE_SIZE) {\n errors.push(`Orchestration: session.maxMetadataSize must be <= ${VALIDATION_LIMITS.MAX_FILE_SIZE} bytes`);\n }\n }\n\n // session.saveDebounce\n if (!isNonNegativeInteger(config.orchestration.session.saveDebounce)) {\n errors.push('Orchestration: session.saveDebounce must be a non-negative integer');\n } else if (config.orchestration.session.saveDebounce > VALIDATION_LIMITS.MAX_TIMEOUT) {\n errors.push(`Orchestration: session.saveDebounce must be <= ${VALIDATION_LIMITS.MAX_TIMEOUT}ms`);\n }\n\n // session.cleanupAfterDays\n if (!isPositiveInteger(config.orchestration.session.cleanupAfterDays)) {\n errors.push('Orchestration: session.cleanupAfterDays must be a positive integer');\n } else if (config.orchestration.session.cleanupAfterDays > 365) {\n errors.push('Orchestration: session.cleanupAfterDays must be <= 365 days');\n }\n\n // session.maxUuidAttempts\n if (!isPositiveInteger(config.orchestration.session.maxUuidAttempts)) {\n errors.push('Orchestration: session.maxUuidAttempts must be a positive integer');\n } else if (config.orchestration.session.maxUuidAttempts > 1000) {\n errors.push('Orchestration: session.maxUuidAttempts must be <= 1000');\n }\n\n // delegation.maxDepth\n if (!isPositiveInteger(config.orchestration.delegation.maxDepth)) {\n errors.push('Orchestration: delegation.maxDepth must be a positive integer');\n } else if (config.orchestration.delegation.maxDepth > 5) {\n errors.push('Orchestration: delegation.maxDepth must be <= 5 (prevent deep chains)');\n }\n\n // delegation.timeout\n if (!isPositiveInteger(config.orchestration.delegation.timeout)) {\n errors.push('Orchestration: delegation.timeout must be a positive integer');\n } else {\n if (config.orchestration.delegation.timeout < VALIDATION_LIMITS.MIN_TIMEOUT) {\n errors.push(`Orchestration: delegation.timeout must be >= ${VALIDATION_LIMITS.MIN_TIMEOUT}ms`);\n }\n if (config.orchestration.delegation.timeout > VALIDATION_LIMITS.MAX_TIMEOUT) {\n errors.push(`Orchestration: delegation.timeout must be <= ${VALIDATION_LIMITS.MAX_TIMEOUT}ms`);\n }\n }\n\n // workspace.maxFileSize\n if (!isPositiveInteger(config.orchestration.workspace.maxFileSize)) {\n errors.push('Orchestration: workspace.maxFileSize must be a positive integer');\n } else {\n if (config.orchestration.workspace.maxFileSize < VALIDATION_LIMITS.MIN_FILE_SIZE) {\n errors.push(`Orchestration: workspace.maxFileSize must be >= ${VALIDATION_LIMITS.MIN_FILE_SIZE} bytes`);\n }\n if (config.orchestration.workspace.maxFileSize > VALIDATION_LIMITS.MAX_FILE_SIZE) {\n errors.push(`Orchestration: workspace.maxFileSize must be <= ${VALIDATION_LIMITS.MAX_FILE_SIZE} bytes (100MB max)`);\n }\n }\n\n // workspace.maxFiles\n if (!isPositiveInteger(config.orchestration.workspace.maxFiles)) {\n errors.push('Orchestration: workspace.maxFiles must be a positive integer');\n } else if (config.orchestration.workspace.maxFiles > 10000) {\n errors.push('Orchestration: workspace.maxFiles must be <= 10000');\n }\n\n // workspace.cleanupAfterDays\n if (!isPositiveInteger(config.orchestration.workspace.cleanupAfterDays)) {\n errors.push('Orchestration: workspace.cleanupAfterDays must be a positive integer');\n } else if (config.orchestration.workspace.cleanupAfterDays > 365) {\n errors.push('Orchestration: workspace.cleanupAfterDays must be <= 365 days');\n }\n }\n\n // Validate memory\n if (!isPositiveInteger(config.memory.maxEntries)) {\n errors.push('Memory: maxEntries must be a positive integer');\n } else {\n if (config.memory.maxEntries > VALIDATION_LIMITS.MAX_ENTRIES) {\n errors.push(`Memory: maxEntries must be <= ${VALIDATION_LIMITS.MAX_ENTRIES} (1 million max)`);\n }\n }\n\n if (!isPositiveInteger(config.memory.cleanupDays)) {\n errors.push('Memory: cleanupDays must be a positive integer');\n } else if (config.memory.cleanupDays > 365) {\n errors.push('Memory: cleanupDays must be <= 365 days');\n }\n\n if (config.memory.search) {\n if (!isPositiveInteger(config.memory.search.defaultLimit)) {\n errors.push('Memory: search.defaultLimit must be a positive integer');\n } else if (config.memory.search.defaultLimit > 1000) {\n errors.push('Memory: search.defaultLimit must be <= 1000');\n }\n\n if (!isPositiveInteger(config.memory.search.maxLimit)) {\n errors.push('Memory: search.maxLimit must be a positive integer');\n } else {\n if (config.memory.search.maxLimit < config.memory.search.defaultLimit) {\n errors.push('Memory: search.maxLimit must be >= defaultLimit');\n }\n if (config.memory.search.maxLimit > 10000) {\n errors.push('Memory: search.maxLimit must be <= 10000');\n }\n }\n\n if (!isPositiveInteger(config.memory.search.timeout)) {\n errors.push('Memory: search.timeout must be a positive integer');\n } else {\n if (config.memory.search.timeout < 100) {\n errors.push('Memory: search.timeout must be >= 100ms');\n }\n if (config.memory.search.timeout > VALIDATION_LIMITS.MAX_TIMEOUT) {\n errors.push(`Memory: search.timeout must be <= ${VALIDATION_LIMITS.MAX_TIMEOUT}ms`);\n }\n }\n }\n\n // Validate abilities\n if (config.abilities) {\n if (!isPositiveInteger(config.abilities.cache.maxEntries)) {\n errors.push('Abilities: cache.maxEntries must be a positive integer');\n } else if (config.abilities.cache.maxEntries > 1000) {\n errors.push('Abilities: cache.maxEntries must be <= 1000');\n }\n\n if (!isPositiveInteger(config.abilities.cache.ttl)) {\n errors.push('Abilities: cache.ttl must be a positive integer');\n } else {\n if (config.abilities.cache.ttl < VALIDATION_LIMITS.MIN_INTERVAL) {\n errors.push(`Abilities: cache.ttl must be >= ${VALIDATION_LIMITS.MIN_INTERVAL}ms`);\n }\n if (config.abilities.cache.ttl > VALIDATION_LIMITS.MAX_TTL) {\n errors.push(`Abilities: cache.ttl must be <= ${VALIDATION_LIMITS.MAX_TTL}ms (24 hours max)`);\n }\n }\n\n if (!isPositiveInteger(config.abilities.cache.maxSize)) {\n errors.push('Abilities: cache.maxSize must be a positive integer');\n } else {\n if (config.abilities.cache.maxSize < VALIDATION_LIMITS.MIN_BYTES) {\n errors.push(`Abilities: cache.maxSize must be >= ${VALIDATION_LIMITS.MIN_BYTES} bytes`);\n }\n if (config.abilities.cache.maxSize > VALIDATION_LIMITS.MAX_CACHE_SIZE) {\n errors.push(`Abilities: cache.maxSize must be <= ${VALIDATION_LIMITS.MAX_CACHE_SIZE} bytes (500MB max)`);\n }\n }\n\n if (!isPositiveInteger(config.abilities.limits.maxFileSize)) {\n errors.push('Abilities: limits.maxFileSize must be a positive integer');\n } else {\n if (config.abilities.limits.maxFileSize < VALIDATION_LIMITS.MIN_FILE_SIZE) {\n errors.push(`Abilities: limits.maxFileSize must be >= ${VALIDATION_LIMITS.MIN_FILE_SIZE} bytes`);\n }\n if (config.abilities.limits.maxFileSize > VALIDATION_LIMITS.MAX_FILE_SIZE) {\n errors.push(`Abilities: limits.maxFileSize must be <= ${VALIDATION_LIMITS.MAX_FILE_SIZE} bytes (100MB max)`);\n }\n }\n }\n\n // Validate workspace (legacy)\n if (!isPositiveInteger(config.workspace.cleanupDays)) {\n errors.push('Workspace: cleanupDays must be a positive integer');\n } else if (config.workspace.cleanupDays > 365) {\n errors.push('Workspace: cleanupDays must be <= 365 days');\n }\n\n if (!isPositiveInteger(config.workspace.maxFiles)) {\n errors.push('Workspace: maxFiles must be a positive integer');\n } else if (config.workspace.maxFiles > 10000) {\n errors.push('Workspace: maxFiles must be <= 10000');\n }\n\n // Validate logging\n if (config.logging?.retention) {\n if (!isPositiveInteger(config.logging.retention.maxSizeBytes)) {\n errors.push('Logging: retention.maxSizeBytes must be a positive integer');\n } else {\n if (config.logging.retention.maxSizeBytes < VALIDATION_LIMITS.MIN_BYTES) {\n errors.push(`Logging: retention.maxSizeBytes must be >= ${VALIDATION_LIMITS.MIN_BYTES} bytes`);\n }\n if (config.logging.retention.maxSizeBytes > VALIDATION_LIMITS.MAX_FILE_SIZE * 10) {\n errors.push('Logging: retention.maxSizeBytes must be <= 1GB');\n }\n }\n\n if (!isPositiveInteger(config.logging.retention.maxAgeDays)) {\n errors.push('Logging: retention.maxAgeDays must be a positive integer');\n } else if (config.logging.retention.maxAgeDays > 365) {\n errors.push('Logging: retention.maxAgeDays must be <= 365 days');\n }\n }\n\n // Validate performance\n if (config.performance) {\n const validateCache = (name: string, cache: any) => {\n if (!isPositiveInteger(cache.maxEntries)) {\n errors.push(`Performance: ${name}.maxEntries must be a positive integer`);\n } else if (cache.maxEntries > 10000) {\n errors.push(`Performance: ${name}.maxEntries must be <= 10000`);\n }\n\n if (!isPositiveInteger(cache.ttl)) {\n errors.push(`Performance: ${name}.ttl must be a positive integer`);\n } else {\n if (cache.ttl < VALIDATION_LIMITS.MIN_INTERVAL) {\n errors.push(`Performance: ${name}.ttl must be >= ${VALIDATION_LIMITS.MIN_INTERVAL}ms`);\n }\n if (cache.ttl > VALIDATION_LIMITS.MAX_TTL) {\n errors.push(`Performance: ${name}.ttl must be <= ${VALIDATION_LIMITS.MAX_TTL}ms (24 hours max)`);\n }\n }\n\n if (!isPositiveInteger(cache.cleanupInterval)) {\n errors.push(`Performance: ${name}.cleanupInterval must be a positive integer`);\n } else {\n if (cache.cleanupInterval < VALIDATION_LIMITS.MIN_INTERVAL) {\n errors.push(`Performance: ${name}.cleanupInterval must be >= ${VALIDATION_LIMITS.MIN_INTERVAL}ms`);\n }\n if (cache.cleanupInterval > VALIDATION_LIMITS.MAX_TIMEOUT) {\n errors.push(`Performance: ${name}.cleanupInterval must be <= ${VALIDATION_LIMITS.MAX_TIMEOUT}ms`);\n }\n }\n };\n\n validateCache('profileCache', config.performance.profileCache);\n validateCache('teamCache', config.performance.teamCache);\n validateCache('providerCache', config.performance.providerCache);\n\n if (config.performance.rateLimit.enabled) {\n if (!isPositiveInteger(config.performance.rateLimit.requestsPerMinute)) {\n errors.push('Performance: rateLimit.requestsPerMinute must be a positive integer');\n } else if (config.performance.rateLimit.requestsPerMinute > 1000) {\n errors.push('Performance: rateLimit.requestsPerMinute must be <= 1000');\n }\n\n if (!isPositiveInteger(config.performance.rateLimit.burstSize)) {\n errors.push('Performance: rateLimit.burstSize must be a positive integer');\n } else if (config.performance.rateLimit.burstSize > 100) {\n errors.push('Performance: rateLimit.burstSize must be <= 100');\n }\n }\n }\n\n // Validate advanced\n if (config.advanced) {\n if (config.advanced.embedding) {\n if (!isPositiveInteger(config.advanced.embedding.timeout)) {\n errors.push('Advanced: embedding.timeout must be a positive integer');\n } else {\n if (config.advanced.embedding.timeout < VALIDATION_LIMITS.MIN_TIMEOUT) {\n errors.push(`Advanced: embedding.timeout must be >= ${VALIDATION_LIMITS.MIN_TIMEOUT}ms`);\n }\n if (config.advanced.embedding.timeout > VALIDATION_LIMITS.MAX_TIMEOUT) {\n errors.push(`Advanced: embedding.timeout must be <= ${VALIDATION_LIMITS.MAX_TIMEOUT}ms`);\n }\n }\n\n if (!isPositiveInteger(config.advanced.embedding.dimensions)) {\n errors.push('Advanced: embedding.dimensions must be a positive integer');\n } else if (config.advanced.embedding.dimensions > 10000) {\n errors.push('Advanced: embedding.dimensions must be <= 10000');\n }\n\n if (!isNonNegativeInteger(config.advanced.embedding.maxRetries)) {\n errors.push('Advanced: embedding.maxRetries must be a non-negative integer');\n } else if (config.advanced.embedding.maxRetries > 10) {\n errors.push('Advanced: embedding.maxRetries must be <= 10');\n }\n }\n }\n\n // Validate integration\n if (config.integration) {\n if (config.integration.vscode.enabled) {\n if (config.integration.vscode.apiPort < VALIDATION_LIMITS.MIN_PORT || config.integration.vscode.apiPort > VALIDATION_LIMITS.MAX_PORT) {\n errors.push(`Integration: vscode.apiPort must be between ${VALIDATION_LIMITS.MIN_PORT} and ${VALIDATION_LIMITS.MAX_PORT}`);\n }\n }\n }\n\n // NEW: Validate all path fields (prevent path traversal)\n const pathFields = [\n { name: 'Memory: persistPath', value: config.memory.persistPath },\n { name: 'Logging: path', value: config.logging.path },\n { name: 'Abilities: basePath', value: config.abilities?.basePath },\n { name: 'Abilities: fallbackPath', value: config.abilities?.fallbackPath },\n { name: 'Orchestration: session.persistPath', value: config.orchestration?.session.persistPath },\n { name: 'Orchestration: workspace.basePath', value: config.orchestration?.workspace.basePath },\n { name: 'Workspace: basePath', value: config.workspace.basePath }\n ];\n\n for (const { name, value } of pathFields) {\n if (value && typeof value === 'string' && !isValidRelativePath(value)) {\n errors.push(`${name} must be a relative path within project (no ../, no absolute paths)`);\n }\n }\n\n // NEW: Validate security.allowedExtensions\n if (config.advanced?.security?.allowedExtensions) {\n if (!Array.isArray(config.advanced.security.allowedExtensions)) {\n errors.push('Security: allowedExtensions must be an array');\n } else {\n if (config.advanced.security.allowedExtensions.length > VALIDATION_LIMITS.MAX_ARRAY_LENGTH) {\n errors.push(`Security: allowedExtensions too many items (max ${VALIDATION_LIMITS.MAX_ARRAY_LENGTH})`);\n }\n\n for (const ext of config.advanced.security.allowedExtensions) {\n if (typeof ext !== 'string') {\n errors.push(`Security: allowedExtensions must contain only strings`);\n break;\n }\n if (!isValidExtension(ext)) {\n errors.push(`Security: invalid extension \"${ext}\" (must be alphanumeric with leading dot, max 10 chars)`);\n }\n }\n }\n }\n\n // NEW: Validate execution.retry.retryableErrors (type and length)\n if (config.execution?.retry?.retryableErrors) {\n if (!Array.isArray(config.execution.retry.retryableErrors)) {\n errors.push('Execution: retry.retryableErrors must be an array');\n } else if (config.execution.retry.retryableErrors.length > VALIDATION_LIMITS.MAX_ARRAY_LENGTH) {\n errors.push(`Execution: retry.retryableErrors too many items (max ${VALIDATION_LIMITS.MAX_ARRAY_LENGTH})`);\n }\n }\n\n return errors;\n}\n\n/**\n * Save configuration to file (supports both YAML and JSON)\n *\n * Format is auto-detected from file extension:\n * - .yaml or .yml → YAML format\n * - .json or other → JSON format\n *\n * @param path - Path to config file\n * @param config - Configuration object to save\n *\n * @throws {ConfigError} If validation fails or write fails\n */\nexport async function saveConfigFile(\n path: string,\n config: AutomatosXConfig\n): Promise<void> {\n try {\n // Validate config before saving\n const validationErrors = validateConfig(config);\n if (validationErrors.length > 0) {\n throw ConfigError.invalid(\n validationErrors.join('; '),\n { path, errors: validationErrors }\n );\n }\n\n const ext = extname(path).toLowerCase();\n let content: string;\n\n if (ext === '.yaml' || ext === '.yml') {\n // Serialize to YAML with comments\n content = dumpYaml(config, {\n indent: 2,\n lineWidth: 120,\n noRefs: true,\n sortKeys: false\n });\n } else {\n // Serialize to JSON with indentation\n content = JSON.stringify(config, null, 2);\n }\n\n // Write to file\n await writeFile(path, content, 'utf-8');\n\n logger.info('Config saved successfully', { path, format: ext });\n } catch (error) {\n // Re-throw ConfigError as-is\n if (error instanceof ConfigError) {\n throw error;\n }\n\n // Handle file system errors\n if ((error as any).code === 'EACCES') {\n throw new ConfigError(\n `Permission denied writing config: ${path}`,\n ErrorCode.CONFIG_PARSE_ERROR,\n [\n 'Check file permissions',\n 'Run with appropriate user privileges',\n 'Verify the directory is writable'\n ],\n { path, error: (error as Error).message }\n );\n }\n\n // Unknown error\n throw new ConfigError(\n `Failed to save config: ${(error as Error).message}`,\n ErrorCode.CONFIG_PARSE_ERROR,\n ['Check file path and permissions'],\n { path, originalError: (error as Error).message }\n );\n }\n}\n","/**\n * Deep Merge Utility\n *\n * Provides type-safe deep merging of configuration objects with proper handling\n * of null values (explicit disable), undefined values (use defaults), and arrays (replace).\n */\n\n/**\n * Deep merge two objects with proper null/undefined handling\n *\n * Behavior:\n * - `user === null` or `user === undefined` → returns defaults\n * - `user.key === null` → feature disabled (result.key = undefined)\n * - `user.key === undefined` → use default (result.key = defaults.key)\n * - `user.key === object` → recursively merge with defaults.key\n * - `user.key === primitive/array` → replace defaults.key\n *\n * @param defaults - Default configuration object\n * @param user - User-provided partial configuration\n * @returns Merged configuration with user overrides\n *\n * @example\n * ```typescript\n * const defaults = {\n * memory: {\n * maxEntries: 10000,\n * search: { defaultLimit: 10 }\n * }\n * };\n *\n * const user = {\n * memory: {\n * maxEntries: 5000,\n * search: null // Disable search\n * }\n * };\n *\n * const result = deepMerge(defaults, user);\n * // {\n * // memory: {\n * // maxEntries: 5000,\n * // search: undefined // Disabled\n * // }\n * // }\n * ```\n */\nexport function deepMerge<T extends object>(\n defaults: T,\n user: Partial<T> | undefined | null\n): T {\n // Handle null/undefined user config\n if (user === null || user === undefined) {\n return defaults;\n }\n\n // Start with shallow copy of defaults\n const result = { ...defaults };\n\n // Merge user values\n for (const key in user) {\n const userValue = user[key];\n\n // Explicit null = disable feature (set to undefined)\n if (userValue === null) {\n result[key] = undefined as any;\n continue;\n }\n\n // Skip undefined (use default)\n if (userValue === undefined) {\n continue;\n }\n\n const defaultValue = defaults[key];\n\n // Recursively merge nested objects\n if (\n typeof userValue === 'object' &&\n typeof defaultValue === 'object' &&\n !Array.isArray(userValue) &&\n !Array.isArray(defaultValue) &&\n userValue !== null &&\n defaultValue !== null\n ) {\n result[key] = deepMerge(defaultValue, userValue as any);\n } else {\n // Replace primitives and arrays\n result[key] = userValue as any;\n }\n }\n\n return result;\n}\n\n/**\n * Type-safe helper to check if a value is a plain object\n */\nfunction isPlainObject(value: unknown): value is object {\n return (\n typeof value === 'object' &&\n value !== null &&\n !Array.isArray(value) &&\n Object.getPrototypeOf(value) === Object.prototype\n );\n}\n","/**\n * Configuration Validation Limits and Helpers\n *\n * Defines security limits and validation functions to prevent:\n * - Resource exhaustion (DoS)\n * - Path traversal attacks\n * - Command injection\n * - Name injection\n */\n\n/**\n * Security and resource limits for configuration validation\n */\nexport const VALIDATION_LIMITS = {\n // Resource limits (prevent DoS)\n MAX_ENTRIES: 1000000, // 1 million entries (memory, cache)\n MAX_TIMEOUT: 3600000, // 1 hour (execution, delegation)\n MAX_FILE_SIZE: 104857600, // 100 MB (workspace, abilities)\n MAX_CACHE_SIZE: 524288000, // 500 MB (cache storage)\n MAX_SESSIONS: 10000, // 10k concurrent sessions\n MAX_TTL: 86400000, // 24 hours (cache TTL)\n\n // String/array limits (prevent memory exhaustion)\n MAX_STRING_LENGTH: 1000, // Max length for string fields\n MAX_ARRAY_LENGTH: 100, // Max array items\n MAX_COMMAND_LENGTH: 100, // Max command string length\n MAX_NAME_LENGTH: 50, // Max name length (providers, agents)\n\n // Config file limits\n MAX_CONFIG_FILE_SIZE: 1024 * 1024, // 1 MB config file\n\n // Port ranges (security)\n MIN_PORT: 1024, // Avoid privileged ports\n MAX_PORT: 65535, // Max valid port\n\n // Minimum values (sanity checks)\n MIN_TIMEOUT: 1000, // 1 second\n MIN_INTERVAL: 1000, // 1 second\n MIN_DELAY: 0, // Can be 0\n MIN_FILE_SIZE: 1024, // 1 KB\n MIN_ENTRIES: 1, // At least 1\n MIN_DAYS: 1, // At least 1 day\n MIN_BYTES: 1024, // 1 KB\n\n // Ratio limits\n MIN_BACKOFF_FACTOR: 1, // Linear at minimum\n MAX_BACKOFF_FACTOR: 10 // Reasonable exponential growth\n} as const;\n\n/**\n * Validate relative path (prevent path traversal)\n *\n * Security checks:\n * - No absolute paths (/)\n * - No parent directory references (../)\n * - No Windows absolute paths (C:\\)\n *\n * @param path - Path to validate\n * @returns true if path is safe relative path\n *\n * @example\n * ```typescript\n * isValidRelativePath('.automatosx/config.yaml') // ✅ true\n * isValidRelativePath('/etc/passwd') // ❌ false\n * isValidRelativePath('../../../etc/passwd') // ❌ false\n * ```\n */\nexport function isValidRelativePath(path: string): boolean {\n if (!path || typeof path !== 'string') {\n return false;\n }\n\n // No absolute Unix paths\n if (path.startsWith('/')) {\n return false;\n }\n\n // No parent directory traversal\n if (path.includes('..')) {\n return false;\n }\n\n // No absolute Windows paths (C:, D:, etc.)\n if (/^[a-zA-Z]:/.test(path)) {\n return false;\n }\n\n // No UNC paths (\\\\server\\share)\n if (path.startsWith('\\\\\\\\')) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Validate command string (prevent command injection)\n *\n * Security checks:\n * - Only alphanumeric, dash, underscore\n * - No shell metacharacters (; & | $ etc.)\n * - Reasonable length limit\n *\n * @param command - Command to validate\n * @returns true if command is safe\n *\n * @example\n * ```typescript\n * isValidCommand('claude') // ✅ true\n * isValidCommand('my-provider_v2') // ✅ true\n * isValidCommand('claude; rm -rf /') // ❌ false\n * isValidCommand('claude & backdoor') // ❌ false\n * ```\n */\nexport function isValidCommand(command: string): boolean {\n if (!command || typeof command !== 'string') {\n return false;\n }\n\n // Length check\n if (command.length > VALIDATION_LIMITS.MAX_COMMAND_LENGTH) {\n return false;\n }\n\n // Only alphanumeric, dash, underscore (no shell metacharacters)\n if (!/^[a-z0-9_-]+$/i.test(command)) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Validate provider/agent name (prevent name injection)\n *\n * Security checks:\n * - Only alphanumeric, dash, underscore\n * - Must start with alphanumeric\n * - Reasonable length limit\n *\n * @param name - Name to validate\n * @returns true if name is valid\n *\n * @example\n * ```typescript\n * isValidName('backend') // ✅ true\n * isValidName('my-agent_v2') // ✅ true\n * isValidName('../../malicious') // ❌ false\n * isValidName('agent\\nmalicious: true') // ❌ false\n * ```\n */\nexport function isValidName(name: string): boolean {\n if (!name || typeof name !== 'string') {\n return false;\n }\n\n // Length check\n if (name.length > VALIDATION_LIMITS.MAX_NAME_LENGTH) {\n return false;\n }\n\n // Must start with alphanumeric, then can have dash/underscore\n if (!/^[a-z0-9][a-z0-9-_]*$/i.test(name)) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Validate file extension\n *\n * @param ext - Extension to validate (with or without leading dot)\n * @returns true if extension is valid\n */\nexport function isValidExtension(ext: string): boolean {\n if (!ext || typeof ext !== 'string') {\n return false;\n }\n\n // Ensure starts with dot\n const normalized = ext.startsWith('.') ? ext : `.${ext}`;\n\n // Reasonable length (e.g., .json, .yaml, .tsx)\n if (normalized.length > 10 || normalized.length < 2) {\n return false;\n }\n\n // Only alphanumeric after dot\n if (!/^\\.[a-z0-9]+$/i.test(normalized)) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Check if a number is a positive integer\n */\nexport function isPositiveInteger(value: any): value is number {\n return typeof value === 'number' &&\n Number.isInteger(value) &&\n value > 0;\n}\n\n/**\n * Check if a number is a non-negative integer (can be 0)\n */\nexport function isNonNegativeInteger(value: any): value is number {\n return typeof value === 'number' &&\n Number.isInteger(value) &&\n value >= 0;\n}\n\n/**\n * Check if value is within range (inclusive)\n */\nexport function inRange(value: number, min: number, max: number): boolean {\n return value >= min && value <= max;\n}\n\n/**\n * Sanitize error message for production (remove sensitive paths)\n *\n * @param message - Error message to sanitize\n * @param isProduction - Whether in production mode\n * @returns Sanitized message\n */\nexport function sanitizeErrorMessage(message: string, isProduction: boolean): string {\n if (!isProduction) {\n return message;\n }\n\n // Remove absolute paths\n message = message.replace(/\\/[^\\s]+\\//g, '<path>/');\n\n // Remove usernames\n message = message.replace(/\\/Users\\/[^/]+\\//g, '/Users/<user>/');\n message = message.replace(/\\/home\\/[^/]+\\//g, '/home/<user>/');\n message = message.replace(/C:\\\\Users\\\\[^\\\\]+\\\\/g, 'C:\\\\Users\\\\<user>\\\\');\n\n return message;\n}\n","/**\n * Init Command - Initialize AutomatosX project\n */\n\nimport type { CommandModule } from 'yargs';\nimport { mkdir, writeFile, access } from 'fs/promises';\nimport { resolve, join, dirname } from 'path';\nimport { fileURLToPath } from 'url';\nimport { constants } from 'fs';\nimport chalk from 'chalk';\nimport { DEFAULT_CONFIG } from '../../types/config.js';\nimport type { AutomatosXConfig } from '../../types/config.js';\nimport { logger } from '../../utils/logger.js';\nimport { printError } from '../../utils/error-formatter.js';\n\n// Get the directory of this file for locating examples\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\n// Get package root - handle both dev (src/) and prod (dist/) scenarios\nfunction getPackageRoot(): string {\n const currentDir = __dirname;\n if (currentDir.includes('/dist')) {\n // Production: dist/index.js -> go up one level to package root\n return join(currentDir, '..');\n } else {\n // Development: src/cli/commands/init.ts -> go up three levels to package root\n return join(currentDir, '../../..');\n }\n}\n\ninterface InitOptions {\n force?: boolean;\n path?: string;\n}\n\nexport const initCommand: CommandModule<Record<string, unknown>, InitOptions> = {\n command: 'init [path]',\n describe: 'Initialize AutomatosX in current or specified directory',\n\n builder: (yargs) => {\n return yargs\n .positional('path', {\n describe: 'Project directory (defaults to current directory)',\n type: 'string',\n default: '.'\n })\n .option('force', {\n alias: 'f',\n describe: 'Force initialization even if .automatosx already exists',\n type: 'boolean',\n default: false\n });\n },\n\n handler: async (argv) => {\n const projectDir = resolve(argv.path || '.');\n const automatosxDir = join(projectDir, '.automatosx');\n\n console.log(chalk.blue.bold('\\n🤖 AutomatosX v4.0 - Project Initialization\\n'));\n\n try {\n // Check if already initialized\n const exists = await checkExists(automatosxDir);\n if (exists && !argv.force) {\n console.log(chalk.yellow('⚠️ AutomatosX is already initialized in this directory'));\n console.log(chalk.gray(` ${automatosxDir}`));\n console.log(chalk.gray('\\n Use --force to reinitialize\\n'));\n process.exit(1);\n }\n\n if (exists && argv.force) {\n console.log(chalk.yellow('⚠️ Reinitializing (--force flag detected)'));\n }\n\n // Create directory structure\n console.log(chalk.cyan('📁 Creating directory structure...'));\n await createDirectoryStructure(automatosxDir);\n console.log(chalk.green(' ✓ Directories created'));\n\n // Copy example agents\n console.log(chalk.cyan('🤖 Installing example agents...'));\n await copyExampleAgents(automatosxDir);\n console.log(chalk.green(' ✓ 5 example agents installed'));\n\n // Copy example abilities\n console.log(chalk.cyan('⚡ Installing example abilities...'));\n await copyExampleAbilities(automatosxDir);\n console.log(chalk.green(' ✓ 15 example abilities installed'));\n\n // Copy agent templates (v5.0+)\n console.log(chalk.cyan('📋 Installing agent templates...'));\n await copyExampleTemplates(automatosxDir);\n console.log(chalk.green(' ✓ 5 agent templates installed'));\n\n // Create default config\n console.log(chalk.cyan('⚙️ Generating configuration...'));\n const configPath = join(projectDir, 'automatosx.config.json');\n await createDefaultConfig(configPath, argv.force ?? false);\n console.log(chalk.green(' ✓ Configuration created'));\n\n // Setup Claude Code integration\n console.log(chalk.cyan('🔌 Setting up Claude Code integration...'));\n await setupClaudeIntegration(projectDir);\n console.log(chalk.green(' ✓ Claude Code integration configured'));\n\n // Create .gitignore entry\n console.log(chalk.cyan('📝 Updating .gitignore...'));\n await updateGitignore(projectDir);\n console.log(chalk.green(' ✓ .gitignore updated'));\n\n // Success message\n console.log(chalk.green.bold('\\n✅ AutomatosX initialized successfully!\\n'));\n console.log(chalk.gray('Next steps:'));\n console.log(chalk.gray(' 1. Review automatosx.config.json'));\n console.log(chalk.gray(' 2. List agents: automatosx list agents'));\n console.log(chalk.gray(' 3. Run an agent: automatosx run backend \"Hello!\"\\n'));\n console.log(chalk.cyan('Available example agents:'));\n console.log(chalk.gray(' • backend - Backend engineer'));\n console.log(chalk.gray(' • frontend - Frontend engineer'));\n console.log(chalk.gray(' • devops - DevOps specialist'));\n console.log(chalk.gray(' • security - Security analyst'));\n console.log(chalk.gray(' • quality - QA specialist'));\n console.log(chalk.gray(' • data - Data scientist'));\n console.log(chalk.gray(' • design - Product designer'));\n console.log(chalk.gray(' • writer - Technical writer'));\n console.log(chalk.gray(' • product - Product manager'));\n console.log(chalk.gray(' • ceo - Executive advisor'));\n console.log(chalk.gray(' • cto - Technology strategist'));\n console.log(chalk.gray(' • researcher - Research analyst\\n'));\n console.log(chalk.cyan('Claude Code Integration:'));\n console.log(chalk.gray(' • Use /ax command in Claude Code'));\n console.log(chalk.gray(' • Example: /ax assistant \"Explain this code\"'));\n console.log(chalk.gray(' • MCP tools available in .claude/mcp/\\n'));\n\n logger.info('AutomatosX initialized', { projectDir, automatosxDir });\n\n } catch (error) {\n printError(error, {\n verbose: false,\n showCode: true,\n showSuggestions: true,\n colors: true\n });\n logger.error('Initialization failed', { error: (error as Error).message });\n process.exit(1);\n }\n }\n};\n\n/**\n * Check if path exists\n */\nasync function checkExists(path: string): Promise<boolean> {\n try {\n await access(path, constants.F_OK);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Create AutomatosX directory structure\n */\nasync function createDirectoryStructure(baseDir: string): Promise<void> {\n const dirs = [\n baseDir,\n join(baseDir, 'agents'),\n join(baseDir, 'teams'),\n join(baseDir, 'abilities'),\n join(baseDir, 'templates'), // v5.0: Agent templates\n join(baseDir, 'memory'),\n join(baseDir, 'memory/exports'), // v5.1: MCP memory export directory\n join(baseDir, 'sessions'), // v5.1: Session persistence\n join(baseDir, 'workspaces'),\n join(baseDir, 'logs')\n ];\n\n for (const dir of dirs) {\n await mkdir(dir, { recursive: true });\n }\n}\n\n/**\n * Copy example agents to user's .automatosx directory\n */\nasync function copyExampleAgents(baseDir: string): Promise<void> {\n const { readdir, copyFile } = await import('fs/promises');\n\n const examplesDir = join(getPackageRoot(), 'examples/agents');\n const targetDir = join(baseDir, 'agents');\n\n try {\n const files = await readdir(examplesDir);\n for (const file of files) {\n if (file.endsWith('.yaml')) {\n await copyFile(join(examplesDir, file), join(targetDir, file));\n }\n }\n } catch (error) {\n logger.warn('Could not copy example agents', { error: (error as Error).message });\n }\n}\n\n/**\n * Copy example abilities to user's .automatosx directory\n */\nasync function copyExampleAbilities(baseDir: string): Promise<void> {\n const { readdir, copyFile } = await import('fs/promises');\n\n const examplesDir = join(getPackageRoot(), 'examples/abilities');\n const targetDir = join(baseDir, 'abilities');\n\n try {\n const files = await readdir(examplesDir);\n for (const file of files) {\n if (file.endsWith('.md')) {\n await copyFile(join(examplesDir, file), join(targetDir, file));\n }\n }\n } catch (error) {\n logger.warn('Could not copy example abilities', { error: (error as Error).message });\n }\n}\n\n/**\n * Copy agent templates to user's .automatosx directory (v5.0+)\n */\nasync function copyExampleTemplates(baseDir: string): Promise<void> {\n const { readdir, copyFile } = await import('fs/promises');\n\n const examplesDir = join(getPackageRoot(), 'examples/templates');\n const targetDir = join(baseDir, 'templates');\n\n try {\n const files = await readdir(examplesDir);\n for (const file of files) {\n if (file.endsWith('.yaml')) {\n await copyFile(join(examplesDir, file), join(targetDir, file));\n }\n }\n } catch (error) {\n logger.warn('Could not copy agent templates', { error: (error as Error).message });\n }\n}\n\n/**\n * Create default configuration file\n */\nasync function createDefaultConfig(\n configPath: string,\n force: boolean\n): Promise<void> {\n const exists = await checkExists(configPath);\n\n if (exists && !force) {\n return; // Don't overwrite existing config unless forced\n }\n\n const config = {\n ...DEFAULT_CONFIG,\n // Add metadata\n $schema: './schema/config.json',\n version: '5.0.0'\n };\n\n const content = JSON.stringify(config, null, 2);\n await writeFile(configPath, content, 'utf-8');\n}\n\n/**\n * Setup Claude Code integration files\n */\nasync function setupClaudeIntegration(projectDir: string): Promise<void> {\n const { readdir, copyFile } = await import('fs/promises');\n\n const examplesBaseDir = join(getPackageRoot(), 'examples/claude');\n\n // Create .claude directory structure\n const claudeDir = join(projectDir, '.claude');\n const commandsDir = join(claudeDir, 'commands');\n const mcpDir = join(claudeDir, 'mcp');\n\n await mkdir(commandsDir, { recursive: true });\n await mkdir(mcpDir, { recursive: true });\n\n try {\n // Copy slash command\n const commandsSourceDir = join(examplesBaseDir, 'commands');\n const commandFiles = await readdir(commandsSourceDir);\n for (const file of commandFiles) {\n if (file.endsWith('.md')) {\n await copyFile(join(commandsSourceDir, file), join(commandsDir, file));\n }\n }\n\n // Copy MCP configuration\n const mcpSourceDir = join(examplesBaseDir, 'mcp');\n const mcpFiles = await readdir(mcpSourceDir);\n for (const file of mcpFiles) {\n if (file.endsWith('.json')) {\n await copyFile(join(mcpSourceDir, file), join(mcpDir, file));\n }\n }\n } catch (error) {\n logger.warn('Could not copy Claude integration files', { error: (error as Error).message });\n }\n}\n\n/**\n * Update .gitignore with AutomatosX entries\n */\nasync function updateGitignore(projectDir: string): Promise<void> {\n const gitignorePath = join(projectDir, '.gitignore');\n\n const automatosxEntries = [\n '',\n '# AutomatosX',\n '.automatosx/memory/',\n '.automatosx/workspaces/',\n '.automatosx/logs/',\n 'automatosx.config.json # Optional: remove to track config',\n ''\n ].join('\\n');\n\n try {\n const exists = await checkExists(gitignorePath);\n\n if (exists) {\n // Append to existing .gitignore\n const { readFile } = await import('fs/promises');\n const content = await readFile(gitignorePath, 'utf-8');\n\n // Check if AutomatosX entries already exist\n if (content.includes('# AutomatosX')) {\n return; // Already exists\n }\n\n await writeFile(gitignorePath, content + automatosxEntries, 'utf-8');\n } else {\n // Create new .gitignore\n await writeFile(gitignorePath, automatosxEntries, 'utf-8');\n }\n } catch (error) {\n // Non-critical error, just log it\n logger.warn('Failed to update .gitignore', { error: (error as Error).message });\n }\n}\n","/**\n * List Command - List agents, abilities, or providers\n */\n\nimport type { CommandModule } from 'yargs';\nimport { readdir } from 'fs/promises';\nimport { join } from 'path';\nimport chalk from 'chalk';\nimport { logger } from '../../utils/logger.js';\nimport { PathResolver, detectProjectRoot } from '../../core/path-resolver.js';\n\ninterface ListOptions {\n type: 'agents' | 'abilities' | 'providers';\n}\n\nexport const listCommand: CommandModule<Record<string, unknown>, ListOptions> = {\n command: 'list <type>',\n describe: 'List available agents, abilities, or providers',\n\n builder: (yargs) => {\n return yargs\n .positional('type', {\n describe: 'What to list',\n type: 'string',\n choices: ['agents', 'abilities', 'providers'] as const,\n demandOption: true\n }) as any;\n },\n\n handler: async (argv) => {\n try {\n const projectDir = await detectProjectRoot();\n const pathResolver = new PathResolver({\n projectDir,\n workingDir: process.cwd(),\n agentWorkspace: join(projectDir, '.automatosx', 'workspaces')\n });\n\n switch (argv.type) {\n case 'agents':\n await listAgents(pathResolver);\n break;\n case 'abilities':\n await listAbilities(pathResolver);\n break;\n case 'providers':\n await listProviders();\n break;\n }\n\n } catch (error) {\n console.log(chalk.red.bold('\\n❌ Failed to list ' + argv.type + '\\n'));\n console.log(chalk.red((error as Error).message));\n logger.error('List command failed', { type: argv.type, error: (error as Error).message });\n process.exit(1);\n }\n }\n};\n\n/**\n * List available agents\n */\nasync function listAgents(pathResolver: PathResolver): Promise<void> {\n const agentsDir = pathResolver.getAgentsDirectory();\n const { existsSync } = await import('fs');\n const projectDir = await detectProjectRoot();\n const examplesDir = join(projectDir, 'examples', 'agents');\n\n try {\n // Collect agent files from both directories\n const agentFiles: Array<{ file: string; path: string; source: string }> = [];\n\n // Load from .automatosx/agents/\n if (existsSync(agentsDir)) {\n const files = await readdir(agentsDir);\n for (const file of files) {\n if (file.endsWith('.yaml') || file.endsWith('.yml')) {\n agentFiles.push({\n file,\n path: join(agentsDir, file),\n source: '.automatosx'\n });\n }\n }\n }\n\n // Load from examples/agents/\n if (existsSync(examplesDir)) {\n const files = await readdir(examplesDir);\n for (const file of files) {\n if (file.endsWith('.yaml') || file.endsWith('.yml')) {\n // Skip if already loaded from .automatosx (avoid duplicates)\n const alreadyLoaded = agentFiles.some(a => a.file === file);\n if (!alreadyLoaded) {\n agentFiles.push({\n file,\n path: join(examplesDir, file),\n source: 'examples'\n });\n }\n }\n }\n }\n\n if (agentFiles.length === 0) {\n console.log(chalk.yellow('\\n⚠️ No agents found\\n'));\n console.log(chalk.gray('Create agents in: ' + agentsDir));\n console.log(chalk.gray('Or run: automatosx init\\n'));\n return;\n }\n\n console.log(chalk.blue.bold('\\n🤖 Available Agents:\\n'));\n\n // Load and display each agent's info\n const { load } = await import('js-yaml');\n const { readFile } = await import('fs/promises');\n\n // Sort by name\n agentFiles.sort((a, b) => a.file.localeCompare(b.file));\n\n for (const { file, path: agentPath, source } of agentFiles) {\n try {\n const content = await readFile(agentPath, 'utf-8');\n const agent = load(content) as any;\n\n const name = agent.displayName || agent.name || file.replace(/\\.(yaml|yml)$/, '');\n const description = agent.description || 'No description';\n\n console.log(chalk.cyan(` • ${name}`) + chalk.gray(` (${source})`));\n console.log(chalk.gray(` ${description}`));\n\n if (agent.abilities && agent.abilities.length > 0) {\n console.log(chalk.gray(` Abilities: ${agent.abilities.join(', ')}`));\n }\n console.log();\n } catch (error) {\n console.log(chalk.yellow(` • ${file} (error loading)`) + chalk.gray(` (${source})`));\n console.log();\n }\n }\n\n console.log(chalk.gray(`Total: ${agentFiles.length} agent(s)\\n`));\n\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n console.log(chalk.yellow('\\n⚠️ Agents directory not found\\n'));\n console.log(chalk.gray('Run: automatosx init\\n'));\n } else {\n throw error;\n }\n }\n}\n\n/**\n * List available abilities\n */\nasync function listAbilities(pathResolver: PathResolver): Promise<void> {\n const abilitiesDir = pathResolver.getAbilitiesDirectory();\n\n try {\n const files = await readdir(abilitiesDir);\n const abilityFiles = files.filter(f => f.endsWith('.md'));\n\n if (abilityFiles.length === 0) {\n console.log(chalk.yellow('\\n⚠️ No abilities found\\n'));\n console.log(chalk.gray('Create abilities in: ' + abilitiesDir));\n console.log(chalk.gray('Or run: automatosx init\\n'));\n return;\n }\n\n console.log(chalk.blue.bold('\\n⚡ Available Abilities:\\n'));\n\n const { readFile } = await import('fs/promises');\n\n for (const file of abilityFiles.sort()) {\n const abilityPath = join(abilitiesDir, file);\n try {\n const content = await readFile(abilityPath, 'utf-8');\n\n // Extract title and description from markdown\n const lines = content.split('\\n');\n const titleLine = lines.find(l => l.startsWith('# '));\n const descLine = lines.find(l => l.startsWith('## Description'));\n const descIndex = lines.indexOf(descLine || '');\n\n const name = titleLine?.replace('# ', '') || file.replace('.md', '');\n const description = descIndex >= 0 ? lines[descIndex + 1]?.trim() || 'No description' : 'No description';\n\n console.log(chalk.cyan(` • ${name}`));\n console.log(chalk.gray(` ${description}`));\n console.log();\n } catch (error) {\n console.log(chalk.yellow(` • ${file} (error loading)`));\n console.log();\n }\n }\n\n console.log(chalk.gray(`Total: ${abilityFiles.length} ability(ies)\\n`));\n\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n console.log(chalk.yellow('\\n⚠️ Abilities directory not found\\n'));\n console.log(chalk.gray('Run: automatosx init\\n'));\n } else {\n throw error;\n }\n }\n}\n\n/**\n * List available providers\n */\nasync function listProviders(): Promise<void> {\n console.log(chalk.blue.bold('\\n🔌 Available Providers:\\n'));\n\n const providers = [\n {\n name: 'claude',\n description: 'Anthropic Claude (via CLI)',\n status: 'Available',\n capabilities: ['text-generation', 'conversation']\n },\n {\n name: 'gemini',\n description: 'Google Gemini (via CLI)',\n status: 'Available',\n capabilities: ['text-generation', 'conversation']\n },\n {\n name: 'openai-embed',\n description: 'OpenAI Embeddings (via CLI)',\n status: 'Available',\n capabilities: ['embeddings']\n }\n ];\n\n for (const provider of providers) {\n console.log(chalk.cyan(` • ${provider.name}`));\n console.log(chalk.gray(` ${provider.description}`));\n console.log(chalk.gray(` Status: ${provider.status}`));\n console.log(chalk.gray(` Capabilities: ${provider.capabilities.join(', ')}`));\n console.log();\n }\n\n console.log(chalk.gray(`Total: ${providers.length} provider(s)\\n`));\n}\n","/**\n * MCP Command - Start MCP Server\n *\n * Starts AutomatosX as a stdio JSON-RPC MCP server for\n * integration with Claude Code and other MCP clients.\n */\n\nimport type { CommandModule } from 'yargs';\nimport { McpServer } from '../../mcp/server.js';\nimport { logger } from '../../utils/logger.js';\n\ninterface McpCommandArgs {\n debug?: boolean;\n}\n\nexport const mcpCommand: CommandModule<object, McpCommandArgs> = {\n command: 'mcp',\n describe: 'Start MCP server for Claude Code integration',\n\n builder: (yargs) => {\n return yargs\n .option('debug', {\n alias: 'd',\n type: 'boolean',\n description: 'Enable debug logging',\n default: false\n })\n .example('$0 mcp', 'Start MCP server (stdio mode)')\n .example('$0 mcp --debug', 'Start with debug logging');\n },\n\n handler: async (argv) => {\n try {\n logger.info('Starting AutomatosX MCP Server...');\n\n const server = new McpServer({\n debug: argv.debug\n });\n\n await server.start();\n\n // Server runs until stopped (SIGINT/SIGTERM)\n } catch (error) {\n logger.error('Failed to start MCP server', { error });\n process.exit(1);\n }\n }\n};\n","/**\n * AutomatosX MCP Server\n *\n * Implements stdio JSON-RPC server for Model Context Protocol (MCP).\n * Exposes AutomatosX capabilities as MCP tools for Claude Code and other clients.\n */\n\nimport { createRequire } from 'module';\nimport { join } from 'path';\nimport type {\n JsonRpcRequest,\n JsonRpcResponse,\n JsonRpcError,\n McpInitializeRequest,\n McpInitializeResponse,\n McpToolListRequest,\n McpToolListResponse,\n McpToolCallRequest,\n McpToolCallResponse,\n McpTool,\n ToolHandler\n} from './types.js';\nimport { McpErrorCode } from './types.js';\nimport { logger, setLogLevel } from '../utils/logger.js';\nimport { loadConfig } from '../core/config.js';\nimport { Router } from '../core/router.js';\nimport { MemoryManager } from '../core/memory-manager.js';\nimport { SessionManager } from '../core/session-manager.js';\nimport { WorkspaceManager } from '../core/workspace-manager.js';\nimport { ContextManager } from '../agents/context-manager.js';\nimport { ProfileLoader } from '../agents/profile-loader.js';\nimport { AbilitiesManager } from '../agents/abilities-manager.js';\nimport { TeamManager } from '../core/team-manager.js';\nimport { PathResolver } from '../core/path-resolver.js';\n\n// Import tool handlers - Phase 1\nimport { createRunAgentHandler } from './tools/run-agent.js';\nimport { createListAgentsHandler } from './tools/list-agents.js';\nimport { createSearchMemoryHandler } from './tools/search-memory.js';\nimport { createGetStatusHandler } from './tools/get-status.js';\n\n// Import tool handlers - Phase 2: Sessions\nimport { createSessionCreateHandler } from './tools/session-create.js';\nimport { createSessionListHandler } from './tools/session-list.js';\nimport { createSessionStatusHandler } from './tools/session-status.js';\nimport { createSessionCompleteHandler } from './tools/session-complete.js';\nimport { createSessionFailHandler } from './tools/session-fail.js';\n\n// Import tool handlers - Phase 2: Memory\nimport { createMemoryAddHandler } from './tools/memory-add.js';\nimport { createMemoryListHandler } from './tools/memory-list.js';\nimport { createMemoryDeleteHandler } from './tools/memory-delete.js';\nimport { createMemoryExportHandler } from './tools/memory-export.js';\nimport { createMemoryImportHandler } from './tools/memory-import.js';\nimport { createMemoryStatsHandler } from './tools/memory-stats.js';\nimport { createMemoryClearHandler } from './tools/memory-clear.js';\n\nexport interface McpServerOptions {\n debug?: boolean;\n}\n\nexport class McpServer {\n private tools: Map<string, ToolHandler<unknown, unknown>> = new Map();\n private toolSchemas: McpTool[] = [];\n private initialized = false;\n private initializationPromise: Promise<void> | null = null; // Fix: Race condition prevention\n private version: string;\n\n // Shared services (initialized once per server)\n private router!: Router;\n private memoryManager!: MemoryManager;\n private sessionManager!: SessionManager;\n private workspaceManager!: WorkspaceManager;\n private contextManager!: ContextManager;\n private profileLoader!: ProfileLoader;\n private pathResolver!: PathResolver;\n\n constructor(options: McpServerOptions = {}) {\n if (options.debug) {\n setLogLevel('debug');\n }\n\n // Get version (try ../../version.json first, then package.json)\n const require = createRequire(import.meta.url);\n this.version = 'unknown';\n try {\n const versionData = require('../../version.json');\n this.version = versionData.version || 'unknown';\n } catch {\n try {\n const packageJson = require('../../package.json');\n this.version = packageJson.version || 'unknown';\n } catch {\n // Keep 'unknown'\n }\n }\n\n logger.info('[MCP Server] Initializing AutomatosX MCP Server', {\n version: this.version\n });\n }\n\n /**\n * Initialize shared services once per server process\n */\n private async initializeServices(): Promise<void> {\n logger.info('[MCP Server] Initializing shared services...');\n\n const projectDir = process.cwd();\n const config = await loadConfig(projectDir);\n\n // Initialize TeamManager\n const teamManager = new TeamManager(\n join(projectDir, '.automatosx', 'teams')\n );\n\n // Initialize ProfileLoader\n this.profileLoader = new ProfileLoader(\n join(projectDir, '.automatosx', 'agents'),\n undefined, // fallbackProfilesDir (uses default)\n teamManager\n );\n\n // Initialize AbilitiesManager\n const abilitiesManager = new AbilitiesManager(\n join(projectDir, '.automatosx', 'abilities')\n );\n\n // Initialize MemoryManager\n this.memoryManager = await MemoryManager.create({\n dbPath: join(projectDir, '.automatosx', 'memory', 'memory.db')\n });\n\n // Initialize PathResolver\n this.pathResolver = new PathResolver({\n projectDir,\n workingDir: process.cwd(),\n agentWorkspace: join(projectDir, '.automatosx', 'workspaces')\n });\n\n // Initialize Providers\n const providers = [];\n\n if (config.providers['claude-code']?.enabled) {\n const { ClaudeProvider } = await import('../providers/claude-provider.js');\n providers.push(new ClaudeProvider({\n name: 'claude-code',\n enabled: true,\n priority: config.providers['claude-code'].priority,\n timeout: config.providers['claude-code'].timeout,\n command: config.providers['claude-code'].command\n }));\n }\n\n if (config.providers['gemini-cli']?.enabled) {\n const { GeminiProvider } = await import('../providers/gemini-provider.js');\n providers.push(new GeminiProvider({\n name: 'gemini-cli',\n enabled: true,\n priority: config.providers['gemini-cli'].priority,\n timeout: config.providers['gemini-cli'].timeout,\n command: config.providers['gemini-cli'].command\n }));\n }\n\n if (config.providers['openai']?.enabled) {\n const { OpenAIProvider } = await import('../providers/openai-provider.js');\n providers.push(new OpenAIProvider({\n name: 'openai',\n enabled: true,\n priority: config.providers['openai'].priority,\n timeout: config.providers['openai'].timeout,\n command: config.providers['openai'].command\n }));\n }\n\n // Initialize Router\n this.router = new Router({\n providers,\n fallbackEnabled: true\n });\n\n // Initialize SessionManager\n this.sessionManager = new SessionManager({\n persistencePath: join(projectDir, '.automatosx', 'sessions', 'sessions.json')\n });\n await this.sessionManager.initialize();\n\n // Initialize WorkspaceManager\n this.workspaceManager = new WorkspaceManager(projectDir);\n await this.workspaceManager.initialize();\n\n // Initialize ContextManager\n this.contextManager = new ContextManager({\n profileLoader: this.profileLoader,\n abilitiesManager,\n memoryManager: this.memoryManager,\n router: this.router,\n pathResolver: this.pathResolver,\n sessionManager: this.sessionManager,\n workspaceManager: this.workspaceManager\n });\n\n logger.info('[MCP Server] Services initialized successfully');\n }\n\n /**\n * Register Phase 1 tools\n */\n private registerTools(): void {\n logger.info('[MCP Server] Registering tools...');\n\n // Tool 1: run_agent\n this.tools.set(\n 'run_agent',\n createRunAgentHandler({\n contextManager: this.contextManager,\n executorConfig: {\n sessionManager: this.sessionManager,\n workspaceManager: this.workspaceManager,\n contextManager: this.contextManager,\n profileLoader: this.profileLoader\n }\n }) as ToolHandler<unknown, unknown>\n );\n\n this.toolSchemas.push({\n name: 'run_agent',\n description: 'Execute an AutomatosX agent with a specific task',\n inputSchema: {\n type: 'object',\n properties: {\n agent: {\n type: 'string',\n description: 'The name of the agent to run (e.g., backend, Paris, Bob)'\n },\n task: {\n type: 'string',\n description: 'The task for the agent to perform'\n },\n provider: {\n type: 'string',\n description: 'Optional: Override the AI provider',\n enum: ['claude', 'gemini', 'openai']\n },\n no_memory: {\n type: 'boolean',\n description: 'Optional: Skip memory injection',\n default: false\n }\n },\n required: ['agent', 'task']\n }\n });\n\n // Tool 2: list_agents\n this.tools.set(\n 'list_agents',\n createListAgentsHandler({\n profileLoader: this.profileLoader\n }) as ToolHandler<unknown, unknown>\n );\n\n this.toolSchemas.push({\n name: 'list_agents',\n description: 'List all available AutomatosX agents',\n inputSchema: {\n type: 'object',\n properties: {}\n }\n });\n\n // Tool 3: search_memory\n this.tools.set(\n 'search_memory',\n createSearchMemoryHandler({\n memoryManager: this.memoryManager\n }) as ToolHandler<unknown, unknown>\n );\n\n this.toolSchemas.push({\n name: 'search_memory',\n description: 'Search AutomatosX memory for relevant information',\n inputSchema: {\n type: 'object',\n properties: {\n query: {\n type: 'string',\n description: 'Search query'\n },\n limit: {\n type: 'number',\n description: 'Maximum number of results',\n default: 10\n }\n },\n required: ['query']\n }\n });\n\n // Tool 4: get_status\n this.tools.set(\n 'get_status',\n createGetStatusHandler({\n memoryManager: this.memoryManager,\n sessionManager: this.sessionManager,\n router: this.router\n }) as ToolHandler<unknown, unknown>\n );\n\n this.toolSchemas.push({\n name: 'get_status',\n description: 'Get AutomatosX system status and configuration',\n inputSchema: {\n type: 'object',\n properties: {}\n }\n });\n\n // ============================================\n // Phase 2: Session Management Tools\n // ============================================\n\n // Tool 5: session_create\n this.tools.set(\n 'session_create',\n createSessionCreateHandler({\n sessionManager: this.sessionManager\n }) as ToolHandler<unknown, unknown>\n );\n\n this.toolSchemas.push({\n name: 'session_create',\n description: 'Create a new multi-agent session',\n inputSchema: {\n type: 'object',\n properties: {\n name: {\n type: 'string',\n description: 'Session name/task description'\n },\n agent: {\n type: 'string',\n description: 'Initiating agent name'\n }\n },\n required: ['name', 'agent']\n }\n });\n\n // Tool 6: session_list\n this.tools.set(\n 'session_list',\n createSessionListHandler({\n sessionManager: this.sessionManager\n }) as ToolHandler<unknown, unknown>\n );\n\n this.toolSchemas.push({\n name: 'session_list',\n description: 'List all active sessions',\n inputSchema: {\n type: 'object',\n properties: {}\n }\n });\n\n // Tool 7: session_status\n this.tools.set(\n 'session_status',\n createSessionStatusHandler({\n sessionManager: this.sessionManager\n }) as ToolHandler<unknown, unknown>\n );\n\n this.toolSchemas.push({\n name: 'session_status',\n description: 'Get detailed status of a specific session',\n inputSchema: {\n type: 'object',\n properties: {\n id: {\n type: 'string',\n description: 'Session ID'\n }\n },\n required: ['id']\n }\n });\n\n // Tool 8: session_complete\n this.tools.set(\n 'session_complete',\n createSessionCompleteHandler({\n sessionManager: this.sessionManager\n }) as ToolHandler<unknown, unknown>\n );\n\n this.toolSchemas.push({\n name: 'session_complete',\n description: 'Mark a session as completed',\n inputSchema: {\n type: 'object',\n properties: {\n id: {\n type: 'string',\n description: 'Session ID'\n }\n },\n required: ['id']\n }\n });\n\n // Tool 9: session_fail\n this.tools.set(\n 'session_fail',\n createSessionFailHandler({\n sessionManager: this.sessionManager\n }) as ToolHandler<unknown, unknown>\n );\n\n this.toolSchemas.push({\n name: 'session_fail',\n description: 'Mark a session as failed with an error reason',\n inputSchema: {\n type: 'object',\n properties: {\n id: {\n type: 'string',\n description: 'Session ID'\n },\n reason: {\n type: 'string',\n description: 'Failure reason'\n }\n },\n required: ['id', 'reason']\n }\n });\n\n // ============================================\n // Phase 2: Memory Management Tools\n // ============================================\n\n // Tool 10: memory_add\n this.tools.set(\n 'memory_add',\n createMemoryAddHandler({\n memoryManager: this.memoryManager\n }) as ToolHandler<unknown, unknown>\n );\n\n this.toolSchemas.push({\n name: 'memory_add',\n description: 'Add a new memory entry to the system',\n inputSchema: {\n type: 'object',\n properties: {\n content: {\n type: 'string',\n description: 'Memory content'\n },\n metadata: {\n type: 'object',\n description: 'Optional metadata (agent, timestamp, etc.)',\n properties: {\n agent: { type: 'string' },\n timestamp: { type: 'string' }\n }\n }\n },\n required: ['content']\n }\n });\n\n // Tool 11: memory_list\n this.tools.set(\n 'memory_list',\n createMemoryListHandler({\n memoryManager: this.memoryManager\n }) as ToolHandler<unknown, unknown>\n );\n\n this.toolSchemas.push({\n name: 'memory_list',\n description: 'List memory entries with optional filtering',\n inputSchema: {\n type: 'object',\n properties: {\n agent: {\n type: 'string',\n description: 'Filter by agent name'\n },\n limit: {\n type: 'number',\n description: 'Maximum number of entries',\n default: 50\n }\n }\n }\n });\n\n // Tool 12: memory_delete\n this.tools.set(\n 'memory_delete',\n createMemoryDeleteHandler({\n memoryManager: this.memoryManager\n }) as ToolHandler<unknown, unknown>\n );\n\n this.toolSchemas.push({\n name: 'memory_delete',\n description: 'Delete a specific memory entry by ID',\n inputSchema: {\n type: 'object',\n properties: {\n id: {\n type: 'number',\n description: 'Memory entry ID'\n }\n },\n required: ['id']\n }\n });\n\n // Tool 13: memory_export\n this.tools.set(\n 'memory_export',\n createMemoryExportHandler({\n memoryManager: this.memoryManager,\n pathResolver: this.pathResolver\n }) as ToolHandler<unknown, unknown>\n );\n\n this.toolSchemas.push({\n name: 'memory_export',\n description: 'Export all memory entries to a JSON file',\n inputSchema: {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description: 'Export file path'\n }\n },\n required: ['path']\n }\n });\n\n // Tool 14: memory_import\n this.tools.set(\n 'memory_import',\n createMemoryImportHandler({\n memoryManager: this.memoryManager,\n pathResolver: this.pathResolver\n }) as ToolHandler<unknown, unknown>\n );\n\n this.toolSchemas.push({\n name: 'memory_import',\n description: 'Import memory entries from a JSON file',\n inputSchema: {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description: 'Import file path'\n }\n },\n required: ['path']\n }\n });\n\n // Tool 15: memory_stats\n this.tools.set(\n 'memory_stats',\n createMemoryStatsHandler({\n memoryManager: this.memoryManager\n }) as ToolHandler<unknown, unknown>\n );\n\n this.toolSchemas.push({\n name: 'memory_stats',\n description: 'Get detailed memory statistics',\n inputSchema: {\n type: 'object',\n properties: {}\n }\n });\n\n // Tool 16: memory_clear\n this.tools.set(\n 'memory_clear',\n createMemoryClearHandler({\n memoryManager: this.memoryManager\n }) as ToolHandler<unknown, unknown>\n );\n\n this.toolSchemas.push({\n name: 'memory_clear',\n description: 'Clear all memory entries from the database',\n inputSchema: {\n type: 'object',\n properties: {}\n }\n });\n\n logger.info('[MCP Server] Registered tools', {\n count: this.tools.size,\n tools: Array.from(this.tools.keys())\n });\n }\n\n /**\n * Handle MCP protocol messages\n */\n private async handleRequest(request: JsonRpcRequest): Promise<JsonRpcResponse> {\n const { method, params, id } = request;\n\n logger.debug('[MCP Server] Handling request', { method, id });\n\n try {\n // Initialize protocol\n if (method === 'initialize') {\n return await this.handleInitialize(request as McpInitializeRequest, id ?? null);\n }\n\n // List available tools\n if (method === 'tools/list') {\n return this.handleToolsList(request as McpToolListRequest, id ?? null);\n }\n\n // Execute tool\n if (method === 'tools/call') {\n return await this.handleToolCall(request as McpToolCallRequest, id ?? null);\n }\n\n // Method not found\n return this.createErrorResponse(\n id ?? null,\n McpErrorCode.MethodNotFound,\n `Method not found: ${method}`\n );\n } catch (error) {\n logger.error('[MCP Server] Request handling failed', { method, error });\n return this.createErrorResponse(\n id ?? null,\n McpErrorCode.InternalError,\n `Internal error: ${(error as Error).message}`\n );\n }\n }\n\n /**\n * Handle initialize request\n */\n private async handleInitialize(\n request: McpInitializeRequest,\n id: string | number | null\n ): Promise<JsonRpcResponse> {\n logger.info('[MCP Server] Initialize request received', {\n clientInfo: request.params.clientInfo\n });\n\n // Fix: Prevent race condition in concurrent initialization\n if (!this.initialized) {\n if (!this.initializationPromise) {\n // First initialize request - start initialization\n this.initializationPromise = (async () => {\n await this.initializeServices();\n this.registerTools();\n this.initialized = true;\n logger.info('[MCP Server] Initialization complete');\n })();\n }\n // Wait for initialization to complete (either first or concurrent request)\n await this.initializationPromise;\n }\n\n const response: McpInitializeResponse = {\n protocolVersion: '2024-11-05',\n capabilities: {\n tools: {}\n },\n serverInfo: {\n name: 'automatosx',\n version: this.version\n }\n };\n\n return {\n jsonrpc: '2.0',\n id,\n result: response\n };\n }\n\n /**\n * Handle tools/list request\n */\n private handleToolsList(\n _request: McpToolListRequest,\n id: string | number | null\n ): JsonRpcResponse {\n logger.debug('[MCP Server] Tools list requested');\n\n // Fix: Check initialization status\n if (!this.initialized) {\n return this.createErrorResponse(\n id,\n McpErrorCode.ServerNotInitialized,\n 'Server not initialized. Please send initialize request first.'\n );\n }\n\n const response: McpToolListResponse = {\n tools: this.toolSchemas\n };\n\n return {\n jsonrpc: '2.0',\n id,\n result: response\n };\n }\n\n /**\n * Validate tool input against schema\n */\n private validateToolInput(\n toolName: string,\n input: Record<string, unknown>\n ): { valid: boolean; error?: string } {\n const schema = this.toolSchemas.find((s) => s.name === toolName);\n if (!schema) {\n return { valid: false, error: 'Tool schema not found' };\n }\n\n const { properties, required } = schema.inputSchema;\n\n // Check required fields\n if (required) {\n for (const field of required) {\n if (!(field in input)) {\n return {\n valid: false,\n error: `Missing required parameter: ${field}`\n };\n }\n }\n }\n\n // Basic type validation for known fields\n if (properties) {\n for (const [key, value] of Object.entries(input)) {\n const propSchema = properties[key];\n if (propSchema && typeof propSchema === 'object' && 'type' in propSchema) {\n const expectedType = propSchema.type;\n const actualType = typeof value;\n\n // Type checking\n if (expectedType === 'string' && actualType !== 'string') {\n return {\n valid: false,\n error: `Parameter '${key}' must be a string`\n };\n }\n if (expectedType === 'number' && actualType !== 'number') {\n return {\n valid: false,\n error: `Parameter '${key}' must be a number`\n };\n }\n if (expectedType === 'boolean' && actualType !== 'boolean') {\n return {\n valid: false,\n error: `Parameter '${key}' must be a boolean`\n };\n }\n }\n }\n }\n\n return { valid: true };\n }\n\n /**\n * Handle tools/call request\n */\n private async handleToolCall(\n request: McpToolCallRequest,\n id: string | number | null\n ): Promise<JsonRpcResponse> {\n const { name, arguments: args } = request.params;\n\n logger.info('[MCP Server] Tool call', { tool: name });\n\n // Fix: Check initialization status\n if (!this.initialized) {\n return this.createErrorResponse(\n id,\n McpErrorCode.ServerNotInitialized,\n 'Server not initialized. Please send initialize request first.'\n );\n }\n\n const handler = this.tools.get(name);\n if (!handler) {\n return this.createErrorResponse(\n id,\n McpErrorCode.ToolNotFound,\n `Tool not found: ${name}`\n );\n }\n\n // Validate input parameters\n const validation = this.validateToolInput(name, args || {});\n if (!validation.valid) {\n return this.createErrorResponse(\n id,\n McpErrorCode.InvalidParams,\n validation.error || 'Invalid parameters'\n );\n }\n\n try {\n const result = await handler(args || {});\n\n const response: McpToolCallResponse = {\n content: [\n {\n type: 'text',\n text: JSON.stringify(result, null, 2)\n }\n ]\n };\n\n return {\n jsonrpc: '2.0',\n id,\n result: response\n };\n } catch (error) {\n logger.error('[MCP Server] Tool execution failed', { tool: name, error });\n\n const response: McpToolCallResponse = {\n content: [\n {\n type: 'text',\n text: `Error: ${(error as Error).message}`\n }\n ],\n isError: true\n };\n\n return {\n jsonrpc: '2.0',\n id,\n result: response\n };\n }\n }\n\n /**\n * Create error response\n */\n private createErrorResponse(\n id: string | number | null,\n code: McpErrorCode,\n message: string\n ): JsonRpcResponse {\n const error: JsonRpcError = {\n code,\n message\n };\n\n return {\n jsonrpc: '2.0',\n id,\n error\n };\n }\n\n /**\n * Write MCP-compliant response with Content-Length framing\n */\n private writeResponse(response: JsonRpcResponse): void {\n const json = JSON.stringify(response);\n const contentLength = Buffer.byteLength(json, 'utf-8');\n const message = `Content-Length: ${contentLength}\\r\\n\\r\\n${json}`;\n\n // Write to stdout (not stderr, to avoid polluting the JSON-RPC stream)\n process.stdout.write(message);\n\n logger.debug('[MCP Server] Response sent', {\n id: response.id,\n contentLength\n });\n }\n\n /**\n * Start stdio server with Content-Length framing\n */\n async start(): Promise<void> {\n logger.info('[MCP Server] Starting stdio JSON-RPC server...');\n\n let buffer = '';\n let contentLength: number | null = null;\n\n // Process stdin data with Content-Length framing\n process.stdin.on('data', async (chunk: Buffer) => {\n buffer += chunk.toString('utf-8');\n\n while (true) {\n // Parse headers if we don't have Content-Length yet\n if (contentLength === null) {\n // Look for the end of headers (blank line: \\r\\n\\r\\n)\n const headerEndIndex = buffer.indexOf('\\r\\n\\r\\n');\n if (headerEndIndex === -1) {\n // Incomplete headers, wait for more data\n break;\n }\n\n // Extract the header block (everything before \\r\\n\\r\\n)\n const headerBlock = buffer.slice(0, headerEndIndex);\n\n // Parse each header line (case-insensitive key lookup)\n const headerLines = headerBlock.split('\\r\\n');\n for (const line of headerLines) {\n const separatorIndex = line.indexOf(':');\n if (separatorIndex !== -1) {\n const key = line.slice(0, separatorIndex).trim().toLowerCase();\n const value = line.slice(separatorIndex + 1).trim();\n\n if (key === 'content-length') {\n contentLength = parseInt(value, 10);\n if (isNaN(contentLength) || contentLength < 0) {\n logger.error('[MCP Server] Invalid Content-Length header', { value });\n contentLength = null;\n buffer = ''; // Discard invalid data\n break;\n }\n }\n }\n }\n\n // If we still don't have Content-Length, it's a protocol error\n if (contentLength === null) {\n logger.error('[MCP Server] No Content-Length header found in request');\n buffer = buffer.slice(headerEndIndex + 4); // Skip past headers\n continue; // Try to recover by looking for next message\n }\n\n // Remove the headers (including \\r\\n\\r\\n) from buffer\n buffer = buffer.slice(headerEndIndex + 4);\n }\n\n // Check if we have the complete message body\n const messageBytes = Buffer.byteLength(buffer, 'utf-8');\n if (messageBytes < contentLength) {\n // Incomplete message, wait for more data\n break;\n }\n\n // Extract the JSON message\n const messageBuffer = Buffer.from(buffer, 'utf-8');\n const jsonMessage = messageBuffer.slice(0, contentLength).toString('utf-8');\n buffer = messageBuffer.slice(contentLength).toString('utf-8');\n contentLength = null;\n\n // Process the request\n try {\n const request = JSON.parse(jsonMessage) as JsonRpcRequest;\n logger.debug('[MCP Server] Request received', {\n method: request.method,\n id: request.id\n });\n\n const response = await this.handleRequest(request);\n\n // Only write response if request had an id (not a notification)\n if (request.id !== undefined && request.id !== null) {\n this.writeResponse(response);\n } else {\n logger.debug('[MCP Server] Notification received (no response sent)', {\n method: request.method\n });\n }\n } catch (error) {\n logger.error('[MCP Server] Failed to parse or handle request', {\n jsonMessage,\n error\n });\n\n const errorResponse: JsonRpcResponse = {\n jsonrpc: '2.0',\n id: null,\n error: {\n code: McpErrorCode.ParseError,\n message: 'Parse error: Invalid JSON'\n }\n };\n\n this.writeResponse(errorResponse);\n }\n }\n });\n\n process.stdin.on('end', () => {\n logger.info('[MCP Server] Server stopped (stdin closed)');\n process.exit(0);\n });\n\n // Graceful shutdown\n process.on('SIGINT', () => {\n logger.info('[MCP Server] Received SIGINT, shutting down...');\n process.exit(0);\n });\n\n process.on('SIGTERM', () => {\n logger.info('[MCP Server] Received SIGTERM, shutting down...');\n process.exit(0);\n });\n\n logger.info('[MCP Server] Server started successfully (Content-Length framing)');\n }\n}\n","/**\n * MCP (Model Context Protocol) Type Definitions\n *\n * Defines types for stdio JSON-RPC communication between\n * AutomatosX MCP server and MCP clients (e.g., Claude Code).\n */\n\n// JSON-RPC 2.0 Base Types\nexport interface JsonRpcRequest {\n jsonrpc: '2.0';\n id?: string | number | null;\n method: string;\n params?: unknown;\n}\n\nexport interface JsonRpcResponse {\n jsonrpc: '2.0';\n id: string | number | null;\n result?: unknown;\n error?: JsonRpcError;\n}\n\nexport interface JsonRpcError {\n code: number;\n message: string;\n data?: unknown;\n}\n\n// MCP Protocol Messages\nexport interface McpInitializeRequest {\n method: 'initialize';\n params: {\n protocolVersion: string;\n capabilities: {\n tools?: Record<string, unknown>;\n };\n clientInfo: {\n name: string;\n version: string;\n };\n };\n}\n\nexport interface McpInitializeResponse {\n protocolVersion: string;\n capabilities: {\n tools?: Record<string, unknown>;\n };\n serverInfo: {\n name: string;\n version: string;\n };\n}\n\nexport interface McpToolListRequest {\n method: 'tools/list';\n params?: Record<string, never>;\n}\n\nexport interface McpToolListResponse {\n tools: McpTool[];\n}\n\nexport interface McpToolCallRequest {\n method: 'tools/call';\n params: {\n name: string;\n arguments?: Record<string, unknown>;\n };\n}\n\nexport interface McpToolCallResponse {\n content: Array<{\n type: 'text';\n text: string;\n }>;\n isError?: boolean;\n}\n\nexport interface McpTool {\n name: string;\n description: string;\n inputSchema: {\n type: 'object';\n properties: Record<string, unknown>;\n required?: string[];\n };\n}\n\n// Tool-Specific Input/Output Types\n\n// run_agent\nexport interface RunAgentInput {\n agent: string;\n task: string;\n provider?: 'claude' | 'gemini' | 'openai';\n no_memory?: boolean;\n}\n\nexport interface RunAgentOutput {\n content: string;\n agent: string;\n tokens?: {\n prompt: number;\n completion: number;\n total: number;\n };\n latencyMs?: number;\n}\n\n// list_agents\nexport interface ListAgentsOutput {\n agents: Array<{\n name: string;\n displayName?: string;\n role?: string;\n team?: string;\n }>;\n}\n\n// search_memory\nexport interface SearchMemoryInput {\n query: string;\n limit?: number;\n}\n\nexport interface SearchMemoryOutput {\n results: Array<{\n id: number;\n similarity: number;\n content: string;\n metadata: {\n agent?: string;\n timestamp?: string;\n [key: string]: unknown;\n };\n }>;\n}\n\n// get_status\nexport interface GetStatusOutput {\n version: string;\n providers: string[];\n memory: {\n entries: number;\n dbSize?: string;\n };\n sessions: {\n active: number;\n total: number;\n };\n}\n\n// ============================================\n// Phase 2: Session Management Tools\n// ============================================\n\n// session_create\nexport interface SessionCreateInput {\n name: string;\n agent: string;\n}\n\nexport interface SessionCreateOutput {\n sessionId: string;\n name: string;\n agent: string;\n status: string;\n createdAt: string;\n}\n\n// session_list\nexport interface SessionListOutput {\n sessions: Array<{\n id: string;\n task: string;\n initiator: string;\n status: string;\n agents: string[];\n createdAt: string;\n updatedAt: string;\n }>;\n}\n\n// session_status\nexport interface SessionStatusInput {\n id: string;\n}\n\nexport interface SessionStatusOutput {\n id: string;\n task: string;\n initiator: string;\n status: string;\n agents: string[];\n createdAt: string;\n updatedAt: string;\n metadata?: Record<string, unknown>;\n}\n\n// session_complete\nexport interface SessionCompleteInput {\n id: string;\n}\n\nexport interface SessionCompleteOutput {\n success: boolean;\n sessionId: string;\n status: string;\n}\n\n// session_fail\nexport interface SessionFailInput {\n id: string;\n reason: string;\n}\n\nexport interface SessionFailOutput {\n success: boolean;\n sessionId: string;\n status: string;\n error: string;\n}\n\n// ============================================\n// Phase 2: Memory Management Tools\n// ============================================\n\n// memory_add\nexport interface MemoryAddInput {\n content: string;\n metadata?: {\n agent?: string;\n timestamp?: string;\n [key: string]: unknown;\n };\n}\n\nexport interface MemoryAddOutput {\n id: number;\n content: string;\n metadata: Record<string, unknown>;\n createdAt: string;\n}\n\n// memory_list\nexport interface MemoryListInput {\n agent?: string;\n limit?: number;\n}\n\nexport interface MemoryListOutput {\n entries: Array<{\n id: number;\n content: string;\n metadata: Record<string, unknown>;\n createdAt: string;\n }>;\n total: number;\n}\n\n// memory_delete\nexport interface MemoryDeleteInput {\n id: number;\n}\n\nexport interface MemoryDeleteOutput {\n success: boolean;\n id: number;\n}\n\n// memory_export\nexport interface MemoryExportInput {\n path: string;\n}\n\nexport interface MemoryExportOutput {\n success: boolean;\n path: string;\n entries: number;\n}\n\n// memory_import\nexport interface MemoryImportInput {\n path: string;\n}\n\nexport interface MemoryImportOutput {\n success: boolean;\n imported: number;\n skipped: number;\n}\n\n// memory_stats\nexport interface MemoryStatsOutput {\n totalEntries: number;\n dbSize: string;\n byAgent: Record<string, number>;\n}\n\n// memory_clear\nexport interface MemoryClearOutput {\n success: boolean;\n deleted: number;\n}\n\n// Tool Handler Type\nexport type ToolHandler<TInput = unknown, TOutput = unknown> = (\n input: TInput\n) => Promise<TOutput>;\n\n// Error Codes (align with JSON-RPC standard)\nexport enum McpErrorCode {\n ParseError = -32700,\n InvalidRequest = -32600,\n MethodNotFound = -32601,\n InvalidParams = -32602,\n InternalError = -32603,\n\n // Custom error codes (application-specific)\n ToolNotFound = -32001,\n ToolExecutionFailed = -32002,\n InvalidToolInput = -32003,\n ServerNotInitialized = -32004,\n}\n","/**\n * Router - AI Provider Router with Fallback\n *\n * Routes requests to available providers based on:\n * - Provider priority\n * - Provider health\n * - Rate limit status\n * - Automatic fallback on failure\n */\n\nimport type {\n Provider,\n ExecutionRequest,\n ExecutionResponse,\n HealthStatus\n} from '../types/provider.js';\nimport { logger } from '../utils/logger.js';\nimport { ProviderError, ErrorCode } from '../utils/errors.js';\n\nexport interface RouterConfig {\n providers: Provider[];\n fallbackEnabled: boolean;\n healthCheckInterval?: number;\n providerCooldownMs?: number; // Cooldown period for failed providers (default: 30000ms)\n}\n\nexport class Router {\n private providers: Provider[];\n private fallbackEnabled: boolean;\n private healthCheckInterval?: NodeJS.Timeout;\n private penalizedProviders: Map<string, number>; // provider name -> penalty expiry timestamp\n private providerCooldownMs: number;\n\n constructor(config: RouterConfig) {\n // Sort providers by priority (lower number = higher priority)\n this.providers = [...config.providers].sort((a, b) => {\n return a.priority - b.priority;\n });\n this.fallbackEnabled = config.fallbackEnabled;\n this.penalizedProviders = new Map();\n this.providerCooldownMs = config.providerCooldownMs ?? 30000; // Default: 30 seconds\n\n // Start health checks if interval is provided\n if (config.healthCheckInterval) {\n this.startHealthChecks(config.healthCheckInterval);\n }\n }\n\n /**\n * Execute request with automatic provider fallback\n */\n async execute(request: ExecutionRequest): Promise<ExecutionResponse> {\n const availableProviders = await this.getAvailableProviders();\n\n if (availableProviders.length === 0) {\n throw ProviderError.noAvailableProviders();\n }\n\n let lastError: Error | undefined;\n\n for (const provider of availableProviders) {\n try {\n logger.info(`Attempting execution with provider: ${provider.name}`);\n\n const response = await provider.execute(request);\n\n logger.info(`Execution successful with provider: ${provider.name}`, {\n latency: response.latencyMs,\n tokens: response.tokensUsed.total\n });\n\n // Remove provider from penalty list on success\n this.penalizedProviders.delete(provider.name);\n\n return response;\n\n } catch (error) {\n lastError = error as Error;\n\n logger.warn(`Provider ${provider.name} failed`, {\n error: lastError.message\n });\n\n // Penalize failed provider (add cooldown period)\n const penaltyExpiry = Date.now() + this.providerCooldownMs;\n this.penalizedProviders.set(provider.name, penaltyExpiry);\n\n logger.debug(`Provider ${provider.name} penalized until ${new Date(penaltyExpiry).toISOString()}`);\n\n // If fallback is disabled, throw immediately\n if (!this.fallbackEnabled) {\n throw lastError;\n }\n\n // Continue to next provider\n continue;\n }\n }\n\n // All providers failed\n throw new ProviderError(\n `All providers failed. Last error: ${lastError?.message || 'Unknown error'}`,\n ErrorCode.PROVIDER_NO_AVAILABLE,\n [\n 'Check provider availability with \"automatosx status\"',\n 'Verify provider CLIs are installed and in PATH',\n 'Check provider configuration in automatosx.config.json',\n 'Review error logs for more details'\n ],\n { lastError: lastError?.message }\n );\n }\n\n /**\n * Get available providers sorted by priority\n * Filters out penalized providers (those in cooldown period)\n */\n async getAvailableProviders(): Promise<Provider[]> {\n const now = Date.now();\n\n // Clean up expired penalties\n for (const [providerName, expiryTime] of this.penalizedProviders.entries()) {\n if (now >= expiryTime) {\n this.penalizedProviders.delete(providerName);\n logger.debug(`Provider ${providerName} penalty expired`);\n }\n }\n\n // Check availability in parallel\n const checks = this.providers.map(async provider => {\n try {\n // Skip penalized providers\n if (this.penalizedProviders.has(provider.name)) {\n const expiryTime = this.penalizedProviders.get(provider.name)!;\n const remainingMs = expiryTime - now;\n logger.debug(`Skipping penalized provider ${provider.name} (${Math.ceil(remainingMs / 1000)}s remaining)`);\n return null;\n }\n\n // Check if provider is available\n const isAvailable = await provider.isAvailable();\n return isAvailable ? provider : null;\n } catch (error) {\n logger.warn('Provider availability check failed', {\n provider: provider.name,\n error: (error as Error).message\n });\n return null;\n }\n });\n\n const results = await Promise.all(checks);\n return results.filter((p): p is Provider => p !== null);\n }\n\n /**\n * Get health status of all providers\n */\n async getHealthStatus(): Promise<Map<string, HealthStatus>> {\n const healthMap = new Map<string, HealthStatus>();\n\n for (const provider of this.providers) {\n const health = await provider.getHealth();\n healthMap.set(provider.name, health);\n }\n\n return healthMap;\n }\n\n /**\n * Select best provider based on health and availability\n */\n async selectProvider(): Promise<Provider | null> {\n const availableProviders = await this.getAvailableProviders();\n\n if (availableProviders.length === 0) {\n return null;\n }\n\n // Return first available provider (already sorted by priority)\n return availableProviders[0] ?? null;\n }\n\n /**\n * Start periodic health checks\n */\n private startHealthChecks(intervalMs: number): void {\n const runHealthChecks = async () => {\n try {\n const healthStatus = await this.getHealthStatus();\n\n logger.debug('Provider health check', {\n providers: Array.from(healthStatus.entries()).map(([name, health]) => ({\n name,\n available: health.available,\n latency: health.latencyMs,\n failures: health.consecutiveFailures\n }))\n });\n } catch (error) {\n logger.warn('Provider health check failed', {\n error: (error as Error).message\n });\n }\n };\n\n // Set up interval\n this.healthCheckInterval = setInterval(() => {\n void runHealthChecks(); // Explicitly handle promise\n }, intervalMs);\n\n // Run immediately on start\n void runHealthChecks();\n }\n\n /**\n * Stop health checks and cleanup resources\n */\n destroy(): void {\n if (this.healthCheckInterval) {\n clearInterval(this.healthCheckInterval);\n this.healthCheckInterval = undefined;\n }\n\n // Clear penalty list\n this.penalizedProviders.clear();\n }\n}\n","/**\n * Memory Manager - SQLite + vec extension implementation\n *\n * This replaces the HNSW implementation with pure SQLite vector search\n * using the sqlite-vec extension for better portability and simpler deployment.\n */\n\nimport Database from 'better-sqlite3';\nimport * as sqliteVec from 'sqlite-vec';\nimport { existsSync, mkdirSync } from 'fs';\nimport { dirname } from 'path';\nimport type {\n IMemoryManager,\n MemoryEntry,\n MemoryMetadata,\n MemorySearchQuery,\n MemorySearchResult,\n MemoryManagerConfig,\n MemoryStats\n} from '../types/memory.js';\nimport { MemoryError } from '../types/memory.js';\nimport { logger } from '../utils/logger.js';\n\n// v4.11.0: VECTOR_DIMENSIONS removed (FTS5 only, no vector search)\n\n/**\n * Memory Manager using SQLite + FTS5 for full-text search\n *\n * Features:\n * - FTS5 full-text search (keyword matching)\n * - Optional vector search support (for Plus version)\n * - No embedding provider required\n * - Simple deployment\n * - Cross-platform compatibility\n *\n * v4.11.0: Removed embedding dependency, added FTS5 support\n */\nexport class MemoryManager implements IMemoryManager {\n private db: Database.Database;\n private config: Required<Omit<MemoryManagerConfig, 'embeddingProvider' | 'hnsw' | 'cleanup'>> & {\n embeddingProvider?: unknown;\n };\n private embeddingProvider?: any;\n private initialized: boolean = false;\n private useFTS: boolean = true; // Use FTS5 by default\n\n // Phase 1: Performance optimization\n private entryCount: number = 0; // Internal counter to avoid repeated COUNT(*)\n private statements: {\n countAll?: Database.Statement;\n insert?: Database.Statement;\n deleteById?: Database.Statement;\n deleteOldest?: Database.Statement;\n deleteBeforeCutoff?: Database.Statement;\n updateAccessCount?: Database.Statement;\n } = {}\n\n // Phase 2: Smart cleanup configuration\n private cleanupConfig: {\n enabled: boolean;\n strategy: 'oldest' | 'least_accessed' | 'hybrid';\n triggerThreshold: number;\n targetThreshold: number;\n minCleanupCount: number;\n maxCleanupCount: number;\n retentionDays: number;\n }\n\n private constructor(config: MemoryManagerConfig) {\n // Set default config\n this.config = {\n dbPath: config.dbPath,\n maxEntries: config.maxEntries ?? 10000,\n autoCleanup: config.autoCleanup ?? true,\n cleanupDays: config.cleanupDays ?? 30,\n trackAccess: config.trackAccess ?? true,\n embeddingProvider: config.embeddingProvider\n };\n\n this.embeddingProvider = config.embeddingProvider;\n\n // Phase 2: Initialize smart cleanup configuration with defaults\n const cleanupCfg = config.cleanup || {};\n\n // Handle backward compatibility: autoCleanup → cleanup.enabled\n const enabled = cleanupCfg.enabled ?? config.autoCleanup ?? true;\n\n // Handle backward compatibility: cleanupDays → cleanup.retentionDays\n const retentionDays = cleanupCfg.retentionDays ?? config.cleanupDays ?? 30;\n\n this.cleanupConfig = {\n enabled,\n strategy: cleanupCfg.strategy ?? 'oldest',\n triggerThreshold: cleanupCfg.triggerThreshold ?? 0.9,\n targetThreshold: cleanupCfg.targetThreshold ?? 0.7,\n minCleanupCount: cleanupCfg.minCleanupCount ?? 10,\n maxCleanupCount: cleanupCfg.maxCleanupCount ?? 1000,\n retentionDays\n };\n\n // Validate cleanup configuration\n this.validateCleanupConfig();\n\n // Ensure directory exists\n const dir = dirname(this.config.dbPath);\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n }\n\n // Initialize database\n this.db = new Database(this.config.dbPath);\n this.db.pragma('journal_mode = WAL');\n this.db.pragma('busy_timeout = 5000'); // Wait up to 5 seconds for locks\n }\n\n /**\n * Create MemoryManager instance (async factory)\n */\n static async create(config: MemoryManagerConfig): Promise<MemoryManager> {\n const manager = new MemoryManager(config);\n await manager.initialize();\n return manager;\n }\n\n /**\n * Initialize database and load FTS5 extension\n *\n * v4.11.0: Added FTS5 full-text search support\n */\n private async initialize(): Promise<void> {\n if (this.initialized) return;\n\n try {\n // Load sqlite-vec extension (for Plus version compatibility)\n try {\n sqliteVec.load(this.db);\n } catch (error) {\n // vec extension is optional (only needed for Plus version)\n logger.debug('sqlite-vec extension not loaded (not required for FTS5)', {\n error: (error as Error).message\n });\n }\n\n // Create tables\n // v4.11.0: Removed memory_vectors table (FTS5 only, no vector search)\n this.db.exec(`\n CREATE TABLE IF NOT EXISTS memory_entries (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n content TEXT NOT NULL,\n metadata TEXT NOT NULL,\n created_at INTEGER NOT NULL,\n last_accessed_at INTEGER,\n access_count INTEGER DEFAULT 0\n );\n\n CREATE INDEX IF NOT EXISTS idx_created_at ON memory_entries(created_at);\n CREATE INDEX IF NOT EXISTS idx_access_count ON memory_entries(access_count);\n `);\n\n // Create FTS5 virtual table for full-text search\n // v4.11.0: Removed external content to avoid trigger issues\n this.db.exec(`\n CREATE VIRTUAL TABLE IF NOT EXISTS memory_fts USING fts5(\n content,\n metadata\n );\n\n -- Triggers to keep FTS index in sync\n CREATE TRIGGER IF NOT EXISTS memory_fts_insert AFTER INSERT ON memory_entries BEGIN\n INSERT INTO memory_fts(rowid, content, metadata)\n VALUES (new.id, new.content, new.metadata);\n END;\n\n CREATE TRIGGER IF NOT EXISTS memory_fts_delete AFTER DELETE ON memory_entries BEGIN\n DELETE FROM memory_fts WHERE rowid = old.id;\n END;\n\n CREATE TRIGGER IF NOT EXISTS memory_fts_update AFTER UPDATE ON memory_entries BEGIN\n UPDATE memory_fts\n SET content = new.content, metadata = new.metadata\n WHERE rowid = old.id;\n END;\n `);\n\n // Phase 1: Prepare frequently-used statements for better performance\n this.statements.countAll = this.db.prepare('SELECT COUNT(*) as count FROM memory_entries');\n this.statements.insert = this.db.prepare(`\n INSERT INTO memory_entries (content, metadata, created_at, last_accessed_at, access_count)\n VALUES (?, ?, ?, ?, 0)\n `);\n this.statements.deleteById = this.db.prepare('DELETE FROM memory_entries WHERE id = ?');\n this.statements.deleteOldest = this.db.prepare(`\n DELETE FROM memory_entries\n WHERE id IN (\n SELECT id FROM memory_entries\n ORDER BY created_at ASC\n LIMIT ?\n )\n `);\n this.statements.deleteBeforeCutoff = this.db.prepare(`\n DELETE FROM memory_entries\n WHERE created_at < ?\n `);\n this.statements.updateAccessCount = this.db.prepare(`\n UPDATE memory_entries\n SET access_count = access_count + 1, last_accessed_at = ?\n WHERE id = ?\n `);\n\n // Initialize internal entry counter\n const countResult = this.statements.countAll.get() as { count: number };\n this.entryCount = countResult.count;\n\n this.initialized = true;\n logger.info('MemoryManager initialized successfully', {\n dbPath: this.config.dbPath,\n searchMethod: 'FTS5',\n hasEmbeddingProvider: !!this.embeddingProvider,\n entryCount: this.entryCount\n });\n } catch (error) {\n logger.error('Failed to initialize MemoryManager', { error: (error as Error).message });\n throw new MemoryError(\n `Failed to initialize memory system: ${(error as Error).message}`,\n 'DATABASE_ERROR'\n );\n }\n }\n\n /**\n * Add a new memory entry\n *\n * v4.11.0: Embedding is now optional (only needed for Plus version)\n * v5.0.9: Phase 1 - Transaction atomicity with prepared statements\n */\n async add(content: string, embedding: number[] | null, metadata: MemoryMetadata): Promise<MemoryEntry> {\n if (!this.initialized) {\n throw new MemoryError('Memory manager not initialized', 'DATABASE_ERROR');\n }\n\n // v4.11.0: Embedding validation removed (FTS5 only, no vector search)\n // Note: embedding parameter deprecated but kept for backward compatibility\n\n // Phase 2: Smart cleanup - check threshold before add\n if (this.shouldTriggerCleanup()) {\n try {\n const removed = await this.executeSmartCleanup();\n logger.info('Smart cleanup triggered', {\n removed,\n currentCount: this.entryCount,\n usage: (this.entryCount / this.config.maxEntries * 100).toFixed(1) + '%',\n threshold: (this.cleanupConfig.triggerThreshold * 100).toFixed(0) + '%',\n strategy: this.cleanupConfig.strategy\n });\n } catch (error) {\n logger.warn('Smart cleanup failed', {\n error: (error as Error).message\n });\n }\n }\n\n try {\n const now = Date.now();\n const metadataStr = JSON.stringify(metadata);\n\n // Phase 1.1: Transaction with proper counter synchronization\n // Return deletion count and ID, update counter AFTER transaction succeeds\n const insertTxn = this.db.transaction(() => {\n let deletedCount = 0;\n\n // v5.0.8: Enforce maxEntries limit inside transaction\n if (this.entryCount >= this.config.maxEntries) {\n // Auto-cleanup oldest entries to make room\n const entriesToRemove = Math.min(100, Math.floor(this.config.maxEntries * 0.1));\n const deleteInfo = this.statements.deleteOldest!.run(entriesToRemove);\n deletedCount = deleteInfo.changes;\n\n logger.warn('Memory limit approaching, auto-cleanup triggered', {\n currentCount: this.entryCount,\n maxEntries: this.config.maxEntries,\n removed: deletedCount\n });\n\n // Check if cleanup freed enough space\n if (this.entryCount - deletedCount >= this.config.maxEntries) {\n throw new MemoryError(\n `Memory limit reached (${this.config.maxEntries} entries). Run 'ax memory clear' or increase maxEntries in config.`,\n 'MEMORY_LIMIT'\n );\n }\n }\n\n // Insert entry using prepared statement (FTS5 index is automatically updated via trigger)\n const insertResult = this.statements.insert!.run(content, metadataStr, now, now);\n\n logger.debug('Memory entry added', {\n id: insertResult.lastInsertRowid,\n contentLength: content.length,\n searchMethod: 'FTS5',\n deletedCount\n });\n\n return { id: Number(insertResult.lastInsertRowid), deletedCount };\n });\n\n // Execute transaction and update counter ONLY on success\n const { id, deletedCount } = insertTxn();\n this.entryCount = this.entryCount - deletedCount + 1;\n\n // v4.11.0: No vector storage (FTS5 only)\n\n return {\n id,\n content,\n embedding: [], // v4.11.0: Always empty (FTS5 only)\n metadata,\n createdAt: new Date(now),\n accessCount: 0\n };\n } catch (error) {\n throw new MemoryError(\n `Failed to add memory entry: ${(error as Error).message}`,\n 'DATABASE_ERROR'\n );\n }\n }\n\n /**\n * Search for memories using FTS5 full-text search\n *\n * v4.11.0: Changed from vector search to FTS5 keyword search\n */\n async search(query: MemorySearchQuery): Promise<MemorySearchResult[]> {\n if (!this.initialized) {\n throw new MemoryError('Memory manager not initialized', 'DATABASE_ERROR');\n }\n\n // Use FTS5 for text search (no embedding needed)\n if (!query.text) {\n throw new MemoryError(\n 'Search query must provide text for FTS5 search',\n 'QUERY_ERROR'\n );\n }\n\n try {\n const limit = query.limit || 10;\n\n // Build metadata filter conditions\n const conditions: string[] = [];\n const params: unknown[] = [];\n\n // Apply metadata filters\n if (query.filters) {\n if (query.filters.type) {\n const types = Array.isArray(query.filters.type) ? query.filters.type : [query.filters.type];\n conditions.push(`json_extract(e.metadata, '$.type') IN (${types.map(() => '?').join(',')})`);\n params.push(...types);\n }\n\n if (query.filters.source) {\n const sources = Array.isArray(query.filters.source) ? query.filters.source : [query.filters.source];\n conditions.push(`json_extract(e.metadata, '$.source') IN (${sources.map(() => '?').join(',')})`);\n params.push(...sources);\n }\n\n if (query.filters.agentId) {\n conditions.push(`json_extract(e.metadata, '$.agentId') = ?`);\n params.push(query.filters.agentId);\n }\n\n if (query.filters.sessionId) {\n conditions.push(`json_extract(e.metadata, '$.sessionId') = ?`);\n params.push(query.filters.sessionId);\n }\n\n if (query.filters.tags && query.filters.tags.length > 0) {\n // Check if all required tags are present (AND logic)\n query.filters.tags.forEach(tag => {\n conditions.push(`EXISTS (SELECT 1 FROM json_each(e.metadata, '$.tags') WHERE value = ?)`);\n params.push(tag);\n });\n }\n\n if (query.filters.dateRange?.from) {\n conditions.push('e.created_at >= ?');\n params.push(query.filters.dateRange.from.getTime());\n }\n\n if (query.filters.dateRange?.to) {\n conditions.push('e.created_at <= ?');\n params.push(query.filters.dateRange.to.getTime());\n }\n\n if (query.filters.minImportance !== undefined) {\n conditions.push(`CAST(json_extract(e.metadata, '$.importance') AS REAL) >= ?`);\n params.push(query.filters.minImportance);\n }\n }\n\n // Build WHERE clause for metadata filters\n const metadataWhere = conditions.length > 0 ? ` AND ${conditions.join(' AND ')}` : '';\n\n // Use FTS5 MATCH for full-text search\n // FTS5 returns results sorted by relevance (rank)\n const sql = `\n SELECT\n e.id,\n e.content,\n e.metadata,\n e.created_at,\n e.last_accessed_at,\n e.access_count,\n bm25(memory_fts) as relevance\n FROM memory_fts\n JOIN memory_entries e ON memory_fts.rowid = e.id\n WHERE memory_fts MATCH ?${metadataWhere}\n ORDER BY bm25(memory_fts)\n LIMIT ?\n `;\n\n // FTS5 query syntax: escape special characters and use simple query\n // Remove FTS5 special characters that can cause syntax errors\n // Special chars: . : \" * ( ) [ ] { } ^ $ + | \\ - % < > ~ / @ # & = ? ! ; ' ` , AND OR NOT\n const ftsQuery = query.text\n .replace(/[.:\"*()[\\]{}^$+|\\\\%<>~\\-/@#&=?!;'`,]/g, ' ') // Replace special chars with spaces\n .replace(/\\b(AND|OR|NOT)\\b/gi, ' ') // Remove boolean operators\n .replace(/\\s+/g, ' ') // Normalize whitespace\n .trim();\n\n // If query becomes empty after sanitization, return empty results\n if (!ftsQuery) {\n logger.debug('FTS5 query empty after sanitization', { originalQuery: query.text });\n return [];\n }\n\n const finalParams = [ftsQuery, ...params, limit];\n\n const results = this.db.prepare(sql).all(...finalParams) as any[];\n\n // Phase 1.1: Update access tracking with batch UPDATE for atomicity and performance\n // Note: Cannot use prepared statement here due to dynamic IN (?) clause\n if (this.config.trackAccess && results.length > 0) {\n const now = Date.now();\n const ids = results.map(r => r.id);\n const placeholders = ids.map(() => '?').join(',');\n\n // Batch update: all succeed or all fail (atomic), much faster than N individual updates\n this.db.prepare(`\n UPDATE memory_entries\n SET last_accessed_at = ?, access_count = access_count + 1\n WHERE id IN (${placeholders})\n `).run(now, ...ids);\n }\n\n return results.map(row => {\n // FTS5 rank is negative (higher rank = more relevant)\n // Convert to similarity score (0-1, higher is better)\n const similarity = Math.max(0, Math.min(1, 1 + (row.relevance / 10)));\n\n return {\n entry: {\n id: row.id,\n content: row.content,\n embedding: [], // No embedding in FTS5 mode\n metadata: JSON.parse(row.metadata),\n createdAt: new Date(row.created_at),\n lastAccessedAt: row.last_accessed_at ? new Date(row.last_accessed_at) : undefined,\n accessCount: row.access_count\n },\n similarity,\n distance: 1 - similarity\n };\n });\n } catch (error) {\n throw new MemoryError(\n `Search failed: ${(error as Error).message}`,\n 'QUERY_ERROR'\n );\n }\n }\n\n /**\n * Get memory by ID\n *\n * v4.11.0: No vector loading (FTS5 only)\n */\n async get(id: number): Promise<MemoryEntry | null> {\n if (!this.initialized) {\n throw new MemoryError('Memory manager not initialized', 'DATABASE_ERROR');\n }\n\n try {\n // v4.11.0: No JOIN with memory_vectors (FTS5 only)\n const row = this.db.prepare(`\n SELECT *\n FROM memory_entries\n WHERE id = ?\n `).get(id) as any;\n\n if (!row) return null;\n\n return {\n id: row.id,\n content: row.content,\n embedding: [], // No embedding in FTS5 mode\n metadata: JSON.parse(row.metadata),\n createdAt: new Date(row.created_at),\n lastAccessedAt: row.last_accessed_at ? new Date(row.last_accessed_at) : undefined,\n accessCount: row.access_count\n };\n } catch (error) {\n throw new MemoryError(\n `Failed to get entry: ${(error as Error).message}`,\n 'DATABASE_ERROR'\n );\n }\n }\n\n /**\n * Update memory metadata\n */\n async update(id: number, metadata: Partial<MemoryMetadata>): Promise<void> {\n if (!this.initialized) {\n throw new MemoryError('Memory manager not initialized', 'DATABASE_ERROR');\n }\n\n try {\n // Get existing entry\n const existing = await this.get(id);\n if (!existing) {\n throw new MemoryError(`Memory entry not found: ${id}`, 'ENTRY_NOT_FOUND');\n }\n\n // Merge metadata\n const newMetadata = { ...existing.metadata, ...metadata };\n\n this.db.prepare(`\n UPDATE memory_entries\n SET metadata = ?\n WHERE id = ?\n `).run(JSON.stringify(newMetadata), id);\n\n logger.debug('Memory entry updated', { id });\n } catch (error) {\n if (error instanceof MemoryError) throw error;\n throw new MemoryError(\n `Failed to update entry: ${(error as Error).message}`,\n 'DATABASE_ERROR'\n );\n }\n }\n\n /**\n * Delete memory by ID\n */\n async delete(id: number): Promise<void> {\n if (!this.initialized) {\n throw new MemoryError('Memory manager not initialized', 'DATABASE_ERROR');\n }\n\n try {\n // Check if entry exists\n const existing = await this.get(id);\n if (!existing) {\n throw new MemoryError(`Memory entry not found: ${id}`, 'ENTRY_NOT_FOUND');\n }\n\n // Phase 1: Use prepared statement and maintain entryCount\n const deleteInfo = this.statements.deleteById!.run(id);\n if (deleteInfo.changes > 0) {\n this.entryCount -= deleteInfo.changes;\n }\n\n logger.debug('Memory entry deleted', { id, newCount: this.entryCount });\n } catch (error) {\n if (error instanceof MemoryError) throw error;\n throw new MemoryError(\n `Failed to delete entry: ${(error as Error).message}`,\n 'DATABASE_ERROR'\n );\n }\n }\n\n /**\n * Get all memory entries with optional filtering and pagination\n */\n async getAll(options?: {\n type?: string;\n tags?: string[];\n limit?: number;\n offset?: number;\n orderBy?: 'created' | 'accessed' | 'count';\n order?: 'asc' | 'desc';\n }): Promise<MemoryEntry[]> {\n if (!this.initialized) {\n throw new MemoryError('Memory manager not initialized', 'DATABASE_ERROR');\n }\n\n try {\n const conditions: string[] = [];\n const params: any[] = [];\n\n // Build WHERE clause with filters\n if (options?.type) {\n conditions.push(\"json_extract(e.metadata, '$.type') = ?\");\n params.push(options.type);\n }\n\n if (options?.tags && options.tags.length > 0) {\n // Check if any of the provided tags exist in the entry's tags array\n const tagConditions = options.tags.map(() =>\n \"EXISTS (SELECT 1 FROM json_each(json_extract(e.metadata, '$.tags')) WHERE value = ?)\"\n );\n conditions.push(`(${tagConditions.join(' OR ')})`);\n params.push(...options.tags);\n }\n\n const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';\n\n // Build ORDER BY clause\n let orderByClause = 'ORDER BY e.created_at DESC';\n if (options?.orderBy) {\n const column = options.orderBy === 'created' ? 'e.created_at' :\n options.orderBy === 'accessed' ? 'e.last_accessed_at' :\n 'e.access_count';\n const direction = options.order || 'desc';\n orderByClause = `ORDER BY ${column} ${direction.toUpperCase()}`;\n }\n\n // Build LIMIT clause\n const limitClause = options?.limit ? `LIMIT ${options.limit}` : '';\n const offsetClause = options?.offset ? `OFFSET ${options.offset}` : '';\n\n // v4.11.0: No JOIN with memory_vectors (FTS5 only)\n const sql = `\n SELECT e.*\n FROM memory_entries e\n ${whereClause}\n ${orderByClause}\n ${limitClause}\n ${offsetClause}\n `;\n\n const rows = this.db.prepare(sql).all(...params) as any[];\n\n return rows.map(row => {\n return {\n id: row.id,\n content: row.content,\n embedding: [], // No embedding in FTS5 mode\n metadata: JSON.parse(row.metadata),\n createdAt: new Date(row.created_at),\n lastAccessedAt: row.last_accessed_at ? new Date(row.last_accessed_at) : undefined,\n accessCount: row.access_count\n };\n });\n } catch (error) {\n throw new MemoryError(\n `Failed to retrieve entries: ${(error as Error).message}`,\n 'DATABASE_ERROR'\n );\n }\n }\n\n /**\n * Clear all memories\n */\n async clear(): Promise<void> {\n if (!this.initialized) {\n throw new MemoryError('Memory manager not initialized', 'DATABASE_ERROR');\n }\n\n try {\n this.db.prepare('DELETE FROM memory_entries').run();\n // Phase 1: Reset internal counter\n this.entryCount = 0;\n\n this.db.prepare('VACUUM').run();\n logger.info('All memory entries cleared');\n } catch (error) {\n throw new MemoryError(\n `Failed to clear entries: ${(error as Error).message}`,\n 'DATABASE_ERROR'\n );\n }\n }\n\n /**\n * Get memory statistics\n */\n async getStats(): Promise<MemoryStats> {\n if (!this.initialized) {\n throw new MemoryError('Memory manager not initialized', 'DATABASE_ERROR');\n }\n\n try {\n const count = this.db.prepare('SELECT COUNT(*) as count FROM memory_entries').get() as { count: number };\n const size = this.db.prepare('SELECT page_count * page_size as size FROM pragma_page_count(), pragma_page_size()').get() as { size: number };\n\n return {\n totalEntries: count.count,\n dbSize: size.size,\n indexSize: 0, // vec extension handles indexing internally\n memoryUsage: process.memoryUsage().heapUsed\n };\n } catch (error) {\n throw new MemoryError(\n `Failed to get stats: ${(error as Error).message}`,\n 'DATABASE_ERROR'\n );\n }\n }\n\n /**\n * Cleanup old entries\n */\n /**\n * Get total count of memory entries\n * v5.0.8: Added for maxEntries enforcement\n */\n /**\n * Get current entry count\n * Phase 1: Use internal counter instead of COUNT(*) for better performance\n */\n private getCount(): number {\n if (!this.initialized) {\n return 0;\n }\n\n // Return internal counter (maintained by transactions)\n return this.entryCount;\n }\n\n /**\n * Phase 2: Validate cleanup configuration\n * v5.0.10 Phase 2.1: Added validation for maxCleanupCount and retentionDays\n * @throws {MemoryError} if configuration is invalid\n */\n private validateCleanupConfig(): void {\n const cfg = this.cleanupConfig;\n\n if (cfg.triggerThreshold < 0.5 || cfg.triggerThreshold > 1.0) {\n throw new MemoryError(\n 'cleanup.triggerThreshold must be between 0.5 and 1.0',\n 'CONFIG_ERROR'\n );\n }\n\n if (cfg.targetThreshold < 0.1 || cfg.targetThreshold > 0.9) {\n throw new MemoryError(\n 'cleanup.targetThreshold must be between 0.1 and 0.9',\n 'CONFIG_ERROR'\n );\n }\n\n if (cfg.targetThreshold >= cfg.triggerThreshold) {\n throw new MemoryError(\n 'cleanup.targetThreshold must be less than triggerThreshold',\n 'CONFIG_ERROR'\n );\n }\n\n if (cfg.minCleanupCount < 1) {\n throw new MemoryError(\n 'cleanup.minCleanupCount must be at least 1',\n 'CONFIG_ERROR'\n );\n }\n\n // Phase 2.1: Validate maxCleanupCount is positive\n if (cfg.maxCleanupCount < 1) {\n throw new MemoryError(\n 'cleanup.maxCleanupCount must be at least 1',\n 'CONFIG_ERROR'\n );\n }\n\n if (cfg.maxCleanupCount < cfg.minCleanupCount) {\n throw new MemoryError(\n 'cleanup.maxCleanupCount must be >= minCleanupCount',\n 'CONFIG_ERROR'\n );\n }\n\n // Phase 2.1: Validate retentionDays is positive\n if (cfg.retentionDays < 1) {\n throw new MemoryError(\n 'cleanup.retentionDays must be at least 1',\n 'CONFIG_ERROR'\n );\n }\n }\n\n /**\n * Phase 2: Check if cleanup should be triggered based on usage threshold\n */\n private shouldTriggerCleanup(): boolean {\n if (!this.cleanupConfig.enabled) {\n return false;\n }\n\n const currentUsage = this.entryCount / this.config.maxEntries;\n return currentUsage >= this.cleanupConfig.triggerThreshold;\n }\n\n /**\n * Phase 2: Calculate how many entries to remove to reach target threshold\n */\n private calculateCleanupCount(): number {\n const targetCount = Math.floor(\n this.config.maxEntries * this.cleanupConfig.targetThreshold\n );\n const toRemove = this.entryCount - targetCount;\n\n // Phase 2.1: If already below target, don't cleanup\n if (toRemove <= 0) {\n return 0;\n }\n\n // Enforce min/max bounds\n return Math.max(\n this.cleanupConfig.minCleanupCount,\n Math.min(this.cleanupConfig.maxCleanupCount, toRemove)\n );\n }\n\n /**\n * Phase 2: Execute cleanup with configured strategy\n * @returns Number of entries removed\n */\n private async executeSmartCleanup(): Promise<number> {\n const count = this.calculateCleanupCount();\n\n logger.debug('Executing smart cleanup', {\n strategy: this.cleanupConfig.strategy,\n count,\n currentCount: this.entryCount,\n threshold: this.cleanupConfig.triggerThreshold\n });\n\n // Phase 2.1: All cleanup methods now return actual deleted count\n switch (this.cleanupConfig.strategy) {\n case 'oldest':\n return await this.cleanupOldest(count);\n\n case 'least_accessed':\n return await this.cleanupLeastAccessed(count);\n\n case 'hybrid':\n return await this.cleanupHybrid(count);\n\n default:\n throw new MemoryError(\n `Unknown cleanup strategy: ${this.cleanupConfig.strategy}`,\n 'CONFIG_ERROR'\n );\n }\n }\n\n /**\n * Remove oldest entries\n * v5.0.8: Added for automatic cleanup when approaching maxEntries\n * v5.0.10 Phase 2: Enhanced logging with strategy info\n * v5.0.10 Phase 2.1: Now returns actual deleted count\n */\n private async cleanupOldest(count: number): Promise<number> {\n if (!this.initialized || count <= 0) {\n return 0;\n }\n\n try {\n // Phase 1: Use prepared statement and maintain entryCount\n const deleteInfo = this.statements.deleteOldest!.run(count);\n if (deleteInfo.changes > 0) {\n this.entryCount -= deleteInfo.changes;\n }\n\n logger.info('Cleaned up oldest entries', {\n requested: count,\n deleted: deleteInfo.changes,\n newCount: this.entryCount,\n strategy: 'oldest' // Phase 2: Add strategy info\n });\n\n return deleteInfo.changes;\n } catch (error) {\n logger.error('Failed to cleanup oldest entries', {\n count,\n error: (error as Error).message\n });\n return 0;\n }\n }\n\n /**\n * Phase 2: Remove least accessed entries\n * v5.0.10 Phase 2.1: Now async to support fallback to cleanupOldest\n * @param count Number of entries to remove\n * @returns Number of entries actually removed\n */\n private async cleanupLeastAccessed(count: number): Promise<number> {\n if (!this.initialized || count <= 0) {\n return 0;\n }\n\n if (!this.config.trackAccess) {\n logger.warn('least_accessed strategy requires trackAccess=true, falling back to oldest');\n return await this.cleanupOldest(count); // Phase 2.1: Properly await fallback\n }\n\n try {\n const deleteInfo = this.db.prepare(`\n DELETE FROM memory_entries\n WHERE id IN (\n SELECT id FROM memory_entries\n ORDER BY access_count ASC, last_accessed_at ASC\n LIMIT ?\n )\n `).run(count);\n\n if (deleteInfo.changes > 0) {\n this.entryCount -= deleteInfo.changes;\n }\n\n logger.info('Cleaned up least accessed entries', {\n requested: count,\n deleted: deleteInfo.changes,\n newCount: this.entryCount,\n strategy: 'least_accessed'\n });\n\n return deleteInfo.changes;\n } catch (error) {\n logger.error('Failed to cleanup least accessed entries', {\n count,\n error: (error as Error).message\n });\n return 0;\n }\n }\n\n /**\n * Phase 2: Remove entries using hybrid strategy (access count + age)\n * v5.0.10 Phase 2.1: Now async for consistency with other cleanup methods\n * @param count Number of entries to remove\n * @returns Number of entries actually removed\n */\n private async cleanupHybrid(count: number): Promise<number> {\n if (!this.initialized || count <= 0) {\n return 0;\n }\n\n try {\n const deleteInfo = this.db.prepare(`\n DELETE FROM memory_entries\n WHERE id IN (\n SELECT id FROM memory_entries\n ORDER BY\n access_count ASC,\n created_at ASC\n LIMIT ?\n )\n `).run(count);\n\n if (deleteInfo.changes > 0) {\n this.entryCount -= deleteInfo.changes;\n }\n\n logger.info('Cleaned up entries using hybrid strategy', {\n requested: count,\n deleted: deleteInfo.changes,\n newCount: this.entryCount,\n strategy: 'hybrid'\n });\n\n return deleteInfo.changes;\n } catch (error) {\n logger.error('Failed to cleanup with hybrid strategy', {\n count,\n error: (error as Error).message\n });\n return 0;\n }\n }\n\n async cleanup(olderThanDays?: number): Promise<number> {\n if (!this.initialized) {\n throw new MemoryError('Memory manager not initialized', 'DATABASE_ERROR');\n }\n\n const days = olderThanDays || this.config.cleanupDays;\n const cutoffTime = Date.now() - (days * 24 * 60 * 60 * 1000);\n\n try {\n // Phase 1: Use prepared statement and maintain entryCount\n const deleteInfo = this.statements.deleteBeforeCutoff!.run(cutoffTime);\n const deleted = deleteInfo.changes;\n\n if (deleted > 0) {\n this.entryCount -= deleted;\n this.db.prepare('VACUUM').run();\n logger.info('Cleanup completed', {\n deleted,\n olderThanDays: days,\n newCount: this.entryCount\n });\n }\n\n return deleted;\n } catch (error) {\n throw new MemoryError(\n `Cleanup failed: ${(error as Error).message}`,\n 'DATABASE_ERROR'\n );\n }\n }\n\n /**\n * Close database\n */\n async close(): Promise<void> {\n if (this.db) {\n this.db.close();\n this.initialized = false;\n logger.info('MemoryManager closed');\n }\n }\n\n // Stub implementations for interface compliance\n async saveIndex(): Promise<void> {\n // sqlite-vec handles indexing automatically\n }\n\n async loadIndex(): Promise<void> {\n // sqlite-vec handles indexing automatically\n }\n\n async backup(destPath: string): Promise<void> {\n if (!this.initialized) {\n throw new MemoryError('Memory manager not initialized', 'DATABASE_ERROR');\n }\n\n try {\n // Ensure destination directory exists\n const { dirname } = await import('path');\n const { mkdir } = await import('fs/promises');\n const destDir = dirname(destPath);\n await mkdir(destDir, { recursive: true });\n\n // Use better-sqlite3 backup API (async in v12+)\n // backup() copies FROM source TO destination path\n await this.db.backup(destPath);\n\n logger.info('Database backup created', { destPath });\n } catch (error) {\n throw new MemoryError(\n `Failed to create backup: ${(error as Error).message}`,\n 'DATABASE_ERROR',\n { destPath, error }\n );\n }\n }\n\n async restore(srcPath: string): Promise<void> {\n if (!this.initialized) {\n throw new MemoryError('Memory manager not initialized', 'DATABASE_ERROR');\n }\n\n try {\n // Validate source exists\n if (!existsSync(srcPath)) {\n throw new MemoryError(\n `Backup file not found: ${srcPath}`,\n 'DATABASE_ERROR',\n { srcPath }\n );\n }\n\n // Close current database and reset state\n // Phase 2.1 Fix: Must reset all state before reinitializing\n this.db.close();\n this.initialized = false;\n this.entryCount = 0;\n this.statements = {};\n\n // Copy backup to current location using better-sqlite3's backup method\n const srcDb = new Database(srcPath, { readonly: true });\n const destDb = new Database(this.config.dbPath);\n await srcDb.backup(this.config.dbPath);\n srcDb.close();\n destDb.close();\n\n // Reopen database\n this.db = new Database(this.config.dbPath);\n this.db.pragma('journal_mode = WAL');\n this.db.pragma('busy_timeout = 5000'); // Wait up to 5 seconds for locks\n\n // Phase 2.1 Fix: Reinitialize completely (rebuild statements, recount entries)\n // This ensures prepared statements are bound to the new connection\n await this.initialize();\n\n logger.info('Database restored successfully', { srcPath });\n } catch (error) {\n throw new MemoryError(\n `Failed to restore database: ${(error as Error).message}`,\n 'DATABASE_ERROR',\n { srcPath, error }\n );\n }\n }\n\n async exportToJSON(\n filePath: string,\n options?: import('../types/memory.js').ExportOptions\n ): Promise<import('../types/memory.js').ExportResult> {\n if (!this.initialized) {\n throw new MemoryError('Memory manager not initialized', 'DATABASE_ERROR');\n }\n\n const {\n includeEmbeddings = false,\n filters = {},\n batchSize = 1000,\n pretty = false\n } = options || {};\n\n try {\n // Ensure destination directory exists\n const destDir = dirname(filePath);\n if (!existsSync(destDir)) {\n mkdirSync(destDir, { recursive: true });\n }\n\n // Build query with filters\n // v4.11.0: No JOIN with memory_vectors (FTS5 only, no embeddings)\n let query = 'SELECT e.* FROM memory_entries e';\n const conditions: string[] = [];\n const params: unknown[] = [];\n\n // Apply filters\n if (filters.type) {\n const types = Array.isArray(filters.type) ? filters.type : [filters.type];\n conditions.push(`json_extract(e.metadata, '$.type') IN (${types.map(() => '?').join(',')})`);\n params.push(...types);\n }\n\n if (filters.source) {\n const sources = Array.isArray(filters.source) ? filters.source : [filters.source];\n conditions.push(`json_extract(e.metadata, '$.source') IN (${sources.map(() => '?').join(',')})`);\n params.push(...sources);\n }\n\n if (filters.agentId) {\n conditions.push(`json_extract(e.metadata, '$.agentId') = ?`);\n params.push(filters.agentId);\n }\n\n if (filters.sessionId) {\n conditions.push(`json_extract(e.metadata, '$.sessionId') = ?`);\n params.push(filters.sessionId);\n }\n\n if (filters.dateRange?.from) {\n conditions.push('e.created_at >= ?');\n params.push(filters.dateRange.from.getTime());\n }\n\n if (filters.dateRange?.to) {\n conditions.push('e.created_at <= ?');\n params.push(filters.dateRange.to.getTime());\n }\n\n if (filters.minImportance !== undefined) {\n conditions.push(`CAST(json_extract(e.metadata, '$.importance') AS REAL) >= ?`);\n params.push(filters.minImportance);\n }\n\n if (conditions.length > 0) {\n query += ' WHERE ' + conditions.join(' AND ');\n }\n\n // Execute query\n const rows = this.db.prepare(query).all(...params) as Array<{\n id: number;\n content: string;\n metadata: string;\n created_at: number;\n last_accessed_at: number | null;\n access_count: number;\n embedding: Buffer | null;\n }>;\n\n // Build export data\n const entries = rows.map(row => {\n const entry: {\n id: number;\n content: string;\n embedding?: number[];\n metadata: MemoryMetadata;\n createdAt: string;\n lastAccessedAt?: string;\n accessCount: number;\n } = {\n id: row.id,\n content: row.content,\n metadata: JSON.parse(row.metadata),\n createdAt: new Date(row.created_at).toISOString(),\n accessCount: row.access_count\n };\n\n if (row.last_accessed_at) {\n entry.lastAccessedAt = new Date(row.last_accessed_at).toISOString();\n }\n\n // v4.11.0: No embeddings in FTS5 mode\n\n return entry;\n });\n\n // Create export object\n const exportData: import('../types/memory.js').MemoryExport = {\n version: '4.11.0', // v4.11.0: Updated version\n metadata: {\n exportedAt: new Date().toISOString(),\n totalEntries: entries.length,\n includesEmbeddings: false // v4.11.0: Always false (FTS5 only)\n },\n entries\n };\n\n // Write to file\n const { writeFile } = await import('fs/promises');\n const json = pretty ? JSON.stringify(exportData, null, 2) : JSON.stringify(exportData);\n await writeFile(filePath, json, 'utf-8');\n\n const sizeBytes = Buffer.byteLength(json, 'utf-8');\n\n logger.info('Memory exported to JSON', {\n filePath,\n entriesExported: entries.length,\n sizeBytes\n });\n\n return {\n entriesExported: entries.length,\n sizeBytes,\n filePath,\n exportedAt: new Date()\n };\n } catch (error) {\n throw new MemoryError(\n `Export failed: ${(error as Error).message}`,\n 'DATABASE_ERROR',\n { filePath, error }\n );\n }\n }\n\n async importFromJSON(\n filePath: string,\n options?: import('../types/memory.js').ImportOptions\n ): Promise<import('../types/memory.js').ImportResult> {\n if (!this.initialized) {\n throw new MemoryError('Memory manager not initialized', 'DATABASE_ERROR');\n }\n\n const {\n skipDuplicates = true,\n batchSize = 100,\n validate = true,\n clearExisting = false\n } = options || {};\n\n try {\n // Validate import file exists\n if (!existsSync(filePath)) {\n throw new MemoryError(\n `Import file not found: ${filePath}`,\n 'DATABASE_ERROR',\n { filePath }\n );\n }\n\n // Read import file\n const { readFile } = await import('fs/promises');\n const content = await readFile(filePath, 'utf-8');\n const importData = JSON.parse(content) as import('../types/memory.js').MemoryExport;\n\n // Validate format version\n const SUPPORTED_VERSIONS = ['1.0', '4.0.0', '4.11.0'];\n if (!importData.version || !SUPPORTED_VERSIONS.includes(importData.version)) {\n throw new MemoryError(\n `Unsupported export format version: ${importData.version}. Supported versions: ${SUPPORTED_VERSIONS.join(', ')}`,\n 'DATABASE_ERROR',\n { version: importData.version, supportedVersions: SUPPORTED_VERSIONS }\n );\n }\n\n // Validate format\n if (!importData.entries || !Array.isArray(importData.entries)) {\n throw new MemoryError(\n 'Invalid import format: missing entries array',\n 'DATABASE_ERROR'\n );\n }\n\n // Clear existing data if requested\n if (clearExisting) {\n await this.clear();\n }\n\n let entriesImported = 0;\n let entriesSkipped = 0;\n let entriesFailed = 0;\n const errors: Array<{ entry: unknown; error: string }> = [];\n\n // Track existing content hashes for duplicate detection\n const existingHashes = new Set<string>();\n if (skipDuplicates) {\n const existing = this.db.prepare('SELECT content FROM memory_entries').all() as Array<{ content: string }>;\n existing.forEach(row => {\n existingHashes.add(this.hashContent(row.content));\n });\n }\n\n // Process entries in batches\n for (let i = 0; i < importData.entries.length; i += batchSize) {\n const batch = importData.entries.slice(i, i + batchSize);\n\n for (const entry of batch) {\n try {\n // Validate entry if requested\n if (validate) {\n if (!entry.content || !entry.metadata) {\n throw new Error('Missing required fields: content or metadata');\n }\n // v4.11.0: Embedding validation removed (FTS5 only, no vector search)\n }\n\n // Check for duplicates\n if (skipDuplicates) {\n const hash = this.hashContent(entry.content);\n if (existingHashes.has(hash)) {\n entriesSkipped++;\n continue;\n }\n existingHashes.add(hash);\n }\n\n // Import entry\n // v4.11.0: No embedding generation (FTS5 only)\n await this.add(\n entry.content,\n null, // No embedding needed for FTS5\n entry.metadata\n );\n\n entriesImported++;\n } catch (error) {\n entriesFailed++;\n errors.push({\n entry,\n error: (error as Error).message\n });\n }\n }\n }\n\n logger.info('Memory imported from JSON', {\n filePath,\n entriesImported,\n entriesSkipped,\n entriesFailed\n });\n\n return {\n entriesImported,\n entriesSkipped,\n entriesFailed,\n errors,\n importedAt: new Date()\n };\n } catch (error) {\n throw new MemoryError(\n `Import failed: ${(error as Error).message}`,\n 'DATABASE_ERROR',\n { filePath, error }\n );\n }\n }\n\n /**\n * Hash content for duplicate detection\n */\n private hashContent(content: string): string {\n // Simple hash using content length + first/last 100 chars\n // For production, consider using crypto.createHash('sha256')\n const len = content.length;\n const start = content.substring(0, 100);\n const end = content.substring(Math.max(0, len - 100));\n return `${len}:${start}:${end}`;\n }\n}\n","/**\n * Memory System Types\n *\n * Defines types for the AutomatosX memory system using SQLite + HNSW\n */\n\n/**\n * Memory entry stored in the system\n */\nexport interface MemoryEntry {\n /** Unique identifier */\n id: number;\n\n /** Content/text of the memory */\n content: string;\n\n /** Vector embedding (1536 dimensions for OpenAI/Claude) */\n embedding: number[];\n\n /** Additional metadata */\n metadata: MemoryMetadata;\n\n /** Creation timestamp */\n createdAt: Date;\n\n /** Last access timestamp */\n lastAccessedAt?: Date;\n\n /** Access count */\n accessCount: number;\n\n /** Relevance score (optional, set during search) */\n score?: number;\n}\n\n/**\n * Metadata associated with memory entries\n */\nexport interface MemoryMetadata {\n /** Type of memory entry */\n type: 'conversation' | 'code' | 'document' | 'task' | 'other';\n\n /** Source of the memory */\n source: string;\n\n /** Associated agent ID */\n agentId?: string;\n\n /** Associated session ID */\n sessionId?: string;\n\n /** Tags for categorization */\n tags?: string[];\n\n /** Importance score (0-1) */\n importance?: number;\n\n /** Custom metadata */\n [key: string]: unknown;\n}\n\n/**\n * Search query for finding memories\n */\nexport interface MemorySearchQuery {\n /** Query vector for similarity search */\n vector?: number[];\n\n /** Text query (will be converted to vector) */\n text?: string;\n\n /** Metadata filters */\n filters?: MemoryFilter;\n\n /** Number of results to return */\n limit?: number;\n\n /** Minimum similarity threshold (0-1) */\n threshold?: number;\n\n /** Include embeddings in results */\n includeEmbeddings?: boolean;\n}\n\n/**\n * Metadata filters for memory search\n */\nexport interface MemoryFilter {\n /** Filter by type */\n type?: MemoryMetadata['type'] | MemoryMetadata['type'][];\n\n /** Filter by source */\n source?: string | string[];\n\n /** Filter by agent ID */\n agentId?: string;\n\n /** Filter by session ID */\n sessionId?: string;\n\n /** Filter by tags (AND logic) */\n tags?: string[];\n\n /** Filter by date range */\n dateRange?: {\n from?: Date;\n to?: Date;\n };\n\n /** Filter by importance */\n minImportance?: number;\n}\n\n/**\n * Search result with similarity score\n */\nexport interface MemorySearchResult {\n /** Memory entry */\n entry: MemoryEntry;\n\n /** Similarity score (0-1, higher is more similar) */\n similarity: number;\n\n /** Distance metric (for HNSW, lower is more similar) */\n distance: number;\n}\n\n/**\n * Memory manager configuration\n */\nexport interface MemoryManagerConfig {\n /** Database file path */\n dbPath: string;\n\n /** HNSW index parameters */\n hnsw?: {\n /** Number of connections per layer (default: 16) */\n M?: number;\n\n /** Size of dynamic candidate list (default: 200) */\n efConstruction?: number;\n\n /** Size of dynamic candidate list for search (default: 50) */\n efSearch?: number;\n };\n\n /** Maximum number of entries (default: 10000) */\n maxEntries?: number;\n\n /**\n * Smart cleanup configuration (v5.0.10 Phase 2)\n */\n cleanup?: {\n /** Enable automatic cleanup (default: true) */\n enabled?: boolean;\n\n /** Cleanup strategy (default: 'oldest') */\n strategy?: 'oldest' | 'least_accessed' | 'hybrid';\n\n /** Trigger cleanup when usage reaches this threshold (default: 0.9 = 90%) */\n triggerThreshold?: number;\n\n /** Clean until usage reaches this target (default: 0.7 = 70%) */\n targetThreshold?: number;\n\n /** Minimum number of entries to remove per cleanup (default: 10) */\n minCleanupCount?: number;\n\n /** Maximum number of entries to remove per cleanup (default: 1000) */\n maxCleanupCount?: number;\n\n /** Days to keep entries for time-based cleanup (default: 30) */\n retentionDays?: number;\n };\n\n /**\n * @deprecated Use cleanup.enabled instead (backward compatibility)\n * Auto-cleanup old entries\n */\n autoCleanup?: boolean;\n\n /**\n * @deprecated Use cleanup.retentionDays instead (backward compatibility)\n * Days to keep entries (default: 30)\n */\n cleanupDays?: number;\n\n /** Enable access tracking */\n trackAccess?: boolean;\n\n /** Embedding provider for text-to-vector conversion (required for text queries) */\n embeddingProvider?: unknown; // IEmbeddingProvider - use unknown to avoid circular dependency\n}\n\n/**\n * Memory statistics\n */\nexport interface MemoryStats {\n /** Total number of entries */\n totalEntries: number;\n\n /** Database size in bytes */\n dbSize: number;\n\n /** Index size in bytes (estimated) */\n indexSize: number;\n\n /** Memory usage in bytes */\n memoryUsage: number;\n\n /** Average search time (ms) */\n avgSearchTime?: number;\n\n /** Last cleanup timestamp */\n lastCleanup?: Date;\n}\n\n/**\n * Export options for JSON export\n */\nexport interface ExportOptions {\n /** Include embeddings in export (default: false) */\n includeEmbeddings?: boolean;\n\n /** Filters for selective export */\n filters?: MemoryFilter;\n\n /** Batch size for streaming large datasets (default: 1000) */\n batchSize?: number;\n\n /** Pretty print JSON (default: false) */\n pretty?: boolean;\n}\n\n/**\n * Export result\n */\nexport interface ExportResult {\n /** Number of entries exported */\n entriesExported: number;\n\n /** Total size in bytes */\n sizeBytes: number;\n\n /** Export file path */\n filePath: string;\n\n /** Export timestamp */\n exportedAt: Date;\n}\n\n/**\n * Import options for JSON import\n */\nexport interface ImportOptions {\n /** Skip duplicate entries (by content hash) */\n skipDuplicates?: boolean;\n\n /** Batch size for processing (default: 100) */\n batchSize?: number;\n\n /** Validate entries before import */\n validate?: boolean;\n\n /** Clear existing data before import */\n clearExisting?: boolean;\n}\n\n/**\n * Import result\n */\nexport interface ImportResult {\n /** Number of entries imported */\n entriesImported: number;\n\n /** Number of entries skipped (duplicates) */\n entriesSkipped: number;\n\n /** Number of entries failed */\n entriesFailed: number;\n\n /** Import errors */\n errors: Array<{ entry: unknown; error: string }>;\n\n /** Import timestamp */\n importedAt: Date;\n}\n\n/**\n * JSON export format\n */\nexport interface MemoryExport {\n /** Format version */\n version: string;\n\n /** Export metadata */\n metadata: {\n exportedAt: string;\n totalEntries: number;\n includesEmbeddings: boolean;\n };\n\n /** Memory entries */\n entries: Array<{\n id: number;\n content: string;\n embedding?: number[];\n metadata: MemoryMetadata;\n createdAt: string;\n lastAccessedAt?: string;\n accessCount: number;\n }>;\n}\n\n/**\n * Memory manager interface\n */\nexport interface IMemoryManager {\n /**\n * Add a new memory entry\n *\n * v4.11.0: Embedding is now optional (null allowed for FTS5-only mode)\n */\n add(content: string, embedding: number[] | null, metadata: MemoryMetadata): Promise<MemoryEntry>;\n\n /**\n * Search for similar memories\n */\n search(query: MemorySearchQuery): Promise<MemorySearchResult[]>;\n\n /**\n * Get memory by ID\n */\n get(id: number): Promise<MemoryEntry | null>;\n\n /**\n * Update memory metadata\n */\n update(id: number, metadata: Partial<MemoryMetadata>): Promise<void>;\n\n /**\n * Delete memory by ID\n */\n delete(id: number): Promise<void>;\n\n /**\n * Clear all memories\n */\n clear(): Promise<void>;\n\n /**\n * Get memory statistics\n */\n getStats(): Promise<MemoryStats>;\n\n /**\n * Cleanup old entries\n */\n cleanup(olderThanDays?: number): Promise<number>;\n\n /**\n * Save index to disk\n */\n saveIndex(): Promise<void>;\n\n /**\n * Load index from disk\n */\n loadIndex(): Promise<void>;\n\n /**\n * Close database and save index\n */\n close(): Promise<void>;\n\n /**\n * Backup database to destination path\n */\n backup(destPath: string, onProgress?: (progress: number) => void): Promise<void>;\n\n /**\n * Restore database from backup\n */\n restore(srcPath: string): Promise<void>;\n\n /**\n * Export memories to JSON\n */\n exportToJSON(filePath: string, options?: ExportOptions): Promise<ExportResult>;\n\n /**\n * Import memories from JSON\n */\n importFromJSON(filePath: string, options?: ImportOptions): Promise<ImportResult>;\n}\n\n/**\n * Memory error types\n */\nexport class MemoryError extends Error {\n constructor(\n message: string,\n public readonly code: MemoryErrorCode,\n public readonly context?: Record<string, unknown>\n ) {\n super(message);\n this.name = 'MemoryError';\n }\n}\n\nexport type MemoryErrorCode =\n | 'ENTRY_NOT_FOUND'\n | 'INVALID_VECTOR'\n | 'DATABASE_ERROR'\n | 'INDEX_ERROR'\n | 'QUERY_ERROR'\n | 'CAPACITY_EXCEEDED'\n | 'PROVIDER_MISSING'\n | 'EMBEDDING_GENERATION_FAILED'\n | 'MEMORY_LIMIT' // v5.0.8: Memory limit reached\n | 'CONFIG_ERROR'; // v5.0.10 Phase 2: Invalid configuration\n","/**\n * Session Manager - Manages multi-agent collaborative sessions\n *\n * @module core/session-manager\n * @since v4.7.0\n */\n\nimport { randomUUID } from 'crypto';\nimport { readFile, writeFile, mkdir, rename, copyFile, unlink } from 'fs/promises';\nimport { dirname } from 'path';\nimport type { Session } from '../types/orchestration.js';\nimport { SessionError } from '../types/orchestration.js';\nimport { logger } from '../utils/logger.js';\n\n/**\n * Session Manager\n *\n * Manages the lifecycle of multi-agent collaborative sessions, providing:\n * - Session creation and tracking\n * - Agent participation tracking\n * - Session completion and failure handling\n * - Automatic cleanup of old sessions\n *\n * @example\n * ```typescript\n * const sessionManager = new SessionManager();\n *\n * // Create session\n * const session = await sessionManager.createSession(\n * 'Implement auth feature',\n * 'backend'\n * );\n *\n * // Add agents as they join\n * await sessionManager.addAgent(session.id, 'frontend');\n * await sessionManager.addAgent(session.id, 'security');\n *\n * // Complete session\n * await sessionManager.completeSession(session.id);\n * ```\n */\nexport class SessionManager {\n /** Active sessions (in-memory, keyed by session ID) */\n private activeSessions: Map<string, Session> = new Map();\n\n /** Maximum number of sessions to keep in memory (oldest are cleaned up) */\n private readonly MAX_SESSIONS: number;\n\n /** Path to persistence file (optional) */\n private readonly persistencePath?: string;\n\n /** Pending save operation (for debouncing) */\n private saveTimeout?: NodeJS.Timeout;\n\n /** Pending save promise (for flushing) */\n private pendingSave?: Promise<void>;\n\n /** Maximum metadata size (10 KB) */\n private readonly MAX_METADATA_SIZE = 10 * 1024;\n\n /** UUID v4 validation regex (static for performance) */\n private static readonly UUID_V4_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n\n /**\n * Validate session ID format (must be valid UUID v4)\n *\n * @param sessionId - Session ID to validate\n * @throws {SessionError} If session ID is invalid\n * @private\n */\n private validateSessionId(sessionId: string): void {\n // Check for empty/whitespace session ID\n if (!sessionId || sessionId.trim().length === 0) {\n throw new SessionError(\n 'Session ID cannot be empty. Must be a valid UUID v4.',\n sessionId,\n 'invalid_format'\n );\n }\n\n // UUID v4 format: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\n // where y is 8, 9, a, or b\n if (!SessionManager.UUID_V4_REGEX.test(sessionId)) {\n throw new SessionError(\n `Invalid session ID format: ${sessionId}. Session IDs must be valid UUID v4.`,\n sessionId,\n 'invalid_format'\n );\n }\n }\n\n /**\n * Create SessionManager instance\n *\n * @param config - Configuration options\n * @param config.persistencePath - Optional path to JSON file for persistence\n * @param config.maxSessions - Maximum sessions to keep in memory (default: 100)\n *\n * @example\n * ```typescript\n * // In-memory only (no persistence)\n * const sessionManager = new SessionManager();\n *\n * // With persistence\n * const sessionManager = new SessionManager({\n * persistencePath: '.automatosx/sessions/sessions.json'\n * });\n * await sessionManager.initialize();\n *\n * // With custom limit\n * const sessionManager = new SessionManager({\n * persistencePath: '.automatosx/sessions/sessions.json',\n * maxSessions: 1000 // For large-scale systems\n * });\n * ```\n */\n constructor(config?: { persistencePath?: string; maxSessions?: number }) {\n this.persistencePath = config?.persistencePath;\n this.MAX_SESSIONS = config?.maxSessions ?? 100;\n }\n\n /**\n * Initialize session manager (load from persistence if configured)\n *\n * @example\n * ```typescript\n * const sessionManager = new SessionManager({\n * persistencePath: '.automatosx/sessions/sessions.json'\n * });\n * await sessionManager.initialize();\n * ```\n */\n async initialize(): Promise<void> {\n if (this.persistencePath) {\n await this.loadFromFile();\n }\n }\n\n /**\n * Create a new session\n *\n * @param task - Overall task/goal for the session\n * @param initiator - Agent that initiated the session\n * @returns Created session\n *\n * @example\n * ```typescript\n * const session = await sessionManager.createSession(\n * 'Implement authentication feature',\n * 'backend'\n * );\n * console.log('Session created:', session.id);\n * ```\n */\n async createSession(task: string, initiator: string): Promise<Session> {\n // Auto cleanup if approaching limit (prevent memory exhaustion)\n if (this.activeSessions.size >= this.MAX_SESSIONS) {\n logger.info('Session limit approaching, running auto cleanup', {\n current: this.activeSessions.size,\n limit: this.MAX_SESSIONS\n });\n await this.cleanup(); // Remove oldest completed sessions\n }\n\n // Generate unique session ID (handle extremely rare UUID collisions)\n let sessionId = randomUUID();\n let attempts = 0;\n const MAX_UUID_ATTEMPTS = 100;\n while (this.activeSessions.has(sessionId)) {\n if (++attempts >= MAX_UUID_ATTEMPTS) {\n throw new SessionError(\n `Failed to generate unique session ID after ${MAX_UUID_ATTEMPTS} attempts`,\n undefined,\n 'creation_failed'\n );\n }\n sessionId = randomUUID();\n }\n\n const session: Session = {\n id: sessionId,\n initiator,\n task,\n agents: [initiator], // Initiator is first agent\n status: 'active',\n createdAt: new Date(),\n updatedAt: new Date(),\n metadata: {}\n };\n\n this.activeSessions.set(session.id, session);\n\n logger.info('Session created', {\n sessionId: session.id,\n initiator,\n task: task.substring(0, 100) + (task.length > 100 ? '...' : '')\n });\n\n // Cleanup old completed/failed sessions (prevents memory leak)\n // This runs after session creation to avoid blocking the creation process\n await this.cleanupOldSessions(7); // Clean sessions older than 7 days\n\n // Persist to file\n this.saveToFile();\n\n return session;\n }\n\n /**\n * Add an agent to an existing session\n *\n * @param sessionId - Session ID\n * @param agentName - Agent to add\n * @throws {SessionError} If session not found\n *\n * @example\n * ```typescript\n * await sessionManager.addAgent(session.id, 'frontend');\n * await sessionManager.addAgent(session.id, 'security');\n * ```\n */\n async addAgent(sessionId: string, agentName: string): Promise<void> {\n // Validate session ID format\n this.validateSessionId(sessionId);\n\n const session = this.activeSessions.get(sessionId);\n\n if (!session) {\n throw new SessionError(\n `Session not found: ${sessionId}`,\n sessionId,\n 'not_found'\n );\n }\n\n // Only add if not already in the session\n if (!session.agents.includes(agentName)) {\n session.agents.push(agentName);\n session.updatedAt = new Date();\n\n logger.debug('Agent added to session', {\n sessionId,\n agentName,\n totalAgents: session.agents.length\n });\n\n // Persist to file\n this.saveToFile();\n }\n }\n\n /**\n * Get a session by ID\n *\n * @param sessionId - Session ID\n * @returns Session if found, null otherwise\n *\n * @example\n * ```typescript\n * const session = await sessionManager.getSession('session-123');\n * if (session) {\n * console.log('Session status:', session.status);\n * }\n * ```\n */\n async getSession(sessionId: string): Promise<Session | null> {\n // Validate session ID format (return null for invalid IDs)\n try {\n this.validateSessionId(sessionId);\n } catch {\n return null; // Invalid format = session doesn't exist\n }\n\n return this.activeSessions.get(sessionId) ?? null;\n }\n\n /**\n * Get all active sessions\n *\n * @returns Array of active sessions\n *\n * @example\n * ```typescript\n * const active = await sessionManager.getActiveSessions();\n * console.log(`${active.length} active sessions`);\n * ```\n */\n async getActiveSessions(): Promise<Session[]> {\n return Array.from(this.activeSessions.values())\n .filter(s => s.status === 'active');\n }\n\n /**\n * Get total number of sessions (all statuses)\n *\n * @returns Total session count\n *\n * @example\n * ```typescript\n * const total = await sessionManager.getTotalSessionCount();\n * console.log(`${total} total sessions`);\n * ```\n */\n async getTotalSessionCount(): Promise<number> {\n return this.activeSessions.size;\n }\n\n /**\n * Get active sessions for a specific agent\n *\n * @param agentName - Agent name\n * @returns Array of sessions where agent is involved\n *\n * @example\n * ```typescript\n * const sessions = await sessionManager.getActiveSessionsForAgent('backend');\n * console.log(`Backend is involved in ${sessions.length} sessions`);\n * ```\n */\n async getActiveSessionsForAgent(agentName: string): Promise<Session[]> {\n return Array.from(this.activeSessions.values())\n .filter(s =>\n s.status === 'active' &&\n s.agents.includes(agentName)\n )\n .sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime());\n }\n\n /**\n * Complete a session successfully\n *\n * @param sessionId - Session ID\n * @throws {SessionError} If session not found\n *\n * @example\n * ```typescript\n * await sessionManager.completeSession(session.id);\n * ```\n */\n async completeSession(sessionId: string): Promise<void> {\n // Validate session ID format\n this.validateSessionId(sessionId);\n\n const session = this.activeSessions.get(sessionId);\n\n if (!session) {\n throw new SessionError(\n `Session not found: ${sessionId}`,\n sessionId,\n 'not_found'\n );\n }\n\n if (session.status === 'completed') {\n logger.warn('Session already completed', { sessionId });\n return;\n }\n\n session.status = 'completed';\n session.updatedAt = new Date();\n\n const duration = session.updatedAt.getTime() - session.createdAt.getTime();\n\n logger.info('Session completed', {\n sessionId,\n duration: `${(duration / 1000).toFixed(1)}s`,\n agents: session.agents.length,\n agentList: session.agents.join(', ')\n });\n\n // Persist to file\n this.saveToFile();\n }\n\n /**\n * Mark a session as failed\n *\n * @param sessionId - Session ID\n * @param error - Error that caused the failure\n * @throws {SessionError} If session not found\n *\n * @example\n * ```typescript\n * try {\n * await delegateToAgent(...);\n * } catch (error) {\n * await sessionManager.failSession(session.id, error);\n * }\n * ```\n */\n async failSession(sessionId: string, error: Error): Promise<void> {\n // Validate session ID format (gracefully handle invalid IDs)\n try {\n this.validateSessionId(sessionId);\n } catch {\n logger.warn('Cannot fail session - invalid ID format', { sessionId });\n return;\n }\n\n const session = this.activeSessions.get(sessionId);\n\n if (!session) {\n // Session might have been cleaned up, just log and return\n logger.warn('Cannot fail session - not found', { sessionId });\n return;\n }\n\n session.status = 'failed';\n session.updatedAt = new Date();\n session.metadata = {\n ...session.metadata,\n error: error.message,\n errorStack: error.stack\n };\n\n logger.warn('Session failed', {\n sessionId,\n error: error.message,\n agents: session.agents.join(', ')\n });\n\n // Persist to file\n this.saveToFile();\n }\n\n /**\n * Update session metadata\n *\n * @param sessionId - Session ID\n * @param metadata - Metadata to merge\n * @throws {SessionError} If session not found\n *\n * @example\n * ```typescript\n * await sessionManager.updateMetadata(session.id, {\n * priority: 'high',\n * tags: ['auth', 'security']\n * });\n * ```\n */\n async updateMetadata(\n sessionId: string,\n metadata: Record<string, any>\n ): Promise<void> {\n // Validate session ID format\n this.validateSessionId(sessionId);\n\n const session = this.activeSessions.get(sessionId);\n\n if (!session) {\n throw new SessionError(\n `Session not found: ${sessionId}`,\n sessionId,\n 'not_found'\n );\n }\n\n // Merge metadata\n const newMetadata = {\n ...session.metadata,\n ...metadata\n };\n\n // Check metadata size (prevent DoS attacks)\n // Use Buffer.byteLength for accurate byte count (handles multi-byte characters)\n let metadataSize: number;\n try {\n metadataSize = Buffer.byteLength(JSON.stringify(newMetadata), 'utf-8');\n } catch (error) {\n throw new SessionError(\n `Metadata contains circular reference or non-serializable value: ${(error as Error).message}`,\n sessionId,\n 'metadata_too_large'\n );\n }\n\n if (metadataSize > this.MAX_METADATA_SIZE) {\n throw new SessionError(\n `Metadata too large: ${metadataSize} bytes (max: ${this.MAX_METADATA_SIZE} bytes)`,\n sessionId,\n 'metadata_too_large'\n );\n }\n\n session.metadata = newMetadata;\n session.updatedAt = new Date();\n\n logger.debug('Session metadata updated', {\n sessionId,\n metadata: Object.keys(metadata)\n });\n\n // Persist to file\n this.saveToFile();\n }\n\n /**\n * Cleanup old sessions (keep last MAX_SESSIONS)\n *\n * Removes oldest sessions (by update time) when limit is exceeded.\n *\n * @returns Number of sessions removed\n *\n * @example\n * ```typescript\n * const removed = await sessionManager.cleanup();\n * console.log(`Cleaned up ${removed} old sessions`);\n * ```\n */\n async cleanup(): Promise<number> {\n if (this.activeSessions.size <= this.MAX_SESSIONS) {\n return 0;\n }\n\n // Prioritize removing completed/failed sessions over active ones\n // Sort by: 1) status (completed/failed first), 2) update time (oldest first)\n const sessions = Array.from(this.activeSessions.values())\n .sort((a, b) => {\n // Priority: completed/failed before active\n const statusPriority = (s: Session) => s.status === 'active' ? 1 : 0;\n const priorityDiff = statusPriority(a) - statusPriority(b);\n if (priorityDiff !== 0) return priorityDiff;\n\n // If same status, sort by update time (oldest first)\n return a.updatedAt.getTime() - b.updatedAt.getTime();\n });\n\n // Calculate how many to remove\n const toRemoveCount = sessions.length - this.MAX_SESSIONS;\n const toRemove = sessions.slice(0, toRemoveCount);\n\n // Remove selected sessions\n toRemove.forEach(session => {\n this.activeSessions.delete(session.id);\n });\n\n if (toRemoveCount > 0) {\n const statusCount = toRemove.reduce((acc, s) => {\n acc[s.status] = (acc[s.status] || 0) + 1;\n return acc;\n }, {} as Record<string, number>);\n\n logger.info('Sessions cleaned up', {\n removed: toRemoveCount,\n remaining: this.activeSessions.size,\n removedByStatus: statusCount\n });\n\n // Persist to file\n this.saveToFile();\n }\n\n return toRemoveCount;\n }\n\n /**\n * Cleanup old completed/failed sessions\n *\n * Removes sessions that are completed or failed and older than the specified age.\n * This prevents memory leaks from inactive sessions.\n *\n * @param maxAgeDays - Maximum age in days (default: 7 days)\n * @returns Object with removed count and removed session IDs\n *\n * @example\n * ```typescript\n * // Clean up sessions older than 7 days\n * const result = await sessionManager.cleanupOldSessions();\n * console.log(`Removed ${result.removedCount} sessions`);\n *\n * // Use removedSessionIds to cleanup corresponding workspaces\n * await workspaceManager.cleanupSessionWorkspaces(result.removedSessionIds);\n * ```\n */\n async cleanupOldSessions(maxAgeDays: number = 7): Promise<{\n removedCount: number;\n removedSessionIds: string[];\n }> {\n const cutoffTime = Date.now() - (maxAgeDays * 24 * 60 * 60 * 1000);\n const sessions = Array.from(this.activeSessions.values());\n\n // Only remove completed/failed sessions (keep active ones)\n const toRemove = sessions.filter(s =>\n (s.status === 'completed' || s.status === 'failed') &&\n s.updatedAt.getTime() < cutoffTime\n );\n\n const removedSessionIds = toRemove.map(s => s.id);\n toRemove.forEach(s => this.activeSessions.delete(s.id));\n\n if (toRemove.length > 0) {\n logger.info('Old sessions cleaned up', {\n removed: toRemove.length,\n cutoffDays: maxAgeDays,\n remaining: this.activeSessions.size,\n removedSessionIds: removedSessionIds.slice(0, 5) // Log first 5 IDs\n });\n\n // Persist to file\n this.saveToFile();\n }\n\n return {\n removedCount: toRemove.length,\n removedSessionIds\n };\n }\n\n /**\n * Clear all sessions (mainly for testing)\n *\n * @returns Number of sessions removed\n *\n * @example\n * ```typescript\n * await sessionManager.clearAll();\n * ```\n */\n async clearAll(): Promise<number> {\n const count = this.activeSessions.size;\n this.activeSessions.clear();\n\n if (count > 0) {\n logger.info('All sessions cleared', { count });\n\n // Persist to file\n this.saveToFile();\n }\n\n return count;\n }\n\n /**\n * Destroy session manager (cleanup resources)\n *\n * Clears pending save timeout and flushes any pending save operations.\n * Should be called before discarding the SessionManager instance.\n *\n * @example\n * ```typescript\n * const sessionManager = new SessionManager({...});\n * // ... use sessionManager ...\n * await sessionManager.destroy();\n * ```\n */\n async destroy(): Promise<void> {\n // Clear timeout\n if (this.saveTimeout) {\n clearTimeout(this.saveTimeout);\n this.saveTimeout = undefined;\n }\n\n // Flush pending save (best effort - don't let errors prevent destroy)\n try {\n await this.flushSave();\n } catch (error) {\n logger.error('Error flushing save during destroy', {\n error: (error as Error).message\n });\n // Continue with destroy even if flush fails\n }\n\n logger.debug('SessionManager destroyed', {\n sessions: this.activeSessions.size\n });\n }\n\n /**\n * Flush pending save operation (wait for completion)\n *\n * Forces immediate save if there's a pending debounced save.\n *\n * @private\n */\n private async flushSave(): Promise<void> {\n // If there's a debounced save pending, cancel it and do immediate save\n if (this.saveTimeout) {\n clearTimeout(this.saveTimeout);\n this.saveTimeout = undefined;\n\n // If there's also a pendingSave, wait for it first to avoid concurrent saves\n if (this.pendingSave) {\n try {\n await this.pendingSave;\n } catch (err) {\n // Ignore errors from previous save, we'll try again below\n }\n }\n\n // Do immediate save\n await this.doSave();\n return;\n }\n\n // No timeout, but there might be a pending save - wait for it\n if (this.pendingSave) {\n try {\n await this.pendingSave;\n } catch (err) {\n // Re-throw so destroy() knows there was a problem\n throw err;\n }\n }\n }\n\n /**\n * Perform actual save operation (internal)\n *\n * @private\n */\n private async doSave(): Promise<void> {\n if (!this.persistencePath) {\n return;\n }\n\n try {\n // Ensure directory exists\n await mkdir(dirname(this.persistencePath), { recursive: true });\n\n // Convert sessions to plain objects (Date -> string)\n const sessionsArray = Array.from(this.activeSessions.values()).map(session => ({\n id: session.id,\n initiator: session.initiator,\n task: session.task,\n agents: session.agents,\n status: session.status,\n createdAt: session.createdAt.toISOString(),\n updatedAt: session.updatedAt.toISOString(),\n metadata: session.metadata\n }));\n\n const data = JSON.stringify(sessionsArray, null, 2);\n\n // Atomic write: write to temp file then rename (prevents corruption)\n const tempPath = `${this.persistencePath}.tmp`;\n\n try {\n await writeFile(tempPath, data, 'utf-8');\n await rename(tempPath, this.persistencePath);\n\n logger.debug('Sessions saved to persistence', {\n path: this.persistencePath,\n count: sessionsArray.length\n });\n } catch (renameError) {\n // Clean up temp file if rename failed (prevents accumulation)\n try {\n await unlink(tempPath);\n } catch (unlinkError) {\n // Ignore unlink errors (file might not exist)\n }\n throw renameError;\n }\n } catch (error) {\n logger.error('Failed to save sessions to persistence', {\n path: this.persistencePath,\n error: (error as Error).message\n });\n throw error; // Re-throw for caller to handle\n }\n }\n\n /**\n * Get statistics about current sessions\n *\n * @returns Session statistics\n *\n * @example\n * ```typescript\n * const stats = await sessionManager.getStats();\n * console.log(`Active: ${stats.active}, Total: ${stats.total}`);\n * ```\n */\n async getStats(): Promise<{\n total: number;\n active: number;\n completed: number;\n failed: number;\n }> {\n const sessions = Array.from(this.activeSessions.values());\n\n return {\n total: sessions.length,\n active: sessions.filter(s => s.status === 'active').length,\n completed: sessions.filter(s => s.status === 'completed').length,\n failed: sessions.filter(s => s.status === 'failed').length\n };\n }\n\n /**\n * Load sessions from persistence file\n *\n * @private\n */\n private async loadFromFile(): Promise<void> {\n if (!this.persistencePath) {\n return;\n }\n\n try {\n const data = await readFile(this.persistencePath, 'utf-8');\n const sessionsArray = JSON.parse(data) as Array<{\n id: string;\n initiator: string;\n task: string;\n agents: string[];\n status: 'active' | 'completed' | 'failed';\n createdAt: string;\n updatedAt: string;\n metadata: Record<string, any>;\n }>;\n\n // Convert date strings back to Date objects\n this.activeSessions.clear();\n let skippedCount = 0;\n\n for (const sessionData of sessionsArray) {\n // Validate session ID before loading (security check)\n try {\n this.validateSessionId(sessionData.id);\n } catch (error) {\n skippedCount++;\n logger.warn('Skipping invalid session ID from persistence', {\n sessionId: sessionData.id,\n error: (error as Error).message\n });\n continue;\n }\n\n // Validate dates (protect against Invalid Date objects)\n const createdAt = new Date(sessionData.createdAt);\n const updatedAt = new Date(sessionData.updatedAt);\n\n if (isNaN(createdAt.getTime()) || isNaN(updatedAt.getTime())) {\n skippedCount++;\n logger.warn('Skipping session with invalid dates from persistence', {\n sessionId: sessionData.id,\n createdAt: sessionData.createdAt,\n updatedAt: sessionData.updatedAt\n });\n continue;\n }\n\n const session: Session = {\n ...sessionData,\n createdAt,\n updatedAt\n };\n this.activeSessions.set(session.id, session);\n }\n\n logger.info('Sessions loaded from persistence', {\n path: this.persistencePath,\n loaded: this.activeSessions.size,\n skipped: skippedCount,\n total: sessionsArray.length\n });\n } catch (error) {\n const err = error as NodeJS.ErrnoException;\n\n // File not found is OK (first time initialization)\n if (err.code === 'ENOENT') {\n logger.debug('No existing sessions file, starting fresh', {\n path: this.persistencePath\n });\n return;\n }\n\n // For other errors (corrupted JSON, permission issues, etc.),\n // backup the corrupted file and start fresh\n try {\n const backupPath = `${this.persistencePath}.corrupted.${Date.now()}`;\n await copyFile(this.persistencePath, backupPath);\n\n logger.error('Corrupted sessions file backed up, starting fresh', {\n path: this.persistencePath,\n backupPath,\n error: err.message\n });\n } catch (backupError) {\n // If backup fails, just log and continue\n logger.error('Failed to backup corrupted sessions file', {\n path: this.persistencePath,\n error: err.message,\n backupError: (backupError as Error).message\n });\n }\n }\n }\n\n /**\n * Save sessions to persistence file (debounced)\n *\n * @private\n */\n private saveToFile(): void {\n if (!this.persistencePath) {\n return;\n }\n\n // Debounce saves to avoid excessive file writes\n if (this.saveTimeout) {\n clearTimeout(this.saveTimeout);\n }\n\n this.saveTimeout = setTimeout(() => {\n this.pendingSave = this.doSave().catch(err => {\n logger.error('Debounced save failed', {\n error: err.message\n });\n // Re-throw to keep promise rejected (so flushSave can detect failures)\n throw err;\n });\n }, 100); // 100ms debounce\n }\n}\n","/**\n * Orchestration Types - Agent-to-agent collaboration and delegation\n *\n * @module types/orchestration\n * @since v4.7.0\n */\n\nimport type { ExecutionResponse } from './provider.js';\n\n/**\n * Delegation Request - Structured request for agent delegation\n *\n * @example\n * ```typescript\n * const request: DelegationRequest = {\n * fromAgent: 'backend',\n * toAgent: 'frontend',\n * task: 'Create login UI component',\n * context: {\n * sessionId: 'auth-feature-123',\n * requirements: ['Email/password fields', 'Form validation'],\n * expectedOutputs: ['LoginForm.tsx', 'tests']\n * }\n * };\n * ```\n */\nexport interface DelegationRequest {\n /** Agent initiating the delegation */\n fromAgent: string;\n\n /** Agent receiving the delegated task */\n toAgent: string;\n\n /** Task description for the delegated agent */\n task: string;\n\n /** Additional context for the delegation */\n context?: {\n /** Shared data to pass to delegated agent */\n sharedData?: Record<string, any>;\n\n /** Structured requirements for the task */\n requirements?: string[];\n\n /** Expected outputs from the delegated agent */\n expectedOutputs?: string[];\n\n /** Session ID to track related work (CRITICAL for multi-agent workflows) */\n sessionId?: string;\n\n /** Delegation chain for cycle detection */\n delegationChain?: string[];\n };\n\n /** Execution options */\n options?: {\n /** Maximum execution time in milliseconds */\n timeout?: number;\n\n /** Task priority (affects execution order if queued) */\n priority?: 'low' | 'medium' | 'high';\n };\n}\n\n/**\n * Delegation Result - Structured result from agent delegation\n *\n * Contains both the execution response and structured outputs for easy integration.\n *\n * @example\n * ```typescript\n * const result = await executor.delegateToAgent(request);\n *\n * // Access structured outputs\n * console.log('Files created:', result.outputs.files);\n * console.log('Memory IDs:', result.outputs.memoryIds);\n * console.log('Workspace path:', result.outputs.workspacePath);\n * ```\n */\nexport interface DelegationResult {\n /** Unique delegation identifier (for tracking and auditing) */\n delegationId: string;\n\n /** Agent that initiated the delegation */\n fromAgent: string;\n\n /** Agent that executed the task */\n toAgent: string;\n\n /** Delegation status */\n status: 'success' | 'failure' | 'timeout';\n\n /** Response from the delegated agent execution */\n response: ExecutionResponse;\n\n /** Execution duration in milliseconds */\n duration: number;\n\n /** Structured outputs from the delegation */\n outputs: {\n /** Files created in shared workspace */\n files?: string[];\n\n /** Memory entry IDs created during execution */\n memoryIds?: number[];\n\n /** Path to workspace containing outputs */\n workspacePath?: string;\n };\n\n /** Delegation start timestamp */\n startTime: Date;\n\n /** Delegation completion timestamp */\n endTime: Date;\n}\n\n/**\n * Session - Tracks multi-agent collaborative workflows\n *\n * A session groups related work across multiple agents, providing shared context\n * and workspace organization.\n *\n * @example\n * ```typescript\n * // Create session for auth feature implementation\n * const session = await sessionManager.createSession(\n * 'Implement authentication feature',\n * 'backend'\n * );\n *\n * // Agents added as they join the work\n * await sessionManager.addAgent(session.id, 'frontend');\n * await sessionManager.addAgent(session.id, 'security');\n * ```\n */\nexport interface Session {\n /** Unique session identifier (UUID) */\n id: string;\n\n /** Agent that initiated the session */\n initiator: string;\n\n /** Overall task/goal for the session */\n task: string;\n\n /** Agents involved in this session (ordered by join time) */\n agents: string[];\n\n /** Current session status */\n status: 'active' | 'completed' | 'failed';\n\n /** Session creation timestamp */\n createdAt: Date;\n\n /** Last update timestamp */\n updatedAt: Date;\n\n /** Additional session metadata */\n metadata?: Record<string, any>;\n}\n\n/**\n * Orchestration Configuration - Agent collaboration capabilities\n *\n * Defines workspace access and delegation depth limits for agents.\n * All agents can delegate by default (v4.9.0+). Safety is ensured through\n * cycle detection, depth limits, and timeouts.\n *\n * @example\n * ```yaml\n * # .automatosx/agents/backend.yaml\n * orchestration:\n * maxDelegationDepth: 3\n * canReadWorkspaces:\n * - frontend\n * - data\n * canWriteToShared: true\n * ```\n */\nexport interface OrchestrationConfig {\n /**\n * Maximum delegation chain depth (default: 3)\n *\n * This represents the number of intermediate delegations allowed, NOT the total number of agents.\n *\n * Example:\n * - maxDelegationDepth = 3 allows: A → B → C → D (3 delegations, 4 agents)\n * - maxDelegationDepth = 3 rejects: A → B → C → D → E (4 delegations, 5 agents)\n *\n * The depth is measured by the length of the delegation chain (excluding the current agent).\n */\n maxDelegationDepth?: number;\n\n /** Whitelist of agents' workspaces this agent can read */\n canReadWorkspaces?: string[];\n\n /** Whether this agent can write to shared workspace */\n canWriteToShared?: boolean;\n}\n\n/**\n * Orchestration Metadata - Runtime orchestration information in execution context\n *\n * Added to ExecutionContext when orchestration system is enabled.\n * v4.9.0+: All agents can delegate by default. This metadata indicates whether\n * the orchestration infrastructure (SessionManager, WorkspaceManager) is available.\n */\nexport interface OrchestrationMetadata {\n /** Whether orchestration system is enabled (SessionManager/WorkspaceManager available) */\n isDelegationEnabled: boolean;\n\n /** List of available agents for delegation */\n availableAgents: string[];\n\n /** Path to shared workspace */\n sharedWorkspace: string;\n\n /** Current delegation chain (for cycle detection) */\n delegationChain: string[];\n\n /** Maximum delegation depth (default: 3) */\n maxDelegationDepth: number;\n}\n\n/**\n * Delegation Error - Specialized error for delegation failures\n */\nexport class DelegationError extends Error {\n constructor(\n message: string,\n public readonly fromAgent: string,\n public readonly toAgent: string,\n public readonly reason: 'unauthorized' | 'not_found' | 'max_depth' | 'cycle' | 'timeout' | 'execution_failed'\n ) {\n super(message);\n this.name = 'DelegationError';\n }\n}\n\n/**\n * Session Error - Specialized error for session operations\n */\nexport class SessionError extends Error {\n constructor(\n message: string,\n public readonly sessionId?: string,\n public readonly reason?: 'not_found' | 'already_completed' | 'creation_failed' | 'invalid_format' | 'metadata_too_large'\n ) {\n super(message);\n this.name = 'SessionError';\n }\n}\n\n/**\n * Workspace Error - Specialized error for workspace operations\n */\nexport class WorkspaceError extends Error {\n constructor(\n message: string,\n public readonly workspacePath?: string,\n public readonly reason?: 'permission_denied' | 'not_found' | 'conflict' | 'quota_exceeded' | 'creation_failed' | 'invalid_session_id'\n ) {\n super(message);\n this.name = 'WorkspaceError';\n }\n}\n","/**\n * Workspace Manager - Manages agent workspaces and session-based collaboration\n *\n * Provides:\n * - Session-based workspace organization\n * - Agent workspace isolation with controlled sharing\n * - Permission-based access control\n * - Automatic cleanup of old session workspaces\n *\n * @module core/workspace-manager\n * @since v4.7.0\n */\n\nimport { promises as fs } from 'fs';\nimport path from 'path';\nimport type { AgentProfile } from '../types/agent.js';\nimport type { WorkspaceSystemConfig } from '../types/config.js';\nimport { WorkspaceError } from '../types/orchestration.js';\nimport { logger } from '../utils/logger.js';\n\n/**\n * Workspace structure:\n * ```\n * .automatosx/workspaces/\n * ├── shared/\n * │ ├── sessions/<sessionId>/ # Session-specific shared workspace\n * │ │ ├── specs/ # Requirements, designs\n * │ │ └── outputs/\n * │ │ ├── <agentName>/ # Each agent's outputs\n * │ │ └── ...\n * │ └── persistent/ # Cross-session shared files\n * └── <agentName>/ # Agent private workspace\n * ├── drafts/\n * └── temp/\n * ```\n */\n\nexport interface WorkspaceStats {\n /** Total number of session workspaces */\n totalSessions: number;\n\n /** Total disk space used (bytes) */\n totalSizeBytes: number;\n\n /** Number of agent workspaces */\n agentWorkspaces: number;\n}\n\n/**\n * Workspace Manager\n *\n * Manages workspace organization for multi-agent collaboration with:\n * - Session-based isolation (each session gets its own workspace)\n * - Permission-based access control (based on OrchestrationConfig)\n * - Automatic cleanup of old sessions\n *\n * @example\n * ```typescript\n * const workspaceManager = new WorkspaceManager('/path/to/project');\n *\n * // Create session workspace\n * await workspaceManager.createSessionWorkspace('session-123');\n *\n * // Agent writes to session\n * await workspaceManager.writeToSession(\n * 'session-123',\n * 'backend',\n * 'api-spec.md',\n * '# API Specification...'\n * );\n *\n * // Another agent reads from backend's output\n * const spec = await workspaceManager.readFromAgentWorkspace(\n * 'frontend',\n * 'backend',\n * 'session-123',\n * 'api-spec.md'\n * );\n * ```\n */\nexport class WorkspaceManager {\n private readonly workspacesRoot: string;\n private readonly sharedRoot: string;\n private readonly sessionsRoot: string;\n private readonly persistentRoot: string;\n\n /** Maximum file size for writeToSession (from config) */\n private readonly maxFileSize: number;\n\n /** UUID v4 validation regex (static for performance) */\n private static readonly UUID_V4_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n\n /**\n * Create WorkspaceManager\n *\n * @param projectDir - Project directory path\n * @param config - Workspace configuration (optional, defaults to 10MB max file size)\n */\n constructor(projectDir: string, config?: WorkspaceSystemConfig) {\n this.workspacesRoot = path.join(projectDir, '.automatosx', 'workspaces');\n this.sharedRoot = path.join(this.workspacesRoot, 'shared');\n this.sessionsRoot = path.join(this.sharedRoot, 'sessions');\n this.persistentRoot = path.join(this.sharedRoot, 'persistent');\n\n // v5.0: Use config value instead of hardcoded constant\n this.maxFileSize = config?.maxFileSize ?? 10 * 1024 * 1024; // Default: 10 MB\n }\n\n /**\n * Initialize workspace structure\n *\n * Creates all necessary directories for workspace management.\n *\n * @example\n * ```typescript\n * await workspaceManager.initialize();\n * ```\n */\n async initialize(): Promise<void> {\n await fs.mkdir(this.workspacesRoot, { recursive: true });\n await fs.mkdir(this.sharedRoot, { recursive: true });\n await fs.mkdir(this.sessionsRoot, { recursive: true });\n await fs.mkdir(this.persistentRoot, { recursive: true });\n\n logger.debug('Workspace structure initialized', {\n workspacesRoot: this.workspacesRoot\n });\n }\n\n /**\n * Create workspace for a session\n *\n * @param sessionId - Session ID\n * @throws {WorkspaceError} If creation fails\n *\n * @example\n * ```typescript\n * await workspaceManager.createSessionWorkspace('session-123');\n * ```\n */\n async createSessionWorkspace(sessionId: string): Promise<void> {\n const sessionDir = this.getSessionDir(sessionId);\n const specsDir = path.join(sessionDir, 'specs');\n const outputsDir = path.join(sessionDir, 'outputs');\n\n try {\n await fs.mkdir(sessionDir, { recursive: true });\n await fs.mkdir(specsDir, { recursive: true });\n await fs.mkdir(outputsDir, { recursive: true });\n\n logger.info('Session workspace created', {\n sessionId,\n path: sessionDir\n });\n } catch (error) {\n throw new WorkspaceError(\n `Failed to create session workspace: ${(error as Error).message}`,\n sessionDir,\n 'creation_failed'\n );\n }\n }\n\n /**\n * Get agent's output directory within a session\n *\n * @param sessionId - Session ID\n * @param agentName - Agent name\n * @returns Path to agent's output directory\n */\n private getAgentOutputDir(sessionId: string, agentName: string): string {\n return path.join(this.getSessionDir(sessionId), 'outputs', agentName);\n }\n\n /**\n * Validate session ID format (must be valid UUID v4)\n *\n * @param sessionId - Session ID to validate\n * @throws {WorkspaceError} If session ID is invalid\n */\n private validateSessionId(sessionId: string): void {\n // UUID v4 format: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\n // where y is 8, 9, a, or b\n if (!WorkspaceManager.UUID_V4_REGEX.test(sessionId)) {\n throw new WorkspaceError(\n `Invalid session ID format: ${sessionId}. Session IDs must be valid UUID v4.`,\n undefined,\n 'invalid_session_id'\n );\n }\n }\n\n /**\n * Get session directory path\n *\n * @param sessionId - Session ID\n * @returns Session directory path\n */\n private getSessionDir(sessionId: string): string {\n this.validateSessionId(sessionId);\n return path.join(this.sessionsRoot, sessionId);\n }\n\n /**\n * Validate that a file path is safe (prevents path traversal attacks)\n *\n * @param baseDir - Base directory that file must be within\n * @param filePath - Relative file path to validate\n * @returns Resolved absolute path\n * @throws {WorkspaceError} If path is unsafe\n *\n * Security checks:\n * 1. Normalize path to resolve '..' and '.'\n * 2. Resolve to absolute path\n * 3. Verify resolved path is within base directory\n * 4. Prevent symlink attacks by checking real path\n */\n private async validatePath(baseDir: string, filePath: string): Promise<string> {\n // 1. Reject absolute paths immediately\n if (path.isAbsolute(filePath)) {\n throw new WorkspaceError(\n `Absolute paths not allowed: ${filePath}`,\n filePath,\n 'permission_denied'\n );\n }\n\n // 2. Normalize the path (resolves '..' and '.')\n const normalized = path.normalize(filePath);\n\n // 3. Additional check: normalized path shouldn't start with '..'\n if (normalized.startsWith('..')) {\n throw new WorkspaceError(\n `Path traversal detected: ${filePath}`,\n filePath,\n 'permission_denied'\n );\n }\n\n // 4. Resolve to absolute path\n const resolved = path.resolve(baseDir, normalized);\n\n // 5. Verify resolved path is within base directory\n const resolvedBase = path.resolve(baseDir);\n if (!resolved.startsWith(resolvedBase + path.sep) && resolved !== resolvedBase) {\n throw new WorkspaceError(\n `Path outside workspace: ${filePath}`,\n filePath,\n 'permission_denied'\n );\n }\n\n return resolved;\n }\n\n /**\n * Get agent's private workspace directory\n *\n * @param agentName - Agent name\n * @returns Agent workspace path\n */\n private getAgentWorkspaceDir(agentName: string): string {\n return path.join(this.workspacesRoot, agentName);\n }\n\n /**\n * Write file to session workspace (agent's output area)\n *\n * @param sessionId - Session ID\n * @param agentName - Agent writing the file\n * @param filePath - Relative file path within agent's output\n * @param content - File content\n * @param callerAgent - Optional: Agent profile of the caller (for permission verification)\n * @throws {WorkspaceError} If write fails, path is invalid, or permission denied\n *\n * @example\n * ```typescript\n * await workspaceManager.writeToSession(\n * 'session-123',\n * 'backend',\n * 'api/users.ts',\n * 'export interface User { ... }',\n * backendProfile // Verify caller is actually 'backend'\n * );\n * ```\n */\n async writeToSession(\n sessionId: string,\n agentName: string,\n filePath: string,\n content: string,\n callerAgent?: AgentProfile\n ): Promise<void> {\n // Permission check: Verify caller is the agent they claim to be\n if (callerAgent && callerAgent.name !== agentName) {\n throw new WorkspaceError(\n `Agent '${callerAgent.name}' is not authorized to write to '${agentName}' workspace`,\n undefined,\n 'permission_denied'\n );\n }\n\n const agentOutputDir = this.getAgentOutputDir(sessionId, agentName);\n\n // Validate path security (prevents path traversal)\n const fullPath = await this.validatePath(agentOutputDir, filePath);\n\n // Check file size (prevent disk quota exhaustion)\n const fileSize = Buffer.byteLength(content, 'utf-8');\n if (fileSize > this.maxFileSize) {\n throw new WorkspaceError(\n `File too large: ${fileSize} bytes (max: ${this.maxFileSize} bytes)`,\n fullPath,\n 'quota_exceeded'\n );\n }\n\n try {\n // Ensure directory exists\n await fs.mkdir(path.dirname(fullPath), { recursive: true });\n\n // Write file\n await fs.writeFile(fullPath, content, 'utf-8');\n\n logger.debug('File written to session workspace', {\n sessionId,\n agentName,\n filePath,\n size: content.length\n });\n } catch (error) {\n throw new WorkspaceError(\n `Failed to write file: ${(error as Error).message}`,\n fullPath,\n 'permission_denied'\n );\n }\n }\n\n /**\n * Read file from another agent's workspace (within a session)\n *\n * Requires permission check: requestingAgent must have targetAgent\n * in their canReadWorkspaces whitelist.\n *\n * @param requestingAgent - Agent profile requesting access\n * @param targetAgent - Target agent whose workspace to read\n * @param sessionId - Session ID\n * @param filePath - Relative file path within target agent's output\n * @returns File content\n * @throws {WorkspaceError} If permission denied or file not found\n *\n * @example\n * ```typescript\n * const spec = await workspaceManager.readFromAgentWorkspace(\n * frontendProfile,\n * 'backend',\n * 'session-123',\n * 'api-spec.md'\n * );\n * ```\n */\n async readFromAgentWorkspace(\n requestingAgent: AgentProfile,\n targetAgent: string,\n sessionId: string,\n filePath: string\n ): Promise<string> {\n // Permission check\n const canRead = requestingAgent.orchestration?.canReadWorkspaces;\n if (!canRead || !canRead.includes(targetAgent)) {\n throw new WorkspaceError(\n `Agent '${requestingAgent.name}' is not authorized to read '${targetAgent}' workspace`,\n undefined,\n 'permission_denied'\n );\n }\n\n const agentOutputDir = this.getAgentOutputDir(sessionId, targetAgent);\n\n // Validate path security (prevents path traversal)\n const fullPath = await this.validatePath(agentOutputDir, filePath);\n\n try {\n const content = await fs.readFile(fullPath, 'utf-8');\n\n logger.debug('File read from agent workspace', {\n requestingAgent: requestingAgent.name,\n targetAgent,\n sessionId,\n filePath\n });\n\n return content;\n } catch (error) {\n const err = error as NodeJS.ErrnoException;\n if (err.code === 'ENOENT') {\n throw new WorkspaceError(\n `File not found: ${filePath}`,\n fullPath,\n 'not_found'\n );\n }\n throw new WorkspaceError(\n `Failed to read file: ${err.message}`,\n fullPath,\n 'permission_denied'\n );\n }\n }\n\n /**\n * Write to persistent shared workspace (cross-session)\n *\n * Requires permission check: agent must have canWriteToShared enabled.\n *\n * @param agent - Agent profile\n * @param filePath - Relative file path\n * @param content - File content\n * @throws {WorkspaceError} If permission denied or write fails\n *\n * @example\n * ```typescript\n * await workspaceManager.writeToShared(\n * agentProfile,\n * 'templates/api-template.ts',\n * 'export const template = ...'\n * );\n * ```\n */\n async writeToShared(\n agent: AgentProfile,\n filePath: string,\n content: string\n ): Promise<void> {\n // Permission check\n if (!agent.orchestration?.canWriteToShared) {\n throw new WorkspaceError(\n `Agent '${agent.name}' is not authorized to write to shared workspace`,\n undefined,\n 'permission_denied'\n );\n }\n\n // Validate path security (prevents path traversal)\n const fullPath = await this.validatePath(this.persistentRoot, filePath);\n\n // Check file size (prevent disk quota exhaustion)\n const fileSize = Buffer.byteLength(content, 'utf-8');\n if (fileSize > this.maxFileSize) {\n throw new WorkspaceError(\n `File too large: ${fileSize} bytes (max: ${this.maxFileSize} bytes)`,\n fullPath,\n 'quota_exceeded'\n );\n }\n\n try {\n await fs.mkdir(path.dirname(fullPath), { recursive: true });\n await fs.writeFile(fullPath, content, 'utf-8');\n\n logger.info('File written to persistent shared workspace', {\n agentName: agent.name,\n filePath,\n size: fileSize\n });\n } catch (error) {\n throw new WorkspaceError(\n `Failed to write to shared workspace: ${(error as Error).message}`,\n fullPath,\n 'permission_denied'\n );\n }\n }\n\n /**\n * List files in session workspace for a specific agent\n *\n * @param sessionId - Session ID\n * @param agentName - Agent name\n * @returns Array of relative file paths\n * @throws {WorkspaceError} If listing fails\n *\n * @example\n * ```typescript\n * const files = await workspaceManager.listSessionFiles('session-123', 'backend');\n * console.log(files); // ['api-spec.md', 'models/user.ts']\n * ```\n */\n async listSessionFiles(sessionId: string, agentName: string): Promise<string[]> {\n const agentOutputDir = this.getAgentOutputDir(sessionId, agentName);\n\n try {\n const files: string[] = [];\n await this.collectFiles(agentOutputDir, agentOutputDir, files);\n return files;\n } catch (error) {\n const err = error as NodeJS.ErrnoException;\n if (err.code === 'ENOENT') {\n return []; // Directory doesn't exist yet\n }\n throw new WorkspaceError(\n `Failed to list files: ${err.message}`,\n agentOutputDir,\n 'permission_denied'\n );\n }\n }\n\n /**\n * Recursively collect files from a directory\n *\n * @param dir - Directory to scan\n * @param baseDir - Base directory for relative paths\n * @param files - Array to collect file paths\n */\n private async collectFiles(\n dir: string,\n baseDir: string,\n files: string[]\n ): Promise<void> {\n try {\n const entries = await fs.readdir(dir, { withFileTypes: true });\n\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n\n try {\n if (entry.isDirectory()) {\n await this.collectFiles(fullPath, baseDir, files);\n } else {\n const relativePath = path.relative(baseDir, fullPath);\n files.push(relativePath);\n }\n } catch (err) {\n // Skip files/directories that were deleted during traversal\n const error = err as NodeJS.ErrnoException;\n if (error.code === 'ENOENT') {\n logger.debug('File removed during traversal', { path: fullPath });\n continue;\n }\n throw err;\n }\n }\n } catch (err) {\n // If directory is deleted during traversal, just log and return\n const error = err as NodeJS.ErrnoException;\n if (error.code === 'ENOENT') {\n logger.debug('Directory removed during traversal', { path: dir });\n return;\n }\n throw err;\n }\n }\n\n /**\n * Cleanup old session workspaces\n *\n * Removes session workspaces older than specified days.\n * Should be called in sync with SessionManager cleanup.\n *\n * @param sessionIds - Active session IDs to keep\n * @returns Number of sessions cleaned up\n *\n * @example\n * ```typescript\n * const activeSessions = await sessionManager.getActiveSessions();\n * const activeIds = activeSessions.map(s => s.id);\n * const removed = await workspaceManager.cleanupSessions(activeIds);\n * ```\n */\n async cleanupSessions(sessionIds: string[]): Promise<number> {\n try {\n const sessionDirs = await fs.readdir(this.sessionsRoot);\n const activeSet = new Set(sessionIds);\n let removed = 0;\n\n for (const sessionId of sessionDirs) {\n if (!activeSet.has(sessionId)) {\n try {\n const sessionDir = this.getSessionDir(sessionId);\n await fs.rm(sessionDir, { recursive: true, force: true });\n removed++;\n\n logger.debug('Session workspace removed', { sessionId });\n } catch (err) {\n // Skip invalid session directories (non-UUID names)\n if (err instanceof WorkspaceError && err.reason === 'invalid_session_id') {\n logger.warn('Skipping invalid session directory', { sessionId });\n continue;\n }\n throw err;\n }\n }\n }\n\n if (removed > 0) {\n logger.info('Session workspaces cleaned up', { removed });\n }\n\n return removed;\n } catch (error) {\n logger.warn('Failed to cleanup session workspaces', {\n error: (error as Error).message\n });\n return 0;\n }\n }\n\n /**\n * Cleanup specific session workspaces by session IDs\n *\n * Removes workspace directories for the specified session IDs.\n * Useful when coordinating with SessionManager cleanup.\n *\n * @param sessionIds - Session IDs to remove\n * @returns Number of workspaces removed\n *\n * @example\n * ```typescript\n * const result = await sessionManager.cleanupOldSessions(7);\n * await workspaceManager.cleanupSessionWorkspaces(result.removedSessionIds);\n * ```\n */\n async cleanupSessionWorkspaces(sessionIds: string[]): Promise<number> {\n let removed = 0;\n\n for (const sessionId of sessionIds) {\n try {\n const sessionDir = this.getSessionDir(sessionId);\n await fs.rm(sessionDir, { recursive: true, force: true });\n removed++;\n\n logger.debug('Session workspace removed', { sessionId });\n } catch (error) {\n const err = error as NodeJS.ErrnoException;\n // Ignore ENOENT errors (workspace already doesn't exist)\n if (err.code !== 'ENOENT') {\n logger.warn('Failed to remove session workspace', {\n sessionId,\n error: err.message\n });\n }\n }\n }\n\n if (removed > 0) {\n logger.info('Session workspaces cleaned up', {\n removed,\n total: sessionIds.length\n });\n }\n\n return removed;\n }\n\n /**\n * Get workspace statistics\n *\n * @returns Workspace statistics\n *\n * @example\n * ```typescript\n * const stats = await workspaceManager.getStats();\n * console.log(`${stats.totalSessions} session workspaces`);\n * ```\n */\n async getStats(): Promise<WorkspaceStats> {\n try {\n const sessionDirs = await fs.readdir(this.sessionsRoot);\n const agentDirs = await fs.readdir(this.workspacesRoot);\n\n // Count only directories (exclude 'shared')\n const agentWorkspaces = agentDirs.filter(\n name => name !== 'shared'\n ).length;\n\n // Calculate total size (simplified - doesn't traverse all files)\n const stats: WorkspaceStats = {\n totalSessions: sessionDirs.length,\n totalSizeBytes: 0,\n agentWorkspaces\n };\n\n return stats;\n } catch (error) {\n logger.warn('Failed to get workspace stats', {\n error: (error as Error).message\n });\n\n return {\n totalSessions: 0,\n totalSizeBytes: 0,\n agentWorkspaces: 0\n };\n }\n }\n\n /**\n * Create agent's private workspace\n *\n * @param agentName - Agent name\n *\n * @example\n * ```typescript\n * await workspaceManager.createAgentWorkspace('backend');\n * ```\n */\n async createAgentWorkspace(agentName: string): Promise<void> {\n const agentDir = this.getAgentWorkspaceDir(agentName);\n const draftsDir = path.join(agentDir, 'drafts');\n const tempDir = path.join(agentDir, 'temp');\n\n try {\n await fs.mkdir(agentDir, { recursive: true });\n await fs.mkdir(draftsDir, { recursive: true });\n await fs.mkdir(tempDir, { recursive: true });\n\n logger.debug('Agent workspace created', {\n agentName,\n path: agentDir\n });\n } catch (error) {\n throw new WorkspaceError(\n `Failed to create agent workspace: ${(error as Error).message}`,\n agentDir,\n 'creation_failed'\n );\n }\n }\n}\n","/**\n * Context Manager - Create and manage execution contexts for agents\n */\n\nimport { mkdir, chmod } from 'fs/promises';\nimport { join, resolve } from 'path';\nimport type {\n ExecutionContext,\n AgentProfile,\n ContextOptions\n} from '../types/agent.js';\nimport type { Provider } from '../types/provider.js';\nimport type { MemoryEntry } from '../types/memory.js';\nimport type { OrchestrationMetadata, Session } from '../types/orchestration.js';\nimport { ProfileLoader } from './profile-loader.js';\nimport { AbilitiesManager } from './abilities-manager.js';\nimport type { IMemoryManager } from '../types/memory.js';\nimport type { SessionManager } from '../core/session-manager.js';\nimport type { WorkspaceManager } from '../core/workspace-manager.js';\nimport { Router } from '../core/router.js';\nimport { PathResolver } from '../core/path-resolver.js';\nimport { logger } from '../utils/logger.js';\nimport { PathError, ProviderError } from '../utils/errors.js';\n\n/**\n * Provider name aliases (v5.0.7 fix)\n * Maps team config names to actual registered provider names\n */\nconst PROVIDER_ALIASES: Record<string, string> = {\n 'claude': 'claude-code',\n 'gemini': 'gemini-cli',\n 'codex': 'openai',\n 'openai': 'openai'\n};\n\nexport interface ContextManagerConfig {\n profileLoader: ProfileLoader;\n abilitiesManager: AbilitiesManager;\n memoryManager: IMemoryManager | null;\n router: Router;\n pathResolver: PathResolver;\n sessionManager?: SessionManager;\n workspaceManager?: WorkspaceManager;\n}\n\n/**\n * Context Manager - Create and manage execution contexts\n */\nexport class ContextManager {\n private config: ContextManagerConfig;\n\n constructor(config: ContextManagerConfig) {\n this.config = config;\n }\n\n /**\n * Create execution context for an agent task\n */\n async createContext(\n agentName: string,\n task: string,\n options?: ContextOptions\n ): Promise<ExecutionContext> {\n logger.info('Creating execution context', { agentName, task });\n\n // 1. Resolve agent name (supports displayName)\n const resolvedName = await this.config.profileLoader.resolveAgentName(agentName);\n logger.debug('Agent name resolved', {\n input: agentName,\n resolved: resolvedName\n });\n\n // 2. Load agent profile\n const agent = await this.config.profileLoader.loadProfile(resolvedName);\n\n // 3. Load abilities (smart selection based on task)\n const selectedAbilities = this.selectAbilities(agent, task);\n const abilities = await this.config.abilitiesManager.getAbilitiesText(\n selectedAbilities\n );\n\n logger.debug('Abilities selected', {\n total: agent.abilities.length,\n selected: selectedAbilities.length,\n abilities: selectedAbilities\n });\n\n // 4. Select provider (v4.10.0+: team-based → agent-based → router)\n const provider = await this.selectProviderForAgent(agent, options);\n\n // 5. Get paths\n const projectDir = await this.config.pathResolver.detectProjectRoot();\n const workingDir = process.cwd();\n\n // Security: Sanitize agent name for directory (prevent path traversal)\n const agentDirName = agent.name.replace(/[^a-zA-Z0-9-]/g, '-').toLowerCase();\n const agentWorkspace = join(projectDir, '.automatosx', 'workspaces', agentDirName);\n\n // Security: Verify workspace is within project boundary\n const resolvedWorkspace = resolve(agentWorkspace);\n const resolvedProject = resolve(projectDir);\n if (!resolvedWorkspace.startsWith(resolvedProject)) {\n throw PathError.traversal(agentWorkspace);\n }\n\n // 6. Create workspace with restricted permissions\n await mkdir(agentWorkspace, { recursive: true });\n\n // Security: Set restrictive permissions on Unix (700 = owner only)\n if (process.platform !== 'win32') {\n await chmod(agentWorkspace, 0o700);\n }\n\n logger.debug('Agent workspace created', { workspace: agentWorkspace });\n\n // 7. Handle session (if sessionId provided)\n let session: Session | undefined;\n if (options?.sessionId) {\n if (!this.config.sessionManager) {\n throw new Error(\n `SessionManager not configured but session ID was provided: ${options.sessionId}`\n );\n }\n\n const foundSession = await this.config.sessionManager.getSession(options.sessionId);\n if (!foundSession) {\n throw new Error(\n `Session not found: ${options.sessionId}. Please verify the session ID or create a new session.`\n );\n }\n session = foundSession;\n }\n\n // 8. Build orchestration metadata (v4.7.8+: all agents can delegate)\n let orchestration: OrchestrationMetadata | undefined;\n if (this.config.workspaceManager && this.config.profileLoader) {\n // Get list of available agents for delegation\n const allAgents = await this.config.profileLoader.listProfiles();\n\n // v4.7.8+: All agents can delegate by default\n // Only exclude self to prevent direct self-delegation (cycles still detected)\n const availableAgents = allAgents.filter(a => a !== agent.name);\n\n // Get shared workspace path\n const sharedWorkspace = session\n ? join(projectDir, '.automatosx', 'workspaces', 'shared', 'sessions', session.id)\n : join(projectDir, '.automatosx', 'workspaces', 'shared', 'persistent');\n\n // Respect maxDelegationDepth from agent config, default to 2\n const maxDelegationDepth = agent.orchestration?.maxDelegationDepth ?? 2;\n\n orchestration = {\n isDelegationEnabled: true,\n availableAgents,\n sharedWorkspace,\n delegationChain: options?.delegationChain || [],\n maxDelegationDepth\n };\n\n logger.debug('Orchestration metadata built', {\n availableAgents,\n sharedWorkspace,\n delegationChain: orchestration.delegationChain,\n maxDelegationDepth\n });\n }\n\n // 9. Create context\n const context: ExecutionContext = {\n agent,\n task,\n memory: [],\n projectDir,\n workingDir,\n agentWorkspace,\n provider,\n abilities,\n createdAt: new Date(),\n orchestration,\n session\n };\n\n // 10. Inject memory (if not skipped)\n if (!options?.skipMemory) {\n await this.injectMemory(\n context,\n task,\n options?.memoryLimit\n );\n }\n\n logger.info('Execution context created', {\n agent: agent.name,\n provider: provider.name,\n memoryEntries: context.memory.length,\n hasAbilities: abilities.length > 0,\n hasOrchestration: !!orchestration,\n isDelegationEnabled: orchestration?.isDelegationEnabled ?? false\n });\n\n return context;\n }\n\n /**\n * Inject memory into context (search by task)\n */\n async injectMemory(\n context: ExecutionContext,\n query?: string,\n limit: number = 5\n ): Promise<void> {\n // Skip if no memory manager available\n if (!this.config.memoryManager) {\n logger.debug('Memory injection skipped: no memory manager available');\n context.memory = [];\n return;\n }\n\n const searchQuery = query || context.task;\n\n try {\n const results = await this.config.memoryManager.search({\n text: searchQuery,\n limit\n });\n\n context.memory = results.map(r => r.entry);\n\n logger.debug('Memory injected', {\n query: searchQuery,\n count: context.memory.length\n });\n\n } catch (error) {\n logger.warn('Failed to inject memory', {\n error: (error as Error).message\n });\n // Continue without memory\n context.memory = [];\n }\n }\n\n /**\n * Select abilities based on task keywords (smart selection)\n */\n private selectAbilities(agent: AgentProfile, task: string): string[] {\n // If no abilitySelection config, load all abilities (backward compatible)\n if (!agent.abilitySelection || agent.abilitySelection.loadAll) {\n return agent.abilities || [];\n }\n\n const taskLower = task.toLowerCase();\n const selectedAbilities = new Set<string>();\n const availableAbilities = new Set(agent.abilities || []);\n\n // Always load core abilities\n if (agent.abilitySelection.core) {\n agent.abilitySelection.core.forEach(a => {\n if (availableAbilities.has(a)) {\n selectedAbilities.add(a);\n } else {\n logger.warn('Core ability not found in agent abilities list', {\n ability: a,\n agent: agent.name\n });\n }\n });\n }\n\n // Task-based selection\n if (agent.abilitySelection.taskBased) {\n for (const [keyword, abilities] of Object.entries(agent.abilitySelection.taskBased)) {\n if (taskLower.includes(keyword.toLowerCase())) {\n abilities.forEach(a => {\n if (availableAbilities.has(a)) {\n selectedAbilities.add(a);\n } else {\n logger.warn('Task-based ability not found in agent abilities list', {\n ability: a,\n keyword,\n agent: agent.name\n });\n }\n });\n logger.debug('Task keyword matched', { keyword, abilities: abilities.filter(a => availableAbilities.has(a)) });\n }\n }\n }\n\n // If no task-based matches, return core abilities only\n const selected = Array.from(selectedAbilities);\n\n // Fallback: if no abilities selected, load core or first 2 abilities\n if (selected.length === 0) {\n logger.debug('No task-based matches, using fallback');\n return agent.abilities.slice(0, 2);\n }\n\n return selected;\n }\n\n /**\n * Select provider for an agent (v4.10.0+: team-based configuration)\n * Priority: CLI option → team config → agent config → router\n */\n async selectProviderForAgent(\n agent: AgentProfile,\n options?: ContextOptions\n ): Promise<Provider> {\n // 1. CLI option overrides everything\n if (options?.provider) {\n const provider = await this.tryGetProvider(options.provider);\n if (provider) {\n logger.debug('Using CLI-specified provider', { provider: options.provider });\n return provider;\n }\n }\n\n // 2. Try team configuration (v4.10.0+)\n if (agent.team) {\n try {\n const teamConfig = await this.config.profileLoader.getTeamConfig(agent.name);\n if (teamConfig) {\n logger.debug('Using team provider configuration', {\n agent: agent.name,\n team: teamConfig.name,\n primary: teamConfig.provider.primary\n });\n\n // Try fallbackChain if specified, otherwise use primary + fallback\n const providersToTry = teamConfig.provider.fallbackChain ||\n [teamConfig.provider.primary, teamConfig.provider.fallback].filter((p): p is string => Boolean(p));\n\n for (const providerName of providersToTry) {\n const provider = await this.tryGetProvider(providerName);\n if (provider) {\n if (providerName !== teamConfig.provider.primary) {\n logger.info('Team primary provider unavailable, using fallback', {\n team: teamConfig.name,\n primary: teamConfig.provider.primary,\n using: providerName\n });\n }\n return provider;\n }\n }\n\n logger.warn('All team providers unavailable, falling back to router', {\n team: teamConfig.name,\n triedProviders: providersToTry\n });\n }\n } catch (error) {\n logger.warn('Failed to load team configuration, using agent defaults', {\n agent: agent.name,\n team: agent.team,\n error: (error as Error).message\n });\n }\n }\n\n // 3. Fallback to agent's own configuration (deprecated but supported)\n if (agent.provider || agent.fallbackProvider) {\n logger.debug('Using agent provider configuration (deprecated)', {\n agent: agent.name,\n provider: agent.provider,\n fallback: agent.fallbackProvider\n });\n\n return await this.selectProvider(agent.provider, agent.fallbackProvider);\n }\n\n // 4. Final fallback: use router (global priority)\n const provider = await this.config.router.selectProvider();\n if (!provider) {\n throw ProviderError.noAvailableProviders();\n }\n\n logger.info('Using router-selected provider', {\n provider: provider.name,\n agent: agent.name\n });\n\n return provider;\n }\n\n /**\n * Try to get a specific provider if available\n */\n /**\n * Try to get provider by name, with alias support (v5.0.7+)\n */\n private async tryGetProvider(providerName: string): Promise<Provider | undefined> {\n const availableProviders = await this.config.router.getAvailableProviders();\n\n // Try exact match first\n let provider = availableProviders.find(p => p.name === providerName);\n if (provider) {\n return provider;\n }\n\n // Try alias mapping (e.g., 'claude' → 'claude-code')\n const aliasedName = PROVIDER_ALIASES[providerName];\n if (aliasedName) {\n provider = availableProviders.find(p => p.name === aliasedName);\n if (provider) {\n logger.debug('Resolved provider via alias', {\n requested: providerName,\n resolved: aliasedName\n });\n return provider;\n }\n }\n\n return undefined;\n }\n\n /**\n * Select provider (from agent preference or router)\n * Tries: primary → fallback → router (global priority)\n * @deprecated v4.10.0+ Use selectProviderForAgent instead\n */\n async selectProvider(\n preferredProvider?: string,\n fallbackProvider?: string\n ): Promise<Provider> {\n const availableProviders = await this.config.router.getAvailableProviders();\n\n // 1. Try primary provider\n if (preferredProvider) {\n const provider = availableProviders.find(p => p.name === preferredProvider);\n\n if (provider) {\n logger.debug('Using primary provider', { provider: preferredProvider });\n return provider;\n }\n\n logger.warn('Primary provider not available', {\n primary: preferredProvider\n });\n }\n\n // 2. Try fallback provider\n if (fallbackProvider) {\n const provider = availableProviders.find(p => p.name === fallbackProvider);\n\n if (provider) {\n logger.info('Using fallback provider', {\n fallback: fallbackProvider,\n primary: preferredProvider\n });\n return provider;\n }\n\n logger.warn('Fallback provider not available', {\n fallback: fallbackProvider\n });\n }\n\n // 3. Use router to select best provider (global priority)\n const provider = await this.config.router.selectProvider();\n\n if (!provider) {\n throw ProviderError.noAvailableProviders();\n }\n\n logger.info('Using router-selected provider (final fallback)', {\n provider: provider.name,\n primary: preferredProvider,\n fallback: fallbackProvider\n });\n return provider;\n }\n\n /**\n * Cleanup context (delete workspace if needed)\n */\n async cleanup(context: ExecutionContext): Promise<void> {\n // For now, keep workspace for debugging\n // In future, add option to auto-cleanup\n logger.debug('Context cleanup', {\n agent: context.agent.name,\n workspace: context.agentWorkspace\n });\n }\n}\n","/**\n * Profile Loader - Load and validate agent profiles from YAML\n */\n\nimport { readFile, readdir } from 'fs/promises';\nimport { join, extname, basename, dirname } from 'path';\nimport { fileURLToPath } from 'url';\nimport { load } from 'js-yaml';\nimport type { AgentProfile } from '../types/agent.js';\nimport { AgentValidationError, AgentNotFoundError } from '../types/agent.js';\nimport { logger } from '../utils/logger.js';\nimport { TTLCache } from '../core/cache.js';\nimport type { TeamManager } from '../core/team-manager.js';\nimport type { TeamConfig } from '../types/team.js';\n\n// Get the directory of this file for locating built-in agents\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\n// Get package root - handle both dev (src/) and prod (dist/) scenarios\nfunction getPackageRoot(): string {\n // In production, __dirname will be dist/\n // In development, __dirname will be src/agents/\n const currentDir = __dirname;\n\n // If we're in dist/, go up one level to package root\n // If we're in src/agents/, go up two levels to package root\n if (currentDir.includes('/dist')) {\n return join(currentDir, '..');\n } else {\n return join(currentDir, '../..');\n }\n}\n\n/**\n * Profile Loader - Load and validate agent profiles\n */\nexport class ProfileLoader {\n private profilesDir: string;\n private fallbackProfilesDir: string;\n private cache: TTLCache<AgentProfile>;\n private displayNameMap: Map<string, string> = new Map();\n private mapInitialized: boolean = false;\n private teamManager?: TeamManager;\n\n constructor(profilesDir: string, fallbackProfilesDir?: string, teamManager?: TeamManager) {\n this.profilesDir = profilesDir;\n // Default fallback to built-in examples/agents\n // This should work in both dev and production environments\n this.fallbackProfilesDir = fallbackProfilesDir || join(getPackageRoot(), 'examples/agents');\n // Use TTLCache with 5 minute TTL for profile caching\n this.cache = new TTLCache<AgentProfile>({\n maxEntries: 20,\n ttl: 300000, // 5 minutes\n cleanupInterval: 60000, // Cleanup every minute\n debug: false\n });\n // v4.10.0+: Optional TeamManager for team-based configuration\n this.teamManager = teamManager;\n }\n\n /**\n * Build displayName → name mapping table (lightweight)\n * Only reads displayName field from YAML, doesn't load full profile\n * Priority: Local .automatosx/agents override examples/agents\n */\n private async buildDisplayNameMap(): Promise<void> {\n if (this.mapInitialized) {\n return;\n }\n\n logger.debug('Building displayName mapping table');\n this.displayNameMap.clear();\n\n try {\n // Priority 1: Process local profiles first (.automatosx/agents)\n const localProfiles = await this.listProfilesFromDir(this.profilesDir);\n for (const name of localProfiles) {\n await this.addToDisplayNameMap(name, 'local');\n }\n\n // Priority 2: Process fallback profiles (examples/agents)\n // These will NOT override local profiles with the same displayName\n const fallbackProfiles = await this.listProfilesFromDir(this.fallbackProfilesDir);\n for (const name of fallbackProfiles) {\n // Skip if already exists in local profiles (by name)\n if (localProfiles.includes(name)) {\n logger.debug('Skipping fallback profile (local override)', { name });\n continue;\n }\n await this.addToDisplayNameMap(name, 'fallback');\n }\n\n this.mapInitialized = true;\n logger.info('DisplayName mapping built', {\n mappings: this.displayNameMap.size,\n localProfiles: localProfiles.length,\n fallbackProfiles: fallbackProfiles.length\n });\n } catch (error) {\n logger.error('Failed to build displayName mapping', { error });\n // Don't throw - allow fallback to direct name lookup\n }\n }\n\n /**\n * Helper: Add profile to displayName map\n */\n private async addToDisplayNameMap(name: string, source: 'local' | 'fallback'): Promise<void> {\n try {\n // Lightweight: Only read displayName field, not full profile\n const displayName = await this.readDisplayNameOnly(name);\n\n if (displayName) {\n const lowerDisplayName = displayName.toLowerCase();\n\n // Check for duplicate display names\n const existing = this.displayNameMap.get(lowerDisplayName);\n if (existing) {\n logger.warn('Duplicate displayName detected', {\n displayName,\n existingAgent: existing,\n newAgent: name,\n source,\n resolution: `Keeping existing (${existing})`\n });\n // Keep existing entry (local profiles have priority)\n return;\n }\n\n // Store case-insensitive mapping\n this.displayNameMap.set(lowerDisplayName, name);\n logger.debug('Mapped displayName to agent', {\n displayName,\n name,\n source\n });\n }\n } catch (error) {\n // Skip profiles that fail to read\n logger.warn('Failed to read displayName for mapping', { name, source, error });\n }\n }\n\n /**\n * Helper: List profiles from a specific directory\n */\n private async listProfilesFromDir(dir: string): Promise<string[]> {\n try {\n const files = await readdir(dir);\n return files\n .filter(file => extname(file) === '.yaml' || extname(file) === '.yml')\n .map(file => basename(file, extname(file)));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n // Directory doesn't exist\n return [];\n }\n throw error;\n }\n }\n\n /**\n * Read only displayName field from YAML (lightweight, no full parsing)\n * Returns null if no displayName or file doesn't exist\n */\n private async readDisplayNameOnly(name: string): Promise<string | null> {\n const profilePaths = this.getProfilePath(name);\n\n for (const profilePath of profilePaths) {\n try {\n const content = await readFile(profilePath, 'utf-8');\n\n // Security: Limit file size check (same as loadProfile)\n if (content.length > 100 * 1024) {\n continue;\n }\n\n // Parse YAML to extract only displayName\n const data = load(content) as any;\n return data.displayName || null;\n\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n // File not found, try next path\n continue;\n }\n // Other errors, skip this profile\n return null;\n }\n }\n\n return null;\n }\n\n /**\n * Resolve agent identifier (name or displayName) to actual profile name\n * Optimized: Try direct load first, only build full mapping if needed\n */\n async resolveAgentName(identifier: string): Promise<string> {\n // Optimization: Try direct profile load first (most common case)\n // This avoids loading all profiles when using profile names directly\n try {\n await this.loadProfile(identifier);\n // If load succeeds, identifier is a valid profile name\n logger.debug('Using identifier as profile name (direct match)', { identifier });\n return identifier;\n } catch (error) {\n // Profile not found directly, might be a displayName\n // Only now build the displayName mapping if not already done\n if ((error as any).name === 'AgentNotFoundError') {\n logger.debug('Direct profile load failed, trying displayName lookup', { identifier });\n\n // Build map lazily if not already built\n await this.buildDisplayNameMap();\n\n // Try case-insensitive displayName lookup\n const resolved = this.displayNameMap.get(identifier.toLowerCase());\n if (resolved) {\n logger.debug('Resolved displayName to agent name', {\n displayName: identifier,\n name: resolved\n });\n return resolved;\n }\n\n // Still not found, throw the original error\n throw error;\n }\n\n // Other errors (validation, etc.) should be propagated\n throw error;\n }\n }\n\n /**\n * Load a specific agent profile\n */\n async loadProfile(name: string): Promise<AgentProfile> {\n // Check cache first\n const cached = this.cache.get(name);\n if (cached) {\n logger.debug('Profile loaded from cache', { name });\n return cached;\n }\n\n // Get possible paths (primary and fallback)\n const profilePaths = this.getProfilePath(name);\n\n // Try each path in order\n for (const profilePath of profilePaths) {\n try {\n const content = await readFile(profilePath, 'utf-8');\n\n // Security: Limit file size to prevent DoS (max 100KB for profile)\n if (content.length > 100 * 1024) {\n throw new AgentValidationError('Profile file too large (max 100KB)');\n }\n\n // Security: Use safe YAML parsing (default safe schema)\n // Note: js-yaml's load() already uses safe schema by default\n const data = load(content) as any;\n\n // Validate and build profile (v4.10.0+: async for team inheritance)\n const profile = await this.buildProfile(data, name);\n\n // Cache it\n this.cache.set(name, profile);\n\n logger.info('Profile loaded', { name, path: profilePath });\n return profile;\n\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n // File not found, try next path\n continue;\n }\n // Other errors should be thrown immediately\n throw error;\n }\n }\n\n // If we've tried all paths and none worked, throw AgentNotFoundError\n throw new AgentNotFoundError(name);\n }\n\n /**\n * List all available profiles\n */\n async listProfiles(): Promise<string[]> {\n const profileSet = new Set<string>();\n\n // Try to load from primary directory\n try {\n const files = await readdir(this.profilesDir);\n const profiles = files\n .filter(file => extname(file) === '.yaml' || extname(file) === '.yml')\n .map(file => basename(file, extname(file)));\n\n profiles.forEach(p => profileSet.add(p));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw error;\n }\n // Directory doesn't exist, will fallback to built-in agents\n }\n\n // Also load from fallback directory (built-in agents)\n try {\n const files = await readdir(this.fallbackProfilesDir);\n const profiles = files\n .filter(file => extname(file) === '.yaml' || extname(file) === '.yml')\n .map(file => basename(file, extname(file)));\n\n profiles.forEach(p => profileSet.add(p));\n } catch (error) {\n // Fallback directory doesn't exist - this is OK\n logger.debug('Fallback profiles directory not found', {\n dir: this.fallbackProfilesDir\n });\n }\n\n return Array.from(profileSet).sort();\n }\n\n /**\n * Calculate Levenshtein distance between two strings (for fuzzy matching)\n */\n private levenshteinDistance(a: string, b: string): number {\n const matrix: number[][] = [];\n\n for (let i = 0; i <= b.length; i++) {\n matrix[i] = [i];\n }\n\n for (let j = 0; j <= a.length; j++) {\n matrix[0]![j] = j;\n }\n\n for (let i = 1; i <= b.length; i++) {\n for (let j = 1; j <= a.length; j++) {\n if (b.charAt(i - 1) === a.charAt(j - 1)) {\n matrix[i]![j] = matrix[i - 1]![j - 1]!;\n } else {\n matrix[i]![j] = Math.min(\n matrix[i - 1]![j - 1]! + 1, // substitution\n matrix[i]![j - 1]! + 1, // insertion\n matrix[i - 1]![j]! + 1 // deletion\n );\n }\n }\n }\n\n return matrix[b.length]![a.length]!;\n }\n\n /**\n * Find similar agent names using fuzzy matching\n * Returns agents sorted by similarity (most similar first)\n */\n async findSimilarAgents(query: string, maxResults: number = 3): Promise<Array<{ name: string; displayName?: string; role?: string; distance: number }>> {\n const allProfiles = await this.listProfiles();\n const similarities: Array<{ name: string; displayName?: string; role?: string; distance: number }> = [];\n\n // Build displayName map if not already done\n await this.buildDisplayNameMap();\n\n for (const profileName of allProfiles) {\n try {\n // Calculate distance for profile name\n const nameDistance = this.levenshteinDistance(query.toLowerCase(), profileName.toLowerCase());\n\n // Try to get displayName and role for better matching\n const displayName = await this.readDisplayNameOnly(profileName);\n let minDistance = nameDistance;\n\n // Also check distance with displayName\n if (displayName) {\n const displayDistance = this.levenshteinDistance(query.toLowerCase(), displayName.toLowerCase());\n minDistance = Math.min(minDistance, displayDistance);\n }\n\n // Load profile to get role (suppress logs)\n try {\n const cached = this.cache.get(profileName);\n let profile: AgentProfile | undefined = cached;\n\n if (!profile) {\n // Load without logging (for similarity search)\n const profilePaths = this.getProfilePath(profileName);\n for (const profilePath of profilePaths) {\n try {\n const content = await readFile(profilePath, 'utf-8');\n if (content.length > 100 * 1024) continue;\n const data = load(content) as any;\n profile = await this.buildProfile(data, profileName);\n this.cache.set(profileName, profile);\n break;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n continue;\n }\n throw error;\n }\n }\n }\n\n if (profile) {\n const roleDistance = this.levenshteinDistance(query.toLowerCase(), profile.role.toLowerCase());\n minDistance = Math.min(minDistance, roleDistance);\n\n similarities.push({\n name: profileName,\n displayName: displayName || undefined,\n role: profile.role,\n distance: minDistance\n });\n } else {\n // Profile not found, just use name/displayName distance\n similarities.push({\n name: profileName,\n displayName: displayName || undefined,\n distance: minDistance\n });\n }\n } catch {\n // If profile fails to load, just use name/displayName distance\n similarities.push({\n name: profileName,\n displayName: displayName || undefined,\n distance: minDistance\n });\n }\n } catch (error) {\n // Skip profiles that fail\n logger.debug('Failed to calculate similarity', { profileName, error });\n }\n }\n\n // Sort by distance (lower is better) and return top N\n return similarities\n .sort((a, b) => a.distance - b.distance)\n .slice(0, maxResults);\n }\n\n /**\n * Validate profile structure\n */\n validateProfile(profile: AgentProfile): boolean {\n const required = ['name', 'role', 'description', 'systemPrompt'];\n\n for (const field of required) {\n if (!profile[field as keyof AgentProfile]) {\n throw new AgentValidationError(`Missing required field: ${field}`);\n }\n }\n\n // Validate types\n if (typeof profile.name !== 'string') {\n throw new AgentValidationError('name must be a string');\n }\n\n if (typeof profile.role !== 'string') {\n throw new AgentValidationError('role must be a string');\n }\n\n if (typeof profile.description !== 'string') {\n throw new AgentValidationError('description must be a string');\n }\n\n if (typeof profile.systemPrompt !== 'string') {\n throw new AgentValidationError('systemPrompt must be a string');\n }\n\n // Validate optional fields\n if (profile.abilities && !Array.isArray(profile.abilities)) {\n throw new AgentValidationError('abilities must be an array');\n }\n\n if (profile.temperature !== undefined) {\n if (typeof profile.temperature !== 'number' || profile.temperature < 0 || profile.temperature > 1) {\n throw new AgentValidationError('temperature must be a number between 0 and 1');\n }\n }\n\n if (profile.maxTokens !== undefined) {\n if (typeof profile.maxTokens !== 'number' || profile.maxTokens < 1) {\n throw new AgentValidationError('maxTokens must be a positive number');\n }\n }\n\n // Validate v4.1+ enhanced fields\n if (profile.stages !== undefined) {\n if (!Array.isArray(profile.stages)) {\n throw new AgentValidationError('stages must be an array');\n }\n\n profile.stages.forEach((stage, i) => {\n if (!stage.name || typeof stage.name !== 'string') {\n throw new AgentValidationError(`stages[${i}].name is required and must be a string`);\n }\n if (!stage.description || typeof stage.description !== 'string') {\n throw new AgentValidationError(`stages[${i}].description is required and must be a string`);\n }\n if (stage.key_questions !== undefined && !Array.isArray(stage.key_questions)) {\n throw new AgentValidationError(`stages[${i}].key_questions must be an array`);\n }\n if (stage.outputs !== undefined && !Array.isArray(stage.outputs)) {\n throw new AgentValidationError(`stages[${i}].outputs must be an array`);\n }\n if (stage.model !== undefined && typeof stage.model !== 'string') {\n throw new AgentValidationError(`stages[${i}].model must be a string`);\n }\n if (stage.temperature !== undefined) {\n if (typeof stage.temperature !== 'number' || stage.temperature < 0 || stage.temperature > 1) {\n throw new AgentValidationError(`stages[${i}].temperature must be a number between 0 and 1`);\n }\n }\n });\n }\n\n if (profile.personality !== undefined) {\n if (typeof profile.personality !== 'object' || profile.personality === null || Array.isArray(profile.personality)) {\n throw new AgentValidationError('personality must be an object');\n }\n // Validate personality fields if present\n const p = profile.personality;\n if (p.traits !== undefined && !Array.isArray(p.traits)) {\n throw new AgentValidationError('personality.traits must be an array');\n }\n if (p.catchphrase !== undefined && typeof p.catchphrase !== 'string') {\n throw new AgentValidationError('personality.catchphrase must be a string');\n }\n if (p.communication_style !== undefined && typeof p.communication_style !== 'string') {\n throw new AgentValidationError('personality.communication_style must be a string');\n }\n if (p.decision_making !== undefined && typeof p.decision_making !== 'string') {\n throw new AgentValidationError('personality.decision_making must be a string');\n }\n }\n\n if (profile.thinking_patterns !== undefined) {\n if (!Array.isArray(profile.thinking_patterns)) {\n throw new AgentValidationError('thinking_patterns must be an array');\n }\n }\n\n // Validate v4.5.8+ abilitySelection\n if (profile.abilitySelection !== undefined) {\n const as = profile.abilitySelection;\n\n if (typeof as !== 'object' || as === null || Array.isArray(as)) {\n throw new AgentValidationError('abilitySelection must be an object');\n }\n\n if (as.core !== undefined) {\n if (!Array.isArray(as.core)) {\n throw new AgentValidationError('abilitySelection.core must be an array');\n }\n // Validate core abilities are strings\n as.core.forEach((ability, i) => {\n if (typeof ability !== 'string') {\n throw new AgentValidationError(`abilitySelection.core[${i}] must be a string`);\n }\n });\n }\n\n if (as.taskBased !== undefined) {\n if (typeof as.taskBased !== 'object' || as.taskBased === null || Array.isArray(as.taskBased)) {\n throw new AgentValidationError('abilitySelection.taskBased must be an object');\n }\n // Validate taskBased structure: keyword -> abilities[]\n Object.entries(as.taskBased).forEach(([keyword, abilities]) => {\n if (!Array.isArray(abilities)) {\n throw new AgentValidationError(`abilitySelection.taskBased[\"${keyword}\"] must be an array`);\n }\n abilities.forEach((ability, i) => {\n if (typeof ability !== 'string') {\n throw new AgentValidationError(`abilitySelection.taskBased[\"${keyword}\"][${i}] must be a string`);\n }\n });\n });\n }\n\n if (as.loadAll !== undefined && typeof as.loadAll !== 'boolean') {\n throw new AgentValidationError('abilitySelection.loadAll must be a boolean');\n }\n }\n\n // Validate v4.7.0+ orchestration\n if (profile.orchestration !== undefined) {\n const orch = profile.orchestration;\n\n if (typeof orch !== 'object' || orch === null || Array.isArray(orch)) {\n throw new AgentValidationError('orchestration must be an object');\n }\n\n // v4.9.0: canDelegate is deprecated and ignored\n if ((orch as any).canDelegate !== undefined) {\n logger.warn('orchestration.canDelegate is deprecated and ignored (v4.9.0+). All agents can delegate by default.', {\n agent: profile.name\n });\n }\n\n if (orch.maxDelegationDepth !== undefined) {\n if (typeof orch.maxDelegationDepth !== 'number' || orch.maxDelegationDepth < 0 || !Number.isInteger(orch.maxDelegationDepth)) {\n throw new AgentValidationError('orchestration.maxDelegationDepth must be a non-negative integer (0 = no delegation allowed)');\n }\n }\n\n if (orch.canReadWorkspaces !== undefined) {\n if (!Array.isArray(orch.canReadWorkspaces)) {\n throw new AgentValidationError('orchestration.canReadWorkspaces must be an array');\n }\n orch.canReadWorkspaces.forEach((workspace, i) => {\n if (typeof workspace !== 'string') {\n throw new AgentValidationError(`orchestration.canReadWorkspaces[${i}] must be a string`);\n }\n });\n }\n\n if (orch.canWriteToShared !== undefined && typeof orch.canWriteToShared !== 'boolean') {\n throw new AgentValidationError('orchestration.canWriteToShared must be a boolean');\n }\n }\n\n return true;\n }\n\n /**\n * Get profile path (with path traversal protection)\n * Returns an array of possible paths to try (primary first, then fallback)\n */\n getProfilePath(name: string): string[] {\n // Security: Prevent path traversal attacks\n // Only allow alphanumeric, dash, underscore in profile names\n if (!/^[a-zA-Z0-9_-]+$/.test(name)) {\n throw new AgentValidationError(`Invalid profile name: ${name}. Only alphanumeric characters, dashes, and underscores are allowed.`);\n }\n\n // Return paths to try in order: primary directory, then fallback\n return [\n join(this.profilesDir, `${name}.yaml`),\n join(this.fallbackProfilesDir, `${name}.yaml`)\n ];\n }\n\n /**\n * Clear cache and displayName mapping\n */\n clearCache(): void {\n this.cache.clear();\n this.displayNameMap.clear();\n this.mapInitialized = false;\n logger.debug('Cache and displayName mapping cleared');\n }\n\n /**\n * Build profile from raw data with defaults\n * v4.10.0+: Supports team-based configuration inheritance\n */\n private async buildProfile(data: any, name: string): Promise<AgentProfile> {\n let teamConfig: TeamConfig | undefined;\n\n // v4.10.0+: Load team configuration if specified\n if (data.team && this.teamManager) {\n try {\n teamConfig = await this.teamManager.loadTeam(data.team);\n logger.debug('Team configuration loaded for agent', {\n agent: name,\n team: data.team\n });\n } catch (error) {\n logger.warn('Failed to load team configuration, using agent defaults', {\n agent: name,\n team: data.team,\n error: (error as Error).message\n });\n }\n }\n\n // Merge abilities: team's sharedAbilities + agent's abilities\n const abilities = data.abilities || [];\n if (teamConfig?.sharedAbilities) {\n // Combine team shared abilities with agent-specific abilities\n // Remove duplicates using Set\n const allAbilities = [...new Set([...teamConfig.sharedAbilities, ...abilities])];\n logger.debug('Merged abilities from team', {\n agent: name,\n team: teamConfig.name,\n teamAbilities: teamConfig.sharedAbilities.length,\n agentAbilities: abilities.length,\n totalAbilities: allAbilities.length\n });\n abilities.splice(0, abilities.length, ...allAbilities);\n }\n\n // Merge orchestration: team defaults + agent overrides\n let orchestration = data.orchestration;\n if (teamConfig?.orchestration && !orchestration) {\n // Use team orchestration defaults if agent doesn't specify its own\n orchestration = teamConfig.orchestration;\n logger.debug('Using team orchestration defaults', {\n agent: name,\n team: teamConfig.name\n });\n }\n\n const profile: AgentProfile = {\n name: data.name || name,\n displayName: data.displayName,\n role: data.role,\n description: data.description,\n // v4.10.0+: Team field\n team: data.team,\n systemPrompt: data.systemPrompt,\n abilities: abilities,\n // Enhanced v4.1+ features\n stages: data.stages,\n personality: data.personality,\n thinking_patterns: data.thinking_patterns,\n abilitySelection: data.abilitySelection,\n // Provider preferences (deprecated, kept for backward compatibility)\n provider: data.provider,\n model: data.model,\n temperature: data.temperature,\n maxTokens: data.maxTokens,\n // Optional\n tags: data.tags,\n version: data.version,\n metadata: data.metadata,\n // v4.7.0+ Orchestration (merged with team defaults)\n orchestration: orchestration\n };\n\n // Validate\n this.validateProfile(profile);\n\n return profile;\n }\n\n /**\n * Get team configuration for an agent (if available)\n * v4.10.0+: Used by ContextManager to get provider configuration\n */\n async getTeamConfig(agentName: string): Promise<TeamConfig | undefined> {\n if (!this.teamManager) {\n return undefined;\n }\n\n try {\n const profile = await this.loadProfile(agentName);\n if (profile.team) {\n return await this.teamManager.loadTeam(profile.team);\n }\n } catch (error) {\n logger.warn('Failed to get team config for agent', {\n agent: agentName,\n error: (error as Error).message\n });\n }\n\n return undefined;\n }\n}\n","/**\n * Agent Types - Agent Profile and Execution Context\n */\n\nimport type { Provider } from './provider.js';\nimport type { MemoryEntry } from './memory.js';\nimport type { OrchestrationConfig, OrchestrationMetadata, Session } from './orchestration.js';\n\n/**\n * Stage - A step in the agent's workflow\n */\nexport interface Stage {\n name: string;\n description: string;\n key_questions?: string[];\n outputs?: string[];\n\n /**\n * @deprecated Model and temperature are now configured at team level.\n * These fields are ignored. Configure provider behavior via CLI config files:\n * - Claude: Claude Code settings\n * - Gemini: ~/.config/gemini/settings.json\n * - Codex: ~/.codex/config.toml\n */\n model?: string;\n temperature?: number;\n\n // Phase 3: Advanced stage features\n dependencies?: string[]; // Stage names this stage depends on\n condition?: string; // Conditional execution (e.g., \"previous.success\")\n parallel?: boolean; // Can this stage run in parallel with others?\n streaming?: boolean; // Enable streaming output for this stage\n saveToMemory?: boolean; // Persist this stage's results to memory\n}\n\n/**\n * Personality - Defines agent's character and behavior\n */\nexport interface Personality {\n traits?: string[];\n catchphrase?: string;\n communication_style?: string;\n decision_making?: string;\n}\n\n/**\n * Ability Selection Strategy - How to select abilities for different tasks\n */\nexport interface AbilitySelection {\n // Core abilities always loaded\n core?: string[];\n // Task-based ability mapping (keyword -> abilities)\n taskBased?: Record<string, string[]>;\n // Load all abilities (default behavior)\n loadAll?: boolean;\n}\n\n/**\n * Agent Profile - Loaded from YAML\n */\nexport interface AgentProfile {\n // Metadata\n name: string;\n displayName?: string; // Human-friendly name (e.g., \"Bob\", \"Eric\")\n role: string;\n description: string;\n\n // v4.10.0+ Team-based configuration\n team?: string; // Team name (e.g., \"core\", \"engineering\", \"business\", \"design\")\n // Agents inherit provider config from their team\n\n // Behavior\n systemPrompt: string;\n abilities: string[]; // List of ability file names (agent-specific, added to team's sharedAbilities)\n\n // Enhanced v4.1+ features\n stages?: Stage[]; // Workflow stages\n personality?: Personality; // Character traits\n thinking_patterns?: string[]; // Guiding principles\n abilitySelection?: AbilitySelection; // Smart ability loading\n\n /**\n * Provider configuration (v4.10.0+)\n *\n * Recommended approach:\n * 1. Assign agent to a team via `team: \"engineering\"`\n * 2. Configure provider at team level in .automatosx/teams/<team>.yaml\n *\n * Alternative (per-agent override):\n * Configure directly in agent YAML for specific needs:\n * - provider: Override team's provider choice\n * - model: Specific model for this agent\n * - temperature: Control randomness (0 = deterministic, 2 = creative)\n * - maxTokens: Limit output length (cost control or specific use case)\n *\n * Note: Only OpenAI Codex CLI currently supports temperature/maxTokens parameters.\n * Gemini and Claude use their CLI's default settings.\n */\n provider?: string; // Provider override (e.g., \"openai\", \"gemini-cli\", \"claude-code\")\n fallbackProvider?: string; // Fallback if primary provider unavailable\n model?: string; // Model override (e.g., \"gpt-4o\", \"gemini-2.0-flash-exp\")\n temperature?: number; // Randomness control: 0-2 (OpenAI only)\n maxTokens?: number; // Max output tokens (OpenAI only)\n\n // Optional\n tags?: string[];\n version?: string;\n metadata?: Record<string, any>;\n\n // v4.7.0+ Orchestration\n orchestration?: OrchestrationConfig; // Agent collaboration capabilities\n}\n\n/**\n * Execution Context - Everything needed to execute an agent\n */\nexport interface ExecutionContext {\n // Agent info\n agent: AgentProfile;\n task: string;\n\n // Memory (injected from MemoryManager)\n memory: MemoryEntry[];\n\n // Paths (from PathResolver)\n projectDir: string;\n workingDir: string;\n agentWorkspace: string;\n\n // Provider (selected from Router)\n provider: Provider;\n\n // Abilities (from AbilitiesManager)\n abilities: string;\n\n // Timestamp\n createdAt: Date;\n\n // v4.7.0+ Orchestration\n orchestration?: OrchestrationMetadata; // Runtime orchestration info\n session?: Session; // Current session (if part of multi-agent workflow)\n}\n\n/**\n * Context creation options\n */\nexport interface ContextOptions {\n provider?: string; // Override provider\n model?: string; // Override model\n skipMemory?: boolean; // Skip memory injection\n memoryLimit?: number; // Limit memory entries\n\n // v4.7.0+ Orchestration options\n sessionId?: string; // Session ID for multi-agent workflows\n delegationChain?: string[]; // Current delegation chain (for cycle detection)\n sharedData?: Record<string, any>; // Shared data from delegating agent\n}\n\n/**\n * Agent validation error\n */\nexport class AgentValidationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'AgentValidationError';\n }\n}\n\n/**\n * Agent not found error\n */\nexport class AgentNotFoundError extends Error {\n constructor(agentName: string) {\n super(`Agent not found: ${agentName}`);\n this.name = 'AgentNotFoundError';\n }\n}\n","/**\n * Abilities Manager - Load and inject agent abilities from markdown files\n */\n\nimport { readFile, readdir } from 'fs/promises';\nimport { join, extname, basename, dirname } from 'path';\nimport { fileURLToPath } from 'url';\nimport { logger } from '../utils/logger.js';\nimport { TTLCache } from '../core/cache.js';\n\n// Get the directory of this file for locating built-in abilities\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\n// Get package root - handle both dev (src/) and prod (dist/) scenarios\nfunction getPackageRoot(): string {\n const currentDir = __dirname;\n if (currentDir.includes('/dist')) {\n return join(currentDir, '..');\n } else {\n return join(currentDir, '../..');\n }\n}\n\n/**\n * Abilities Manager - Load and manage agent abilities\n */\nexport class AbilitiesManager {\n private abilitiesDir: string;\n private fallbackAbilitiesDir: string;\n private cache: TTLCache<string>;\n\n constructor(abilitiesDir: string, fallbackAbilitiesDir?: string) {\n this.abilitiesDir = abilitiesDir;\n // Default fallback to built-in examples/abilities\n this.fallbackAbilitiesDir = fallbackAbilitiesDir || join(getPackageRoot(), 'examples/abilities');\n // Use TTLCache with 10 minute TTL for abilities (they change less frequently)\n this.cache = new TTLCache<string>({\n maxEntries: 50,\n ttl: 600000, // 10 minutes\n maxSize: 5 * 1024 * 1024, // 5MB total cache size\n cleanupInterval: 120000, // Cleanup every 2 minutes\n debug: false\n });\n }\n\n /**\n * Load a single ability by name\n */\n async loadAbility(name: string): Promise<string> {\n // Security: Validate ability name to prevent path traversal\n if (!/^[a-zA-Z0-9_-]+$/.test(name)) {\n logger.warn('Invalid ability name rejected', { name });\n throw new Error(`Invalid ability name: ${name}. Only alphanumeric characters, dashes, and underscores are allowed.`);\n }\n\n // Check cache first\n const cached = this.cache.get(name);\n if (cached) {\n logger.debug('Ability loaded from cache', { name });\n return cached;\n }\n\n // Try primary directory first, then fallback\n const paths = [\n join(this.abilitiesDir, `${name}.md`),\n join(this.fallbackAbilitiesDir, `${name}.md`)\n ];\n\n for (const abilityPath of paths) {\n try {\n const content = await readFile(abilityPath, 'utf-8');\n\n // Security: Limit file size to prevent DoS (max 500KB for ability)\n if (content.length > 500 * 1024) {\n throw new Error('Ability file too large (max 500KB)');\n }\n\n // Cache it\n this.cache.set(name, content);\n\n logger.info('Ability loaded', { name, path: abilityPath });\n return content;\n\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n // Try next path\n continue;\n }\n throw error;\n }\n }\n\n // If not found in any location, log warning and return empty string\n logger.warn('Ability not found in any location', { name });\n return ''; // Return empty string for missing abilities\n }\n\n /**\n * Load multiple abilities\n */\n async loadAbilities(names: string[]): Promise<Map<string, string>> {\n const abilities = new Map<string, string>();\n\n for (const name of names) {\n const content = await this.loadAbility(name);\n if (content) {\n abilities.set(name, content);\n }\n }\n\n return abilities;\n }\n\n /**\n * Get concatenated abilities text\n */\n async getAbilitiesText(names: string[]): Promise<string> {\n const abilities = await this.loadAbilities(names);\n\n if (abilities.size === 0) {\n return '';\n }\n\n // Concatenate all abilities with section headers\n const sections: string[] = [];\n\n for (const [name, content] of abilities.entries()) {\n sections.push(`## Ability: ${name}\\n\\n${content}`);\n }\n\n return sections.join('\\n\\n---\\n\\n');\n }\n\n /**\n * List all available abilities\n */\n async listAbilities(): Promise<string[]> {\n try {\n const files = await readdir(this.abilitiesDir);\n\n const abilities = files\n .filter(file => extname(file) === '.md')\n .map(file => basename(file, extname(file)));\n\n return abilities.sort();\n\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return [];\n }\n throw error;\n }\n }\n\n /**\n * Clear cache\n */\n clearCache(): void {\n this.cache.clear();\n }\n}\n","/**\n * Team Manager - Load and manage team configurations\n *\n * Teams provide shared configuration for groups of agents:\n * - Provider configuration (which AI providers to use)\n * - Shared abilities (common to all team members)\n * - Orchestration defaults (collaboration settings)\n */\n\nimport { readFile, readdir } from 'fs/promises';\nimport { join, extname, basename } from 'path';\nimport { load } from 'js-yaml';\nimport type { TeamConfig } from '../types/team.js';\nimport { TeamValidationError, TeamNotFoundError } from '../types/team.js';\nimport { logger } from '../utils/logger.js';\nimport { TTLCache } from './cache.js';\n\n/**\n * Team Manager - Load and validate team configurations\n */\nexport class TeamManager {\n private teamsDir: string;\n private cache: TTLCache<TeamConfig>;\n\n constructor(teamsDir: string) {\n this.teamsDir = teamsDir;\n // Use TTLCache with 10 minute TTL for team caching (longer than agents)\n // Teams change less frequently than agent profiles\n this.cache = new TTLCache<TeamConfig>({\n maxEntries: 10, // We only have 4 teams (core, engineering, business, design)\n ttl: 600000, // 10 minutes\n cleanupInterval: 120000, // Cleanup every 2 minutes\n debug: false\n });\n }\n\n /**\n * Load a specific team configuration\n */\n async loadTeam(teamName: string): Promise<TeamConfig> {\n logger.debug('Loading team', { teamName });\n\n // Check cache first\n const cached = this.cache.get(teamName);\n if (cached) {\n logger.debug('Team loaded from cache', { teamName });\n return cached;\n }\n\n try {\n // Load team configuration from YAML\n const teamPath = join(this.teamsDir, `${teamName}.yaml`);\n const content = await readFile(teamPath, 'utf-8');\n const team = load(content) as TeamConfig;\n\n // Validate team configuration\n this.validateTeam(team);\n\n // Cache and return\n this.cache.set(teamName, team);\n logger.info('Team loaded', { name: team.name, path: teamPath });\n\n return team;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n throw new TeamNotFoundError(teamName);\n }\n throw new TeamValidationError(`Failed to load team ${teamName}: ${(error as Error).message}`);\n }\n }\n\n /**\n * Get all available teams\n */\n async getAllTeams(): Promise<TeamConfig[]> {\n logger.debug('Loading all teams');\n\n try {\n const files = await readdir(this.teamsDir);\n const teamFiles = files.filter(f => extname(f) === '.yaml' || extname(f) === '.yml');\n\n const teams: TeamConfig[] = [];\n for (const file of teamFiles) {\n const teamName = basename(file, extname(file));\n try {\n const team = await this.loadTeam(teamName);\n teams.push(team);\n } catch (error) {\n logger.warn('Failed to load team', { file, error: (error as Error).message });\n }\n }\n\n logger.info('All teams loaded', { count: teams.length });\n return teams;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n logger.warn('Teams directory not found', { teamsDir: this.teamsDir });\n return [];\n }\n throw error;\n }\n }\n\n /**\n * List available team names\n */\n async listTeams(): Promise<string[]> {\n try {\n const files = await readdir(this.teamsDir);\n return files\n .filter(f => extname(f) === '.yaml' || extname(f) === '.yml')\n .map(f => basename(f, extname(f)));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return [];\n }\n throw error;\n }\n }\n\n /**\n * Check if a team exists\n */\n async teamExists(teamName: string): Promise<boolean> {\n const teams = await this.listTeams();\n return teams.includes(teamName);\n }\n\n /**\n * Clear cache (useful for testing or after team configuration changes)\n */\n clearCache(): void {\n this.cache.clear();\n logger.debug('Team cache cleared');\n }\n\n /**\n * Validate team configuration\n */\n private validateTeam(team: TeamConfig): void {\n // Required fields\n if (!team.name) {\n throw new TeamValidationError('Team name is required');\n }\n if (!team.displayName) {\n throw new TeamValidationError('Team displayName is required');\n }\n if (!team.description) {\n throw new TeamValidationError('Team description is required');\n }\n\n // Provider configuration is required\n if (!team.provider) {\n throw new TeamValidationError('Team provider configuration is required');\n }\n if (!team.provider.primary) {\n throw new TeamValidationError('Team provider.primary is required');\n }\n\n // Validate provider names (v5.0.7+: accept both aliases and actual names)\n const validProviders = [\n 'claude', 'claude-code', // Claude aliases\n 'gemini', 'gemini-cli', // Gemini aliases\n 'codex', 'openai' // OpenAI aliases\n ];\n\n if (!validProviders.includes(team.provider.primary)) {\n throw new TeamValidationError(\n `Invalid primary provider: ${team.provider.primary}. Must be one of: ${validProviders.join(', ')}`\n );\n }\n\n if (team.provider.fallback && !validProviders.includes(team.provider.fallback)) {\n throw new TeamValidationError(\n `Invalid fallback provider: ${team.provider.fallback}. Must be one of: ${validProviders.join(', ')}`\n );\n }\n\n if (team.provider.fallbackChain) {\n for (const provider of team.provider.fallbackChain) {\n if (!validProviders.includes(provider)) {\n throw new TeamValidationError(\n `Invalid provider in fallbackChain: ${provider}. Must be one of: ${validProviders.join(', ')}`\n );\n }\n }\n }\n\n // Validate arrays if provided\n if (team.sharedAbilities && !Array.isArray(team.sharedAbilities)) {\n throw new TeamValidationError('sharedAbilities must be an array');\n }\n\n if (team.orchestration?.canReadWorkspaces && !Array.isArray(team.orchestration.canReadWorkspaces)) {\n throw new TeamValidationError('orchestration.canReadWorkspaces must be an array');\n }\n\n logger.debug('Team validation passed', { name: team.name });\n }\n}\n","/**\n * Team Configuration Types\n *\n * Defines team-level configuration that agents inherit.\n * Eliminates duplication of provider settings across agent profiles.\n */\n\nimport type { OrchestrationConfig } from './orchestration.js';\n\n/**\n * Team Provider Configuration\n *\n * Defines which AI providers a team uses and in what order.\n */\nexport interface TeamProviderConfig {\n primary: string; // Primary provider (claude, gemini, codex)\n fallback?: string; // Single fallback provider\n fallbackChain?: string[]; // Complete fallback chain (if specified, overrides primary+fallback)\n}\n\n/**\n * Team Orchestration Defaults\n *\n * Default orchestration settings for all agents in the team.\n * Individual agents can override these in their profile.\n */\nexport interface TeamOrchestrationDefaults {\n maxDelegationDepth?: number;\n canWriteToShared?: boolean;\n canReadWorkspaces?: string[];\n}\n\n/**\n * Team Metadata\n *\n * Additional metadata for UI and organizational purposes.\n */\nexport interface TeamMetadata {\n color?: string; // Team color (hex code)\n icon?: string; // Team icon (emoji or string)\n priority?: number; // Team priority (lower = higher priority)\n tags?: string[]; // Team tags\n [key: string]: any; // Additional custom metadata\n}\n\n/**\n * Team Configuration\n *\n * Complete team configuration loaded from .automatosx/teams/*.yaml\n */\nexport interface TeamConfig {\n // Basic info\n name: string;\n displayName: string;\n description: string;\n\n // Provider configuration\n provider: TeamProviderConfig;\n\n // Shared abilities (all team members inherit these)\n sharedAbilities?: string[];\n\n // Orchestration defaults\n orchestration?: TeamOrchestrationDefaults;\n\n // Metadata\n metadata?: TeamMetadata;\n\n // Version tracking\n version?: string;\n}\n\n/**\n * Team validation error\n */\nexport class TeamValidationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'TeamValidationError';\n }\n}\n\n/**\n * Team not found error\n */\nexport class TeamNotFoundError extends Error {\n constructor(teamName: string) {\n super(`Team not found: ${teamName}`);\n this.name = 'TeamNotFoundError';\n }\n}\n","/**\n * MCP Tool: run_agent\n *\n * Executes an AutomatosX agent with a task.\n * Wraps the existing CLI run command logic.\n */\n\nimport type { ToolHandler, RunAgentInput, RunAgentOutput } from '../types.js';\nimport { AgentExecutor } from '../../agents/executor.js';\nimport { ContextManager } from '../../agents/context-manager.js';\nimport { logger } from '../../utils/logger.js';\nimport { formatError } from '../../utils/error-formatter.js';\nimport { validateAgentName, validateStringParameter } from '../utils/validation.js';\n\nexport interface RunAgentDependencies {\n contextManager: ContextManager;\n executorConfig: {\n sessionManager?: any;\n workspaceManager?: any;\n contextManager?: ContextManager;\n profileLoader?: any;\n };\n}\n\nexport function createRunAgentHandler(\n deps: RunAgentDependencies\n): ToolHandler<RunAgentInput, RunAgentOutput> {\n return async (input: RunAgentInput): Promise<RunAgentOutput> => {\n const { agent, task, provider, no_memory } = input;\n\n // Validate inputs to prevent security issues\n validateAgentName(agent);\n validateStringParameter(task, 'task', {\n required: true,\n minLength: 1,\n maxLength: 10000\n });\n\n logger.info('[MCP] run_agent called', { agent, task, provider, no_memory });\n\n try {\n // Build execution context (same as CLI run command)\n const context = await deps.contextManager.createContext(agent, task, {\n provider,\n skipMemory: no_memory\n });\n\n // Execute agent with progress/verbose disabled to prevent stdout pollution\n const executor = new AgentExecutor(deps.executorConfig);\n\n const startTime = Date.now();\n const result = await executor.execute(context, {\n showProgress: false,\n verbose: false\n });\n const latencyMs = Date.now() - startTime;\n\n logger.info('[MCP] run_agent completed', {\n agent,\n latencyMs,\n tokensUsed: result.response.tokensUsed?.total\n });\n\n return {\n content: result.response.content,\n agent: context.agent.name,\n tokens: result.response.tokensUsed\n ? {\n prompt: result.response.tokensUsed.prompt,\n completion: result.response.tokensUsed.completion,\n total: result.response.tokensUsed.total\n }\n : undefined,\n latencyMs\n };\n } catch (error) {\n logger.error('[MCP] run_agent failed', { agent, error });\n throw new Error(formatError(error as Error));\n }\n };\n}\n","/**\n * Agent Executor - Orchestrates agent execution workflow\n *\n * Responsibilities:\n * - Execute agents with progress tracking\n * - Manage execution lifecycle\n * - Provide detailed error reporting\n * - Handle agent-to-agent delegation (v4.7.0+)\n */\n\nimport type { ExecutionContext } from '../types/agent.js';\nimport type { ExecutionResponse } from '../types/provider.js';\nimport type { DelegationRequest, DelegationResult } from '../types/orchestration.js';\nimport type { RetryConfig } from '../types/config.js';\nimport { DelegationError } from '../types/orchestration.js';\nimport type { SessionManager } from '../core/session-manager.js';\nimport type { WorkspaceManager } from '../core/workspace-manager.js';\nimport type { ContextManager } from './context-manager.js';\nimport type { ProfileLoader } from './profile-loader.js';\nimport { DelegationParser } from './delegation-parser.js';\nimport { formatError } from '../utils/error-formatter.js';\nimport { randomUUID } from 'crypto';\nimport { logger } from '../utils/logger.js';\nimport chalk from 'chalk';\nimport ora from 'ora';\n\nexport interface ExecutionOptions {\n verbose?: boolean;\n showProgress?: boolean;\n retry?: RetryConfig;\n timeout?: number;\n signal?: AbortSignal;\n}\n\nexport interface ExecutionResult {\n response: ExecutionResponse;\n duration: number;\n context: ExecutionContext;\n}\n\n/**\n * Agent Executor Configuration\n */\nexport interface AgentExecutorConfig {\n sessionManager?: SessionManager;\n workspaceManager?: WorkspaceManager;\n contextManager?: ContextManager;\n profileLoader?: ProfileLoader;\n /** Default retry configuration (v5.0+) */\n defaultRetryConfig?: RetryConfig;\n}\n\n/**\n * Agent Executor\n *\n * Executes agents with progress tracking and comprehensive error handling.\n * Supports agent-to-agent delegation for multi-agent workflows (v4.7.0+).\n */\nexport class AgentExecutor {\n private sessionManager?: SessionManager;\n private workspaceManager?: WorkspaceManager;\n private contextManager?: ContextManager;\n private profileLoader?: ProfileLoader;\n private delegationParser: DelegationParser;\n\n /**\n * Default retry configuration (v5.0: from config instead of hardcoded)\n */\n private readonly defaultRetryConfig: RetryConfig;\n\n /**\n * Create AgentExecutor with optional delegation support\n *\n * @param config - Optional configuration for delegation features\n */\n constructor(config?: AgentExecutorConfig) {\n this.sessionManager = config?.sessionManager;\n this.workspaceManager = config?.workspaceManager;\n this.contextManager = config?.contextManager;\n this.profileLoader = config?.profileLoader;\n this.delegationParser = new DelegationParser(config?.profileLoader);\n\n // v5.0: Use config value instead of hardcoded constant\n this.defaultRetryConfig = config?.defaultRetryConfig ?? {\n maxAttempts: 3,\n initialDelay: 1000,\n maxDelay: 10000,\n backoffFactor: 2,\n retryableErrors: [\n 'ECONNREFUSED',\n 'ETIMEDOUT',\n 'ENOTFOUND',\n 'rate_limit',\n 'overloaded',\n 'timeout'\n ]\n };\n }\n\n /**\n * Execute an agent with the given context\n */\n async execute(\n context: ExecutionContext,\n options: ExecutionOptions = {}\n ): Promise<ExecutionResult> {\n // If both retry and timeout are enabled\n if (options.retry && options.timeout) {\n return this.executeWithTimeout(context, {\n ...options,\n // Wrap retry logic inside timeout\n retry: options.retry\n });\n }\n\n // If only retry is enabled\n if (options.retry) {\n return this.executeWithRetry(context, options);\n }\n\n // If only timeout is enabled\n if (options.timeout) {\n return this.executeWithTimeout(context, options);\n }\n\n // Otherwise, execute normally\n return this.executeInternal(context, options);\n }\n\n /**\n * Execute with retry logic\n */\n private async executeWithRetry(\n context: ExecutionContext,\n options: ExecutionOptions\n ): Promise<ExecutionResult> {\n const retryConfig = { ...this.defaultRetryConfig, ...options.retry };\n const { maxAttempts, initialDelay, maxDelay, backoffFactor, retryableErrors } = retryConfig;\n const { verbose = false } = options;\n\n let lastError: Error | null = null;\n let attempt = 0;\n\n while (attempt < maxAttempts) {\n attempt++;\n\n try {\n if (verbose && attempt > 1) {\n console.log(chalk.yellow(`\\nRetry attempt ${attempt}/${maxAttempts}...`));\n }\n\n return await this.executeInternal(context, options);\n } catch (error: any) {\n lastError = error;\n\n // Check if error is retryable\n const isRetryable = this.isRetryableError(error, retryableErrors);\n\n if (!isRetryable || attempt >= maxAttempts) {\n throw error;\n }\n\n // Calculate backoff delay\n const delay = Math.min(\n initialDelay * Math.pow(backoffFactor, attempt - 1),\n maxDelay\n );\n\n if (verbose) {\n console.log(chalk.yellow(`Retryable error occurred: ${error.message}`));\n console.log(chalk.gray(`Waiting ${delay}ms before retry...`));\n }\n\n await this.sleep(delay);\n }\n }\n\n // Should not reach here, but throw last error if we do\n throw lastError || new Error('Execution failed after retries');\n }\n\n /**\n * Execute with timeout\n */\n private async executeWithTimeout(\n context: ExecutionContext,\n options: ExecutionOptions\n ): Promise<ExecutionResult> {\n const timeout = options.timeout!;\n const { verbose = false } = options;\n\n // Create an AbortController for cancellation\n const controller = new AbortController();\n const executionOptions = {\n ...options,\n signal: controller.signal,\n timeout: undefined // Remove timeout from nested execution\n };\n\n const executionPromise = options.retry\n ? this.executeWithRetry(context, executionOptions)\n : this.executeInternal(context, executionOptions);\n\n const timeoutPromise = new Promise<ExecutionResult>((_, reject) => {\n setTimeout(() => {\n controller.abort(); // Cancel the execution\n reject(new Error(`Execution timed out after ${timeout}ms`));\n }, timeout);\n });\n\n try {\n return await Promise.race([executionPromise, timeoutPromise]);\n } catch (error) {\n // Ensure abortion on error\n controller.abort();\n throw error;\n }\n }\n\n /**\n * Internal execution (actual implementation)\n */\n private async executeInternal(\n context: ExecutionContext,\n options: ExecutionOptions = {}\n ): Promise<ExecutionResult> {\n const { verbose = false, showProgress = true } = options;\n\n // Display execution info\n if (verbose) {\n this.displayExecutionInfo(context);\n }\n\n // Create progress spinner\n const spinner = showProgress\n ? ora({\n text: 'Executing agent...',\n spinner: 'dots'\n }).start()\n : null;\n\n try {\n // Build prompt\n const prompt = this.buildPrompt(context);\n\n // Update spinner\n if (spinner) {\n spinner.text = `Executing with ${context.provider.name}...`;\n }\n\n // Execute via provider\n const startTime = Date.now();\n const response = await context.provider.execute({\n prompt,\n systemPrompt: context.agent.systemPrompt,\n model: context.agent.model,\n temperature: context.agent.temperature,\n maxTokens: context.agent.maxTokens,\n signal: options.signal // v5.0.7: Pass abort signal for cancellation\n });\n const duration = Date.now() - startTime;\n\n // Check for delegation requests in response (v4.7.2+)\n if (context.orchestration) {\n const delegations = await this.delegationParser.parse(response.content, context.agent.name);\n\n if (delegations.length > 0) {\n if (verbose) {\n console.log(chalk.cyan(`\\n🔗 Found ${delegations.length} delegation request(s)`));\n }\n\n // Update spinner\n if (spinner) {\n spinner.text = 'Processing delegations...';\n }\n\n // Execute all delegations\n const delegationResults = await this.executeDelegations(delegations, context, options);\n\n // Append delegation results to response\n let delegationSummary = '\\n\\n---\\n\\n## Delegation Results\\n\\n';\n delegationResults.forEach((result, index) => {\n delegationSummary += `### Delegation ${index + 1}: ${result.toAgent}\\n\\n`;\n delegationSummary += result.response.content + '\\n\\n';\n });\n\n // Modify response to include delegation results\n response.content += delegationSummary;\n\n if (verbose) {\n console.log(chalk.green(`✅ All delegations completed`));\n }\n }\n }\n\n // Stop spinner\n if (spinner) {\n spinner.succeed('Execution complete');\n }\n\n return {\n response,\n duration,\n context\n };\n\n } catch (error) {\n // Stop spinner with failure\n if (spinner) {\n spinner.fail('Execution failed');\n }\n\n throw this.enhanceError(error as Error, context);\n }\n }\n\n\n /**\n * Execute delegation requests parsed from agent response\n *\n * This is called automatically when an agent's response contains\n * delegation instructions (e.g., \"DELEGATE TO frontend: Create UI\")\n */\n private async executeDelegations(\n delegations: Array<{ toAgent: string; task: string }>,\n context: ExecutionContext,\n options: ExecutionOptions\n ): Promise<DelegationResult[]> {\n const results: DelegationResult[] = [];\n const { verbose = false } = options;\n\n for (const { toAgent, task } of delegations) {\n if (verbose) {\n console.log(chalk.cyan(`\\n📤 Delegating to ${toAgent}...`));\n console.log(chalk.gray(` Task: ${task.substring(0, 100)}${task.length > 100 ? '...' : ''}`));\n }\n\n try {\n const request: DelegationRequest = {\n fromAgent: context.agent.name,\n toAgent,\n task,\n context: {\n sessionId: context.session?.id,\n delegationChain: context.orchestration?.delegationChain || []\n }\n };\n\n const result = await this.delegateToAgent(request);\n results.push(result);\n\n if (verbose) {\n console.log(chalk.green(`✅ Delegation to ${toAgent} completed`));\n }\n } catch (error) {\n const err = error as Error;\n logger.error('Delegation failed', {\n fromAgent: context.agent.name,\n toAgent,\n error: err.message\n });\n\n if (verbose) {\n console.log(chalk.red(`❌ Delegation to ${toAgent} failed: ${err.message}`));\n }\n\n // Store error as failed delegation result\n results.push({\n delegationId: randomUUID(),\n fromAgent: context.agent.name,\n toAgent,\n startTime: new Date(),\n endTime: new Date(),\n duration: 0,\n status: 'failure',\n response: {\n content: `Delegation failed: ${err.message}`,\n model: 'error',\n tokensUsed: { prompt: 0, completion: 0, total: 0 },\n latencyMs: 0,\n finishReason: 'error'\n },\n outputs: {\n files: [],\n memoryIds: [],\n workspacePath: ''\n }\n } as DelegationResult);\n }\n }\n\n return results;\n }\n\n /**\n * Display execution information\n */\n private displayExecutionInfo(context: ExecutionContext): void {\n console.log(chalk.gray('Execution Details:'));\n console.log(chalk.gray(` Agent: ${context.agent.name}`));\n console.log(chalk.gray(` Provider: ${context.provider.name}`));\n console.log(chalk.gray(` Model: ${context.agent.model || 'default'}`));\n console.log(chalk.gray(` Abilities: ${context.agent.abilities.length}`));\n console.log(chalk.gray(` Memory entries: ${context.memory.length}`));\n console.log();\n }\n\n /**\n * Build prompt from execution context\n */\n private buildPrompt(context: ExecutionContext): string {\n let prompt = '';\n\n // Add abilities\n if (context.abilities) {\n prompt += `# Your Abilities\\n\\n${context.abilities}\\n\\n`;\n }\n\n // Add stages workflow (v4.1+ enhanced profiles)\n if (context.agent.stages && context.agent.stages.length > 0) {\n prompt += `# Your Workflow Stages\\n\\n`;\n prompt += `You MUST follow these stages explicitly for every task:\\n\\n`;\n\n context.agent.stages.forEach((stage, i) => {\n prompt += `## Stage ${i + 1}: ${stage.name}\\n\\n`;\n prompt += `${stage.description}\\n\\n`;\n\n if (stage.key_questions && stage.key_questions.length > 0) {\n prompt += `**Key Questions:**\\n`;\n stage.key_questions.forEach(q => {\n prompt += `- ${q}\\n`;\n });\n prompt += `\\n`;\n }\n\n if (stage.outputs && stage.outputs.length > 0) {\n prompt += `**Expected Outputs:**\\n`;\n stage.outputs.forEach(o => {\n prompt += `- ${o}\\n`;\n });\n prompt += `\\n`;\n }\n });\n\n prompt += `**Important:** Announce each stage as you work through it (e.g., \"## Stage 1: requirement_analysis\").\\n\\n`;\n }\n\n // Add memory (relevant context)\n if (context.memory.length > 0) {\n prompt += `# Relevant Context from Memory\\n\\n`;\n context.memory.forEach((entry, i) => {\n const score = entry.score !== undefined ? ` (relevance: ${(entry.score * 100).toFixed(1)}%)` : '';\n prompt += `## Memory ${i + 1}${score}\\n${entry.content}\\n\\n`;\n });\n }\n\n // Add orchestration capabilities (v4.7.0+, Enhanced v4.11.0+)\n if (context.orchestration) {\n prompt += `# Multi-Agent Orchestration Capabilities\\n\\n`;\n prompt += `**IMPORTANT - Task Evaluation Strategy:**\\n`;\n prompt += `1. **First, evaluate if YOU can complete the task** using your abilities and expertise\\n`;\n prompt += `2. **If you CAN do it**, complete the task yourself without delegation\\n`;\n prompt += `3. **If you CANNOT do it** (lacks expertise, tools, or authority), then delegate to a specialized agent\\n`;\n prompt += `4. **Max delegation depth: ${context.orchestration.maxDelegationDepth} levels** - use delegation wisely\\n\\n`;\n prompt += `Only delegate when the task genuinely requires specialized expertise you don't have.\\n\\n`;\n\n // Limit agent list to avoid overly long prompts\n const MAX_AGENTS_TO_SHOW = 10;\n const availableAgents = context.orchestration.availableAgents;\n\n if (availableAgents.length > 0) {\n prompt += `**Available agents for delegation:**\\n`;\n\n const agentsToShow = availableAgents.slice(0, MAX_AGENTS_TO_SHOW);\n agentsToShow.forEach(agent => {\n prompt += `- ${agent}\\n`;\n });\n\n if (availableAgents.length > MAX_AGENTS_TO_SHOW) {\n const remaining = availableAgents.length - MAX_AGENTS_TO_SHOW;\n prompt += `... and ${remaining} more agents\\n`;\n prompt += `\\nNote: You can delegate to ANY agent by name, not just those listed above.\\n`;\n }\n prompt += `\\n`;\n }\n\n if (context.session) {\n prompt += `**Current session:** ${context.session.id}\\n`;\n prompt += `**Session task:** ${context.session.task}\\n`;\n prompt += `**Collaborating agents:** ${context.session.agents.join(', ')}\\n\\n`;\n }\n\n prompt += `**Shared workspace:** ${context.orchestration.sharedWorkspace}\\n\\n`;\n\n if (context.orchestration.delegationChain.length > 0) {\n prompt += `**Delegation chain:** ${context.orchestration.delegationChain.join(' → ')} → YOU\\n`;\n prompt += `**Current depth:** ${context.orchestration.delegationChain.length}/${context.orchestration.maxDelegationDepth}\\n\\n`;\n }\n\n prompt += `**How to delegate:**\\n`;\n prompt += `You can delegate using any of these natural syntaxes:\\n`;\n prompt += `1. \"DELEGATE TO frontend: Create login UI\"\\n`;\n prompt += `2. \"@frontend Create login UI\"\\n`;\n prompt += `3. \"Please ask backend to implement auth API\"\\n`;\n prompt += `4. \"I need frontend to handle the UI\"\\n`;\n prompt += `5. \"請 frontend 建立登入 UI\" (Chinese support)\\n\\n`;\n prompt += `Example: \"@frontend Create a responsive login UI with email and password fields\"\\n\\n`;\n }\n\n // Add task\n prompt += `# Task\\n\\n${context.task}`;\n\n return prompt;\n }\n\n /**\n * Enhance error with context-specific details\n */\n private enhanceError(error: Error, context: ExecutionContext): Error {\n const enhanced = new Error(error.message);\n enhanced.stack = error.stack;\n\n // Add context to error\n (enhanced as any).context = {\n agent: context.agent.name,\n provider: context.provider.name,\n model: context.agent.model,\n task: context.task.substring(0, 100) + (context.task.length > 100 ? '...' : '')\n };\n\n return enhanced;\n }\n\n /**\n * Display execution result\n */\n displayResult(result: ExecutionResult, options: ExecutionOptions = {}): void {\n const { verbose = false } = options;\n\n // Display response\n console.log(chalk.cyan('Response:'));\n console.log(result.response.content);\n console.log();\n\n // Display metrics if verbose\n if (verbose) {\n console.log(chalk.gray('Execution Metrics:'));\n console.log(chalk.gray(` Duration: ${result.duration}ms`));\n console.log(chalk.gray(` Tokens used: ${result.response.tokensUsed.total}`));\n console.log(chalk.gray(` Prompt: ${result.response.tokensUsed.prompt}`));\n console.log(chalk.gray(` Completion: ${result.response.tokensUsed.completion}`));\n console.log();\n }\n }\n\n /**\n * Display execution error with helpful suggestions\n */\n displayError(error: Error, agentName: string, options: ExecutionOptions = {}): void {\n const { verbose = false } = options;\n\n // Use structured error formatter\n console.error(formatError(error, {\n verbose,\n showCode: true,\n showSuggestions: true,\n colors: true\n }));\n }\n\n /**\n * Check if error is retryable\n */\n private isRetryableError(error: any, retryableErrors?: string[]): boolean {\n const patterns = retryableErrors || this.defaultRetryConfig.retryableErrors!;\n\n const errorString = (error.message || error.code || '').toLowerCase();\n\n return patterns.some(pattern =>\n errorString.includes(pattern.toLowerCase())\n );\n }\n\n /**\n * Sleep for specified milliseconds\n */\n private sleep(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n }\n\n /**\n * Delegate a task to another agent\n *\n * This method enables agent-to-agent delegation with proper permission checks,\n * cycle detection, and session management.\n *\n * @param request - Delegation request\n * @returns Delegation result with structured outputs\n * @throws {DelegationError} If delegation fails\n *\n * @example\n * ```typescript\n * const result = await executor.delegateToAgent({\n * fromAgent: 'backend',\n * toAgent: 'frontend',\n * task: 'Create login UI component',\n * context: {\n * sessionId: 'auth-feature-123',\n * requirements: ['Email/password fields'],\n * delegationChain: ['backend']\n * }\n * });\n *\n * console.log('Files created:', result.outputs.files);\n * ```\n */\n async delegateToAgent(request: DelegationRequest): Promise<DelegationResult> {\n // Verify minimum required components for delegation\n // Note: SessionManager and WorkspaceManager are optional (for text-only delegation)\n if (!this.contextManager || !this.profileLoader) {\n throw new DelegationError(\n 'Delegation not configured - missing required managers (contextManager, profileLoader)',\n request.fromAgent,\n request.toAgent,\n 'execution_failed'\n );\n }\n\n const delegationId = randomUUID();\n const startTime = new Date();\n\n logger.info('Delegation started', {\n delegationId,\n fromAgent: request.fromAgent,\n toAgent: request.toAgent,\n task: request.task.substring(0, 100)\n });\n\n try {\n // 1. Load agent profiles\n const fromAgentProfile = await this.profileLoader.loadProfile(request.fromAgent);\n const toAgentProfile = await this.profileLoader.loadProfile(request.toAgent);\n\n // 2. v4.7.8+: All agents can delegate by default\n // Permission check removed - autonomous agent collaboration enabled\n // Safety ensured by:\n // - Cycle detection (below)\n // - Max depth limit (below)\n // - Timeout enforcement\n\n // 3. Cycle detection: check delegation chain\n const delegationChain = request.context?.delegationChain || [];\n if (delegationChain.includes(request.toAgent)) {\n throw new DelegationError(\n `Delegation cycle detected: ${[...delegationChain, request.toAgent].join(' -> ')}`,\n request.fromAgent,\n request.toAgent,\n 'cycle'\n );\n }\n\n // 4. Max depth check\n // delegationChain contains agents that have already delegated\n // If chain = ['A', 'B'], this means A→B has happened, and B is now delegating (3rd delegation)\n // maxDepth = 2 allows up to 2 delegations: A→B (1st), B→C (2nd)\n // So we reject when delegationChain.length >= maxDepth (3rd delegation attempt)\n // v4.11.0+: Default to 2 (agents evaluate capability first, delegate only when needed)\n const maxDepth = fromAgentProfile.orchestration?.maxDelegationDepth ?? 2;\n if (delegationChain.length >= maxDepth) {\n throw new DelegationError(\n `Max delegation depth (${maxDepth}) exceeded. Chain: ${delegationChain.join(' -> ')} (length ${delegationChain.length})`,\n request.fromAgent,\n request.toAgent,\n 'max_depth'\n );\n }\n\n // 5. Session management (optional - only if SessionManager is available)\n let sessionId = request.context?.sessionId;\n let session;\n\n if (this.sessionManager && this.workspaceManager) {\n // Session/Workspace managers available - use full collaboration features\n if (sessionId) {\n // Join existing session\n session = await this.sessionManager.getSession(sessionId);\n if (!session) {\n throw new DelegationError(\n `Session not found: ${sessionId}`,\n request.fromAgent,\n request.toAgent,\n 'execution_failed'\n );\n }\n\n // Validate session is active\n if (session.status !== 'active') {\n throw new DelegationError(\n `Cannot delegate to ${session.status} session: ${sessionId}`,\n request.fromAgent,\n request.toAgent,\n 'execution_failed'\n );\n }\n\n // Add toAgent to session\n await this.sessionManager.addAgent(sessionId, request.toAgent);\n } else {\n // Create new session\n session = await this.sessionManager.createSession(request.task, request.fromAgent);\n sessionId = session.id;\n\n // Add toAgent to session\n await this.sessionManager.addAgent(sessionId, request.toAgent);\n\n // Create session workspace\n await this.workspaceManager.createSessionWorkspace(sessionId);\n }\n } else {\n // Simple text-only delegation mode (no persistent session/workspace)\n logger.debug('Text-only delegation mode (no SessionManager/WorkspaceManager)', {\n fromAgent: request.fromAgent,\n toAgent: request.toAgent\n });\n sessionId = undefined;\n }\n\n // 6. Create execution context for delegated agent\n const context = await this.contextManager.createContext(\n request.toAgent,\n request.task,\n {\n sessionId,\n delegationChain: [...delegationChain, request.fromAgent],\n sharedData: request.context?.sharedData\n }\n );\n\n // 7. Execute delegated agent\n const executionResult = await this.execute(context, {\n timeout: request.options?.timeout,\n verbose: false,\n showProgress: true\n });\n\n // 8. Collect outputs (only if WorkspaceManager is available)\n let files: string[] = [];\n if (this.workspaceManager && sessionId) {\n files = await this.workspaceManager.listSessionFiles(\n sessionId,\n request.toAgent\n );\n }\n\n // 9. Memory IDs collection\n // NOTE: Reserved for future enhancement - automatic memory saving from delegation results\n // Currently returns empty array as memory saving is handled separately via MemoryManager\n const memoryIds: number[] = [];\n\n const endTime = new Date();\n const duration = endTime.getTime() - startTime.getTime();\n\n logger.info('Delegation completed', {\n delegationId,\n fromAgent: request.fromAgent,\n toAgent: request.toAgent,\n duration: `${(duration / 1000).toFixed(1)}s`,\n filesCreated: files.length\n });\n\n // 10. Return structured result\n return {\n delegationId,\n fromAgent: request.fromAgent,\n toAgent: request.toAgent,\n status: 'success',\n response: executionResult.response,\n duration,\n outputs: {\n files,\n memoryIds,\n workspacePath: `sessions/${sessionId}/outputs/${request.toAgent}`\n },\n startTime,\n endTime\n };\n\n } catch (error) {\n const endTime = new Date();\n const duration = endTime.getTime() - startTime.getTime();\n\n // If it's already a DelegationError, re-throw it\n if (error instanceof DelegationError) {\n logger.error('Delegation failed', {\n delegationId,\n fromAgent: request.fromAgent,\n toAgent: request.toAgent,\n reason: error.reason,\n error: error.message\n });\n throw error;\n }\n\n // Otherwise, wrap it in a DelegationError\n const delegationError = new DelegationError(\n `Delegation execution failed: ${(error as Error).message}`,\n request.fromAgent,\n request.toAgent,\n 'execution_failed'\n );\n\n logger.error('Delegation failed', {\n delegationId,\n fromAgent: request.fromAgent,\n toAgent: request.toAgent,\n error: (error as Error).message\n });\n\n throw delegationError;\n }\n }\n}\n","/**\n * Delegation Parser - Natural language delegation parsing\n *\n * Parses natural language delegation requests from agent responses.\n * Supports multiple syntaxes for flexibility while maintaining precision.\n *\n * @module agents/delegation-parser\n * @since v4.7.2\n */\n\nimport { logger } from '../utils/logger.js';\nimport type { ProfileLoader } from './profile-loader.js';\n\n/**\n * Parsed delegation instruction\n */\nexport interface ParsedDelegation {\n /** Target agent name */\n toAgent: string;\n\n /** Task description */\n task: string;\n\n /** Original matched text (for debugging) */\n originalText?: string;\n}\n\n/**\n * Delegation Parser\n *\n * Extracts delegation requests from agent response text using multiple patterns.\n * Supports both agent names and display names (e.g., @oliver or @devops).\n *\n * Supported syntaxes:\n * 1. `DELEGATE TO frontend: Create login UI` (explicit, backward-compatible)\n * 2. `@frontend Create login UI` (concise)\n * 3. `@frontend: Create login UI` (with colon separator)\n * 4. `Please ask frontend to create login UI` (polite request)\n * 5. `I need frontend to handle auth` (need expression)\n * 6. `請 frontend 建立登入 UI` (Chinese support)\n * 7. `委派給 backend:實現 API` (Chinese formal)\n *\n * Performance: < 1ms per parse (regex-based, no LLM calls)\n */\nexport class DelegationParser {\n private profileLoader?: ProfileLoader;\n\n /**\n * Create delegation parser with optional ProfileLoader for display name resolution\n *\n * @param profileLoader - Optional ProfileLoader for resolving display names to agent names\n */\n constructor(profileLoader?: ProfileLoader) {\n this.profileLoader = profileLoader;\n }\n\n /**\n * Parse delegation requests from agent response\n *\n * @param response - Agent response text\n * @param fromAgent - Agent name (for logging)\n * @returns Array of parsed delegations\n *\n * @example\n * ```typescript\n * const parser = new DelegationParser(profileLoader);\n * const delegations = await parser.parse(\n * \"I'll handle the backend. @Oliver Create the login UI with validation.\",\n * \"backend\"\n * );\n * // Returns: [{ toAgent: \"devops\", task: \"Create the login UI with validation.\" }]\n * // (Oliver is display name for devops agent)\n * ```\n */\n async parse(response: string, fromAgent: string): Promise<ParsedDelegation[]> {\n const delegations: Array<ParsedDelegation & { position: number }> = [];\n\n // Pattern 1: DELEGATE TO [agent]: [task]\n // Example: \"DELEGATE TO frontend: Create login UI\"\n // Priority: High (most explicit)\n const pattern1 = /DELEGATE\\s+TO\\s+([a-zA-Z0-9-_]+)\\s*:\\s*(.+?)(?=\\n\\n|(?=\\n\\s*DELEGATE\\s+TO)|(?=\\n\\s*@[\\w-]+)|(?=\\n\\s*請\\s+[\\w-]+)|(?=\\n\\s*委派給)|$)/gis;\n await this.extractMatches(pattern1, response, fromAgent, delegations, 'DELEGATE TO');\n\n // Pattern 2a: @[agent]: [task]\n // Example: \"@frontend: Create login UI\"\n // Priority: High (explicit with colon)\n const pattern2a = /@([a-zA-Z0-9-_]+)\\s*:\\s+(.+?)(?=\\n\\n|(?=\\n\\s*DELEGATE\\s+TO)|(?=\\n\\s*@[\\w-]+)|(?=\\n\\s*請\\s+[\\w-]+)|(?=\\n\\s*委派給)|$)/gis;\n await this.extractMatches(pattern2a, response, fromAgent, delegations, '@agent:');\n\n // Pattern 2b: @[agent] [task] (no colon after agent name)\n // Example: \"@frontend Create login UI\" or \"@coder 請檢視程式碼\"\n // Priority: Medium (less explicit, may have false positives)\n // Match task until: double newline, next delegation pattern, or end\n // Support both English (uppercase start) and Chinese/other languages\n // Supports multi-line tasks (e.g., bullet points)\n const pattern2b = /@([a-zA-Z0-9-_]+)\\s+([A-Z\\u4e00-\\u9fff\\u3400-\\u4dbf][\\s\\S]+?)(?:\\n\\n|(?=\\n\\s*DELEGATE\\s+TO)|(?=\\n\\s*@[\\w-]+)|(?=\\n\\s*請\\s+[\\w-]+)|(?=\\n\\s*委派給)|$)/gs;\n await this.extractMatches(pattern2b, response, fromAgent, delegations, '@agent');\n\n // Pattern 3a: Please/Request/Ask [agent] to [task]\n // Example: \"Please ask frontend to create login UI\"\n // Priority: Medium\n const pattern3a = /(?:please|request|ask)\\s+([a-zA-Z0-9-_]+)\\s+to\\s+(.+?)(?=\\n\\n|(?=\\n\\s*DELEGATE\\s+TO)|(?=\\n\\s*@[\\w-]+)|(?=\\n\\s*請\\s+[\\w-]+)|(?=\\n\\s*委派給)|(?=\\n\\s*(?:please|request|ask))|$)/gis;\n await this.extractMatches(pattern3a, response, fromAgent, delegations, 'please/request/ask');\n\n // Pattern 3b: Please/Request [agent]: [task]\n // Example: \"Request frontend: create login UI\"\n // Priority: Medium\n const pattern3b = /(?:please|request)\\s+([a-zA-Z0-9-_]+)\\s*:\\s*(.+?)(?=\\n\\n|(?=\\n\\s*DELEGATE\\s+TO)|(?=\\n\\s*@[\\w-]+)|(?=\\n\\s*請\\s+[\\w-]+)|(?=\\n\\s*委派給)|(?=\\n\\s*(?:please|request))|$)/gis;\n await this.extractMatches(pattern3b, response, fromAgent, delegations, 'please/request:');\n\n // Pattern 4: I need/require [agent] to [task]\n // Example: \"I need frontend to handle the UI\"\n // Priority: Medium\n const pattern4 = /I\\s+(?:need|require)\\s+([a-zA-Z0-9-_]+)\\s+to\\s+(.+?)(?=\\n\\n|(?=\\n\\s*DELEGATE\\s+TO)|(?=\\n\\s*@[\\w-]+)|(?=\\n\\s*請\\s+[\\w-]+)|(?=\\n\\s*委派給)|(?=\\n\\s*I\\s+(?:need|require))|$)/gis;\n await this.extractMatches(pattern4, response, fromAgent, delegations, 'I need/require');\n\n // Pattern 5a: 請 [agent] [task]\n // Example: \"請 frontend 建立登入 UI\"\n // Priority: High (Chinese explicit)\n const pattern5a = /請\\s+([a-zA-Z0-9-_]+)\\s+([^\\n@請委派]+?)(?=\\n\\n|(?=\\n\\s*DELEGATE\\s+TO)|(?=\\n\\s*@[\\w-]+)|(?=\\n\\s*請\\s+[\\w-]+)|(?=\\n\\s*委派給)|$)/gs;\n await this.extractMatches(pattern5a, response, fromAgent, delegations, '請');\n\n // Pattern 5b: 委派給 [agent]:[task] or 委派給 [agent] [task]\n // Example: \"委派給 backend:實現 API\"\n // Priority: High (Chinese formal)\n const pattern5b = /委派給\\s+([a-zA-Z0-9-_]+)\\s*[::]\\s*(.+?)(?=\\n\\n|(?=\\n\\s*DELEGATE\\s+TO)|(?=\\n\\s*@[\\w-]+)|(?=\\n\\s*請\\s+[\\w-]+)|(?=\\n\\s*委派給)|$)/gs;\n await this.extractMatches(pattern5b, response, fromAgent, delegations, '委派給');\n\n // Sort by position in text (ascending)\n delegations.sort((a, b) => a.position - b.position);\n\n // Remove position field before returning\n const result = delegations.map(({ position, ...rest }) => rest);\n\n logger.info(`Parsed ${delegations.length} delegation(s)`, {\n fromAgent,\n delegations: result.map(d => ({ toAgent: d.toAgent, taskPreview: d.task.substring(0, 50) }))\n });\n\n return result;\n }\n\n /**\n * Extract matches from a regex pattern\n *\n * @private\n */\n private async extractMatches(\n pattern: RegExp,\n response: string,\n fromAgent: string,\n delegations: Array<ParsedDelegation & { position: number }>,\n patternName: string\n ): Promise<void> {\n let match;\n while ((match = pattern.exec(response)) !== null) {\n let toAgent = match[1]?.trim();\n const task = match[2]?.trim();\n\n // Validate extracted values\n if (!toAgent || !task) {\n continue;\n }\n\n // Skip if task is too short (likely false positive)\n if (task.length < 5) {\n continue;\n }\n\n // Skip JSDoc annotations (e.g., @returns, @param)\n if (this.isJSDocAnnotation(response, match.index)) {\n logger.debug('Skipping JSDoc annotation', { toAgent, position: match.index });\n continue;\n }\n\n // Skip if in code block (between ``` or `)\n if (this.isInCodeBlock(response, match.index)) {\n logger.debug('Skipping code block', { toAgent, position: match.index });\n continue;\n }\n\n // Skip if in quoted text (e.g., examples in documentation)\n if (this.isInQuotedText(response, match.index)) {\n logger.debug('Skipping quoted text', { toAgent, position: match.index });\n continue;\n }\n\n // Skip if part of documentation examples\n if (this.isDocumentationExample(response, match.index)) {\n logger.debug('Skipping documentation example', { toAgent, position: match.index });\n continue;\n }\n\n // Resolve agent name (supports display names like \"Oliver\" → \"devops\")\n if (this.profileLoader) {\n try {\n const resolvedName = await this.profileLoader.resolveAgentName(toAgent);\n if (resolvedName !== toAgent) {\n logger.debug('Resolved display name to agent name', {\n displayName: toAgent,\n agentName: resolvedName\n });\n toAgent = resolvedName;\n }\n } catch (error) {\n // Agent not found - skip this delegation\n logger.warn('Agent not found, skipping delegation', {\n agentIdentifier: toAgent,\n fromAgent,\n error: error instanceof Error ? error.message : String(error)\n });\n continue;\n }\n }\n\n // Skip if delegating to self\n if (toAgent.toLowerCase() === fromAgent.toLowerCase()) {\n logger.warn('Skipping self-delegation', { fromAgent, toAgent });\n continue;\n }\n\n // Allow multiple delegations to the same agent (removed deduplication)\n delegations.push({\n toAgent,\n task,\n originalText: match[0],\n position: match.index // Track position in text\n });\n\n logger.debug('Delegation extracted', {\n pattern: patternName,\n fromAgent,\n toAgent,\n taskPreview: task.substring(0, 100),\n originalText: match[0]?.substring(0, 100),\n position: match.index\n });\n }\n }\n\n /**\n * Validate if a string looks like a valid agent name\n *\n * @private\n */\n private isValidAgentName(name: string): boolean {\n // Agent names should be alphanumeric with hyphens/underscores\n // 3-50 characters\n return /^[a-zA-Z0-9-_]{3,50}$/.test(name);\n }\n\n /**\n * Check if position is within a JSDoc comment block\n *\n * @private\n */\n private isJSDocAnnotation(text: string, position: number): boolean {\n // Get context before the match (up to 100 chars)\n const before = text.substring(Math.max(0, position - 100), position);\n\n // Check if preceded by JSDoc comment patterns\n // Common patterns: \" * @\", \"* @\", \" *@\"\n if (/[*\\s]+@\\w+\\s*$/.test(before)) {\n return true;\n }\n\n // Check if within a JSDoc block (/** ... */)\n const beforeFull = text.substring(0, position);\n const lastJSDocStart = beforeFull.lastIndexOf('/**');\n const lastJSDocEnd = beforeFull.lastIndexOf('*/');\n\n if (lastJSDocStart > lastJSDocEnd) {\n // Inside JSDoc block\n return true;\n }\n\n return false;\n }\n\n /**\n * Check if position is within a code block (between ``` or `)\n *\n * @private\n */\n private isInCodeBlock(text: string, position: number): boolean {\n const before = text.substring(0, position);\n\n // Check for triple backticks (```) - count should be even if not in block\n const tripleBacktickCount = (before.match(/```/g) || []).length;\n if (tripleBacktickCount % 2 === 1) {\n return true; // Inside ``` code block\n }\n\n // Check for inline code (`) - more complex due to single backticks\n // Only check if not in triple backtick block\n const lines = before.split('\\n');\n const currentLine = lines[lines.length - 1] || '';\n const singleBacktickCount = (currentLine.match(/`/g) || []).length;\n\n if (singleBacktickCount % 2 === 1) {\n return true; // Inside inline code on current line\n }\n\n return false;\n }\n\n /**\n * Check if position is within quoted text (surrounded by \" or ')\n * This helps avoid parsing delegation examples in documentation.\n *\n * @private\n */\n private isInQuotedText(text: string, position: number): boolean {\n // Get context before and after the match (up to 200 chars each)\n const before = text.substring(Math.max(0, position - 200), position);\n const after = text.substring(position, Math.min(text.length, position + 200));\n\n // Check if the match is enclosed in quotes on the same or adjacent lines\n // Look for opening quote in before text\n const lastDoubleQuote = before.lastIndexOf('\"');\n const lastSingleQuote = before.lastIndexOf(\"'\");\n const lastNewline = before.lastIndexOf('\\n');\n\n // If we found a quote after the last newline, check for closing quote\n if (lastDoubleQuote > lastNewline) {\n const closingDoubleQuote = after.indexOf('\"');\n if (closingDoubleQuote !== -1 && closingDoubleQuote < after.indexOf('\\n\\n')) {\n return true; // Enclosed in double quotes\n }\n }\n\n if (lastSingleQuote > lastNewline) {\n const closingSingleQuote = after.indexOf(\"'\");\n if (closingSingleQuote !== -1 && closingSingleQuote < after.indexOf('\\n\\n')) {\n return true; // Enclosed in single quotes\n }\n }\n\n return false;\n }\n\n /**\n * Check if position is part of documentation examples\n * Detects patterns like:\n * - Lines starting with \"Example:\", \"範例:\", \"Supported syntaxes:\"\n * - Numbered lists with quoted text: 1. \"...\", 2. \"...\", etc.\n * - Lines preceded by \"// \" comments\n * - Test code patterns: it(, test(, describe(, async () =>\n *\n * @private\n */\n private isDocumentationExample(text: string, position: number): boolean {\n // Get context before and after the match\n const before = text.substring(Math.max(0, position - 500), position); // Increased from 300\n const after = text.substring(position, Math.min(text.length, position + 200));\n\n // Split into lines for analysis\n const lines = before.split('\\n');\n const recentLines = lines.slice(-10); // Last 10 lines including current (increased from 5)\n\n // Check for example markers in recent lines\n const exampleMarkers = /(?:example|範例|supported syntaxes|syntaxes|patterns?|用法)[::]/i;\n if (recentLines.some(line => exampleMarkers.test(line))) {\n return true;\n }\n\n // Check if current line is part of a numbered list (with or without quotes)\n // Pattern: \"1. \" or \"2) \" at start of line\n const currentLine = recentLines[recentLines.length - 1] || '';\n if (/^\\s*\\d+[.)]\\s+/.test(currentLine)) {\n // Check if previous lines also have numbering (indicates a list)\n const hasNumberedContext = recentLines.slice(-5).some(line => /^\\s*\\d+[.)]\\s+/.test(line));\n if (hasNumberedContext) {\n return true;\n }\n }\n\n // Check if preceded by comment markers (// or #)\n if (/^\\s*(?:\\/\\/|#)\\s*\\d+[.)]\\s*/.test(currentLine)) {\n return true;\n }\n\n // Check for test code patterns in surrounding context\n // Look for: it(, test(, describe(, expect(, async () =>, function()\n const testCodePatterns = /(?:it|test|describe|expect)\\s*\\(|async\\s*\\(\\)\\s*=>|function\\s*\\(/i;\n if (testCodePatterns.test(before) || testCodePatterns.test(after)) {\n return true;\n }\n\n // Check if the match is part of a string literal in code\n // Look for patterns like: 'text...@agent...' or \"text...@agent...\"\n // where the quote starts before the match and ends after it\n const combinedContext = before.slice(-100) + after.slice(0, 100);\n const stringLiteralPattern = /['\"`][^'\"`]{0,100}@[a-zA-Z0-9-_]+[^'\"`]{0,100}['\"`]/;\n if (stringLiteralPattern.test(combinedContext)) {\n return true;\n }\n\n return false;\n }\n}\n","/**\n * MCP Input Validation Utilities\n *\n * Provides comprehensive validation for MCP tool parameters to prevent\n * security vulnerabilities like path traversal, injection attacks, etc.\n */\n\nimport { resolve, isAbsolute, sep } from 'path';\nimport { McpErrorCode } from '../types.js';\n\n/**\n * Custom error class for validation failures\n */\nexport class ValidationError extends Error {\n constructor(\n message: string,\n public readonly code: McpErrorCode = McpErrorCode.InvalidParams,\n public readonly details?: Record<string, unknown>\n ) {\n super(message);\n this.name = 'ValidationError';\n }\n}\n\n/**\n * Validates a path parameter to prevent path traversal attacks\n *\n * Security checks:\n * - Rejects path traversal patterns (.., ~/)\n * - Rejects absolute paths\n * - Rejects system directories (/etc, /var, /usr, C:\\, etc.)\n * - Ensures path stays within project boundary\n *\n * @param path - Path to validate\n * @param paramName - Parameter name for error messages\n * @param projectRoot - Project root directory (defaults to process.cwd())\n * @throws {ValidationError} If path is invalid or potentially malicious\n */\nexport function validatePathParameter(\n path: string,\n paramName: string,\n projectRoot: string = process.cwd()\n): void {\n // Reject empty paths\n if (!path || path.trim() === '') {\n throw new ValidationError(\n `Invalid ${paramName}: path cannot be empty`,\n McpErrorCode.InvalidParams,\n { path, paramName }\n );\n }\n\n // Dangerous patterns that indicate path traversal attempts\n const dangerousPatterns = [\n '../', // Parent directory traversal (Unix)\n '..\\\\', // Parent directory traversal (Windows)\n '~/', // Home directory (Unix)\n '~\\\\', // Home directory (Windows)\n '/etc/', // System directory (Unix)\n '/var/', // System directory (Unix)\n '/usr/', // System directory (Unix)\n '/root/', // Root home directory (Unix)\n 'C:\\\\', // System drive (Windows)\n 'C:/', // System drive (Windows, alt format)\n 'D:\\\\', // Common data drive (Windows)\n 'D:/', // Common data drive (Windows, alt format)\n ];\n\n // Check for dangerous patterns\n for (const pattern of dangerousPatterns) {\n if (path.includes(pattern)) {\n throw new ValidationError(\n `Invalid ${paramName}: path contains dangerous pattern \"${pattern}\"`,\n McpErrorCode.InvalidParams,\n { path, paramName, pattern }\n );\n }\n }\n\n // Reject absolute paths\n if (isAbsolute(path)) {\n throw new ValidationError(\n `Invalid ${paramName}: absolute paths are not allowed`,\n McpErrorCode.InvalidParams,\n { path, paramName }\n );\n }\n\n // Resolve path relative to project root and check boundary\n try {\n const resolvedPath = resolve(projectRoot, path);\n const normalizedRoot = resolve(projectRoot);\n\n // Ensure resolved path starts with project root\n // This catches traversal attempts that might slip through pattern checks\n if (!resolvedPath.startsWith(normalizedRoot + sep) && resolvedPath !== normalizedRoot) {\n throw new ValidationError(\n `Invalid ${paramName}: path escapes project boundary`,\n McpErrorCode.InvalidParams,\n { path, paramName, projectRoot, resolvedPath }\n );\n }\n } catch (error) {\n // If path resolution fails, it's suspicious\n throw new ValidationError(\n `Invalid ${paramName}: path resolution failed`,\n McpErrorCode.InvalidParams,\n { path, paramName, error: String(error) }\n );\n }\n\n // Check for null bytes (common injection technique)\n if (path.includes('\\0')) {\n throw new ValidationError(\n `Invalid ${paramName}: path contains null byte`,\n McpErrorCode.InvalidParams,\n { path, paramName }\n );\n }\n\n // Check for special characters that might be problematic\n const suspiciousChars = /[<>:|\"]/;\n if (suspiciousChars.test(path)) {\n throw new ValidationError(\n `Invalid ${paramName}: path contains invalid characters`,\n McpErrorCode.InvalidParams,\n { path, paramName }\n );\n }\n}\n\n/**\n * Validates an agent name parameter\n *\n * Agent names should be simple alphanumeric strings with hyphens/underscores.\n * No path separators, no special characters.\n *\n * @param name - Agent name to validate\n * @throws {ValidationError} If name is invalid\n */\nexport function validateAgentName(name: string): void {\n // Reject empty names\n if (!name || name.trim() === '') {\n throw new ValidationError(\n 'Invalid agent name: name cannot be empty',\n McpErrorCode.InvalidParams,\n { name }\n );\n }\n\n // Reject path traversal attempts\n if (name.includes('..') || name.includes('/') || name.includes('\\\\')) {\n throw new ValidationError(\n 'Invalid agent name: path traversal detected',\n McpErrorCode.InvalidParams,\n { name }\n );\n }\n\n // Reject absolute paths\n if (isAbsolute(name)) {\n throw new ValidationError(\n 'Invalid agent name: absolute paths not allowed',\n McpErrorCode.InvalidParams,\n { name }\n );\n }\n\n // Agent names should match pattern: alphanumeric, hyphens, underscores\n const validNamePattern = /^[a-zA-Z0-9_-]+$/;\n if (!validNamePattern.test(name)) {\n throw new ValidationError(\n 'Invalid agent name: must contain only letters, numbers, hyphens, and underscores',\n McpErrorCode.InvalidParams,\n { name }\n );\n }\n\n // Prevent excessively long names (DoS protection)\n if (name.length > 100) {\n throw new ValidationError(\n 'Invalid agent name: name too long (max 100 characters)',\n McpErrorCode.InvalidParams,\n { name, length: name.length }\n );\n }\n}\n\n/**\n * Validates a string input parameter\n *\n * @param value - String to validate\n * @param paramName - Parameter name for error messages\n * @param options - Validation options\n * @throws {ValidationError} If value is invalid\n */\nexport function validateStringParameter(\n value: string,\n paramName: string,\n options: {\n required?: boolean;\n minLength?: number;\n maxLength?: number;\n pattern?: RegExp;\n } = {}\n): void {\n const { required = false, minLength, maxLength, pattern } = options;\n\n // Check required\n if (required && (!value || value.trim() === '')) {\n throw new ValidationError(\n `Invalid ${paramName}: value is required`,\n McpErrorCode.InvalidParams,\n { paramName }\n );\n }\n\n // Skip other checks if optional and empty\n if (!required && (!value || value.trim() === '')) {\n return;\n }\n\n // Check minimum length\n if (minLength !== undefined && value.length < minLength) {\n throw new ValidationError(\n `Invalid ${paramName}: value too short (min ${minLength} characters)`,\n McpErrorCode.InvalidParams,\n { paramName, value, minLength, actualLength: value.length }\n );\n }\n\n // Check maximum length\n if (maxLength !== undefined && value.length > maxLength) {\n throw new ValidationError(\n `Invalid ${paramName}: value too long (max ${maxLength} characters)`,\n McpErrorCode.InvalidParams,\n { paramName, maxLength, actualLength: value.length }\n );\n }\n\n // Check pattern\n if (pattern && !pattern.test(value)) {\n throw new ValidationError(\n `Invalid ${paramName}: value does not match required pattern`,\n McpErrorCode.InvalidParams,\n { paramName, pattern: pattern.source }\n );\n }\n}\n\n/**\n * Validates a number parameter\n *\n * @param value - Number to validate\n * @param paramName - Parameter name for error messages\n * @param options - Validation options\n * @throws {ValidationError} If value is invalid\n */\nexport function validateNumberParameter(\n value: number,\n paramName: string,\n options: {\n min?: number;\n max?: number;\n integer?: boolean;\n } = {}\n): void {\n const { min, max, integer = false } = options;\n\n // Check if it's a number\n if (typeof value !== 'number' || isNaN(value)) {\n throw new ValidationError(\n `Invalid ${paramName}: must be a number`,\n McpErrorCode.InvalidParams,\n { paramName, value }\n );\n }\n\n // Check if integer is required\n if (integer && !Number.isInteger(value)) {\n throw new ValidationError(\n `Invalid ${paramName}: must be an integer`,\n McpErrorCode.InvalidParams,\n { paramName, value }\n );\n }\n\n // Check minimum\n if (min !== undefined && value < min) {\n throw new ValidationError(\n `Invalid ${paramName}: value too small (min ${min})`,\n McpErrorCode.InvalidParams,\n { paramName, value, min }\n );\n }\n\n // Check maximum\n if (max !== undefined && value > max) {\n throw new ValidationError(\n `Invalid ${paramName}: value too large (max ${max})`,\n McpErrorCode.InvalidParams,\n { paramName, value, max }\n );\n }\n}\n","/**\n * MCP Tool: list_agents\n *\n * Lists all available AutomatosX agents.\n * Wraps the existing agent list command logic.\n */\n\nimport type { ToolHandler, ListAgentsOutput } from '../types.js';\nimport { ProfileLoader } from '../../agents/profile-loader.js';\nimport { logger } from '../../utils/logger.js';\n\nexport interface ListAgentsDependencies {\n profileLoader: ProfileLoader;\n}\n\nexport function createListAgentsHandler(\n deps: ListAgentsDependencies\n): ToolHandler<Record<string, never>, ListAgentsOutput> {\n return async (): Promise<ListAgentsOutput> => {\n logger.info('[MCP] list_agents called');\n\n try {\n // Get list of agent names\n const agentNames = await deps.profileLoader.listProfiles();\n\n // Load full profiles to get displayName, role, team\n const profiles = await Promise.all(\n agentNames.map(async (name) => {\n try {\n return await deps.profileLoader.loadProfile(name);\n } catch (error) {\n logger.warn(`Failed to load profile for ${name}`, { error });\n return null;\n }\n })\n );\n\n const result: ListAgentsOutput = {\n agents: profiles\n .filter((profile) => profile !== null)\n .map((profile) => ({\n name: profile!.name,\n displayName: profile!.displayName,\n role: profile!.role,\n team: profile!.team\n }))\n };\n\n logger.info('[MCP] list_agents completed', { count: result.agents.length });\n\n return result;\n } catch (error) {\n logger.error('[MCP] list_agents failed', { error });\n throw new Error(`Failed to list agents: ${(error as Error).message}`);\n }\n };\n}\n","/**\n * MCP Tool: search_memory\n *\n * Searches AutomatosX memory for relevant information.\n * Wraps the existing memory search command logic.\n */\n\nimport type { ToolHandler, SearchMemoryInput, SearchMemoryOutput } from '../types.js';\nimport type { IMemoryManager } from '../../types/memory.js';\nimport { logger } from '../../utils/logger.js';\n\nexport interface SearchMemoryDependencies {\n memoryManager: IMemoryManager;\n}\n\nexport function createSearchMemoryHandler(\n deps: SearchMemoryDependencies\n): ToolHandler<SearchMemoryInput, SearchMemoryOutput> {\n return async (input: SearchMemoryInput): Promise<SearchMemoryOutput> => {\n const { query, limit = 10 } = input;\n\n logger.info('[MCP] search_memory called', { query, limit });\n\n try {\n const results = await deps.memoryManager.search({\n text: query,\n limit\n });\n\n const output: SearchMemoryOutput = {\n results: results.map((result) => ({\n id: result.entry.id,\n similarity: result.similarity,\n content: result.entry.content,\n metadata: {\n agent: result.entry.metadata?.agent as string | undefined,\n timestamp: result.entry.metadata?.timestamp as string | undefined,\n ...(result.entry.metadata || {})\n }\n }))\n };\n\n logger.info('[MCP] search_memory completed', {\n query,\n resultsCount: results.length\n });\n\n return output;\n } catch (error) {\n logger.error('[MCP] search_memory failed', { query, error });\n throw new Error(`Memory search failed: ${(error as Error).message}`);\n }\n };\n}\n","/**\n * MCP Tool: get_status\n *\n * Gets AutomatosX system status and configuration.\n * Wraps the existing status command logic.\n */\n\nimport type { ToolHandler, GetStatusOutput } from '../types.js';\nimport type { IMemoryManager } from '../../types/memory.js';\nimport { SessionManager } from '../../core/session-manager.js';\nimport { Router } from '../../core/router.js';\nimport { createRequire } from 'module';\nimport { logger } from '../../utils/logger.js';\n\nexport interface GetStatusDependencies {\n memoryManager: IMemoryManager;\n sessionManager: SessionManager;\n router: Router;\n}\n\nexport function createGetStatusHandler(\n deps: GetStatusDependencies\n): ToolHandler<Record<string, never>, GetStatusOutput> {\n return async (): Promise<GetStatusOutput> => {\n logger.info('[MCP] get_status called');\n\n try {\n // Get version (try ../../version.json first, then package.json)\n const require = createRequire(import.meta.url);\n let version = 'unknown';\n try {\n const versionData = require('../../../version.json');\n version = versionData.version || 'unknown';\n } catch {\n try {\n const packageJson = require('../../../package.json');\n version = packageJson.version || 'unknown';\n } catch {\n // Keep 'unknown'\n }\n }\n\n // Get memory stats\n const memoryStats = await deps.memoryManager.getStats();\n\n // Get session stats\n const activeSessions = await deps.sessionManager.getActiveSessions();\n const totalSessions = await deps.sessionManager.getTotalSessionCount();\n\n // Get available providers\n const availableProviders = await deps.router.getAvailableProviders();\n const providers = availableProviders.map((p) => p.name);\n\n // Format dbSize as human-readable string\n const formatBytes = (bytes: number): string => {\n if (bytes === 0) return '0 B';\n const k = 1024;\n const sizes = ['B', 'KB', 'MB', 'GB'];\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n return `${Math.round((bytes / Math.pow(k, i)) * 100) / 100} ${sizes[i]}`;\n };\n\n const result: GetStatusOutput = {\n version,\n providers,\n memory: {\n entries: memoryStats.totalEntries,\n dbSize: formatBytes(memoryStats.dbSize)\n },\n sessions: {\n active: activeSessions.length,\n total: totalSessions\n }\n };\n\n logger.info('[MCP] get_status completed', {\n version,\n providersCount: providers.length,\n memoryEntries: memoryStats.totalEntries,\n activeSessions: activeSessions.length\n });\n\n return result;\n } catch (error) {\n logger.error('[MCP] get_status failed', { error });\n throw new Error(`Status check failed: ${(error as Error).message}`);\n }\n };\n}\n","/**\n * MCP Tool: session_create\n *\n * Creates a new multi-agent session.\n */\n\nimport type {\n ToolHandler,\n SessionCreateInput,\n SessionCreateOutput\n} from '../types.js';\nimport { SessionManager } from '../../core/session-manager.js';\nimport { logger } from '../../utils/logger.js';\n\nexport interface SessionCreateDependencies {\n sessionManager: SessionManager;\n}\n\nexport function createSessionCreateHandler(\n deps: SessionCreateDependencies\n): ToolHandler<SessionCreateInput, SessionCreateOutput> {\n return async (input: SessionCreateInput): Promise<SessionCreateOutput> => {\n logger.info('[MCP] session_create called', { input });\n\n try {\n const { name, agent } = input;\n\n // Create new session\n const session = await deps.sessionManager.createSession(name, agent);\n\n const result: SessionCreateOutput = {\n sessionId: session.id,\n name: session.task,\n agent: session.initiator,\n status: session.status,\n createdAt: session.createdAt.toISOString()\n };\n\n logger.info('[MCP] session_create completed', {\n sessionId: session.id,\n status: session.status\n });\n\n return result;\n } catch (error) {\n logger.error('[MCP] session_create failed', { error });\n throw new Error(`Session creation failed: ${(error as Error).message}`);\n }\n };\n}\n","/**\n * MCP Tool: session_list\n *\n * Lists all active sessions.\n */\n\nimport type { ToolHandler, SessionListOutput } from '../types.js';\nimport { SessionManager } from '../../core/session-manager.js';\nimport { logger } from '../../utils/logger.js';\n\nexport interface SessionListDependencies {\n sessionManager: SessionManager;\n}\n\nexport function createSessionListHandler(\n deps: SessionListDependencies\n): ToolHandler<Record<string, never>, SessionListOutput> {\n return async (): Promise<SessionListOutput> => {\n logger.info('[MCP] session_list called');\n\n try {\n // Get all active sessions\n const sessions = await deps.sessionManager.getActiveSessions();\n\n const result: SessionListOutput = {\n sessions: sessions.map((session) => ({\n id: session.id,\n task: session.task,\n initiator: session.initiator,\n status: session.status,\n agents: session.agents,\n createdAt: session.createdAt.toISOString(),\n updatedAt: session.updatedAt.toISOString()\n }))\n };\n\n logger.info('[MCP] session_list completed', {\n count: sessions.length\n });\n\n return result;\n } catch (error) {\n logger.error('[MCP] session_list failed', { error });\n throw new Error(`Session list failed: ${(error as Error).message}`);\n }\n };\n}\n","/**\n * MCP Tool: session_status\n *\n * Gets detailed status of a specific session.\n */\n\nimport type {\n ToolHandler,\n SessionStatusInput,\n SessionStatusOutput\n} from '../types.js';\nimport { SessionManager } from '../../core/session-manager.js';\nimport { logger } from '../../utils/logger.js';\n\nexport interface SessionStatusDependencies {\n sessionManager: SessionManager;\n}\n\nexport function createSessionStatusHandler(\n deps: SessionStatusDependencies\n): ToolHandler<SessionStatusInput, SessionStatusOutput> {\n return async (input: SessionStatusInput): Promise<SessionStatusOutput> => {\n logger.info('[MCP] session_status called', { input });\n\n try {\n const { id } = input;\n\n // Get session details\n const session = await deps.sessionManager.getSession(id);\n\n if (!session) {\n throw new Error(`Session not found: ${id}`);\n }\n\n const result: SessionStatusOutput = {\n id: session.id,\n task: session.task,\n initiator: session.initiator,\n status: session.status,\n agents: session.agents,\n createdAt: session.createdAt.toISOString(),\n updatedAt: session.updatedAt.toISOString(),\n metadata: session.metadata\n };\n\n logger.info('[MCP] session_status completed', {\n sessionId: id,\n status: session.status\n });\n\n return result;\n } catch (error) {\n logger.error('[MCP] session_status failed', { error });\n throw new Error(`Session status failed: ${(error as Error).message}`);\n }\n };\n}\n","/**\n * MCP Tool: session_complete\n *\n * Marks a session as completed.\n */\n\nimport type {\n ToolHandler,\n SessionCompleteInput,\n SessionCompleteOutput\n} from '../types.js';\nimport { SessionManager } from '../../core/session-manager.js';\nimport { logger } from '../../utils/logger.js';\n\nexport interface SessionCompleteDependencies {\n sessionManager: SessionManager;\n}\n\nexport function createSessionCompleteHandler(\n deps: SessionCompleteDependencies\n): ToolHandler<SessionCompleteInput, SessionCompleteOutput> {\n return async (input: SessionCompleteInput): Promise<SessionCompleteOutput> => {\n logger.info('[MCP] session_complete called', { input });\n\n try {\n const { id } = input;\n\n // Complete the session\n await deps.sessionManager.completeSession(id);\n\n // Get updated session to confirm status\n const session = await deps.sessionManager.getSession(id);\n\n if (!session) {\n throw new Error(`Session not found after completion: ${id}`);\n }\n\n const result: SessionCompleteOutput = {\n success: true,\n sessionId: id,\n status: session.status\n };\n\n logger.info('[MCP] session_complete completed', {\n sessionId: id,\n status: session.status\n });\n\n return result;\n } catch (error) {\n logger.error('[MCP] session_complete failed', { error });\n throw new Error(`Session completion failed: ${(error as Error).message}`);\n }\n };\n}\n","/**\n * MCP Tool: session_fail\n *\n * Marks a session as failed with an error reason.\n */\n\nimport type {\n ToolHandler,\n SessionFailInput,\n SessionFailOutput\n} from '../types.js';\nimport { SessionManager } from '../../core/session-manager.js';\nimport { logger } from '../../utils/logger.js';\n\nexport interface SessionFailDependencies {\n sessionManager: SessionManager;\n}\n\nexport function createSessionFailHandler(\n deps: SessionFailDependencies\n): ToolHandler<SessionFailInput, SessionFailOutput> {\n return async (input: SessionFailInput): Promise<SessionFailOutput> => {\n logger.info('[MCP] session_fail called', { input });\n\n try {\n const { id, reason } = input;\n\n // Mark session as failed\n const error = new Error(reason);\n await deps.sessionManager.failSession(id, error);\n\n // Get updated session to confirm status\n const session = await deps.sessionManager.getSession(id);\n\n if (!session) {\n throw new Error(`Session not found after failure: ${id}`);\n }\n\n const result: SessionFailOutput = {\n success: true,\n sessionId: id,\n status: session.status,\n error: reason\n };\n\n logger.info('[MCP] session_fail completed', {\n sessionId: id,\n status: session.status,\n reason\n });\n\n return result;\n } catch (error) {\n logger.error('[MCP] session_fail failed', { error });\n throw new Error(`Session failure marking failed: ${(error as Error).message}`);\n }\n };\n}\n","/**\n * MCP Tool: memory_add\n *\n * Adds a new memory entry to the system.\n */\n\nimport type {\n ToolHandler,\n MemoryAddInput,\n MemoryAddOutput\n} from '../types.js';\nimport type { IMemoryManager } from '../../types/memory.js';\nimport { logger } from '../../utils/logger.js';\n\nexport interface MemoryAddDependencies {\n memoryManager: IMemoryManager;\n}\n\nexport function createMemoryAddHandler(\n deps: MemoryAddDependencies\n): ToolHandler<MemoryAddInput, MemoryAddOutput> {\n return async (input: MemoryAddInput): Promise<MemoryAddOutput> => {\n logger.info('[MCP] memory_add called', { input });\n\n try {\n const { content, metadata = {} } = input;\n\n // Construct MemoryMetadata with required fields\n const enrichedMetadata = {\n type: (metadata.type as 'conversation' | 'code' | 'document' | 'task' | 'other') || 'other',\n source: metadata.agent || 'mcp',\n agentId: metadata.agent,\n timestamp: metadata.timestamp || new Date().toISOString(),\n ...metadata\n };\n\n // Add memory entry (no embedding for FTS5)\n const entry = await deps.memoryManager.add(\n content,\n null,\n enrichedMetadata\n );\n\n const result: MemoryAddOutput = {\n id: entry.id,\n content: entry.content,\n metadata: entry.metadata || {},\n createdAt: entry.createdAt.toISOString()\n };\n\n logger.info('[MCP] memory_add completed', {\n id: entry.id,\n agent: enrichedMetadata.agent\n });\n\n return result;\n } catch (error) {\n logger.error('[MCP] memory_add failed', { error });\n throw new Error(`Memory add failed: ${(error as Error).message}`);\n }\n };\n}\n","/**\n * MCP Tool: memory_list\n *\n * Lists memory entries with optional filtering by agent.\n */\n\nimport type {\n ToolHandler,\n MemoryListInput,\n MemoryListOutput\n} from '../types.js';\nimport { MemoryManager } from '../../core/memory-manager.js';\nimport { logger } from '../../utils/logger.js';\n\nexport interface MemoryListDependencies {\n memoryManager: MemoryManager;\n}\n\nexport function createMemoryListHandler(\n deps: MemoryListDependencies\n): ToolHandler<MemoryListInput, MemoryListOutput> {\n return async (input: MemoryListInput): Promise<MemoryListOutput> => {\n logger.info('[MCP] memory_list called', { input });\n\n try {\n const { agent, limit = 50 } = input;\n\n // Get all entries with optional limit\n const allEntries = await deps.memoryManager.getAll({\n limit: agent ? undefined : limit // Get all if filtering by agent, otherwise limit\n });\n\n // Filter by agent if specified\n const entries = agent\n ? allEntries.filter((entry) => entry.metadata?.agentId === agent).slice(0, limit)\n : allEntries;\n\n const result: MemoryListOutput = {\n entries: entries.map((entry) => ({\n id: entry.id,\n content: entry.content,\n metadata: entry.metadata || {},\n createdAt: entry.createdAt.toISOString()\n })),\n total: entries.length\n };\n\n logger.info('[MCP] memory_list completed', {\n count: entries.length,\n agent\n });\n\n return result;\n } catch (error) {\n logger.error('[MCP] memory_list failed', { error });\n throw new Error(`Memory list failed: ${(error as Error).message}`);\n }\n };\n}\n","/**\n * MCP Tool: memory_delete\n *\n * Deletes a specific memory entry by ID.\n */\n\nimport type {\n ToolHandler,\n MemoryDeleteInput,\n MemoryDeleteOutput\n} from '../types.js';\nimport type { IMemoryManager } from '../../types/memory.js';\nimport { logger } from '../../utils/logger.js';\n\nexport interface MemoryDeleteDependencies {\n memoryManager: IMemoryManager;\n}\n\nexport function createMemoryDeleteHandler(\n deps: MemoryDeleteDependencies\n): ToolHandler<MemoryDeleteInput, MemoryDeleteOutput> {\n return async (input: MemoryDeleteInput): Promise<MemoryDeleteOutput> => {\n logger.info('[MCP] memory_delete called', { input });\n\n try {\n const { id } = input;\n\n // Verify entry exists before deletion\n const entry = await deps.memoryManager.get(id);\n if (!entry) {\n throw new Error(`Memory entry not found: ${id}`);\n }\n\n // Delete the entry\n await deps.memoryManager.delete(id);\n\n const result: MemoryDeleteOutput = {\n success: true,\n id\n };\n\n logger.info('[MCP] memory_delete completed', { id });\n\n return result;\n } catch (error) {\n logger.error('[MCP] memory_delete failed', { error });\n throw new Error(`Memory delete failed: ${(error as Error).message}`);\n }\n };\n}\n","/**\n * MCP Tool: memory_export\n *\n * Exports all memory entries to a JSON file.\n *\n * Security: Restricts file operations to .automatosx/memory/exports directory\n * to prevent sandbox escape and arbitrary file overwrites.\n */\n\nimport type {\n ToolHandler,\n MemoryExportInput,\n MemoryExportOutput\n} from '../types.js';\nimport type { IMemoryManager } from '../../types/memory.js';\nimport type { PathResolver } from '../../core/path-resolver.js';\nimport { logger } from '../../utils/logger.js';\nimport { resolve, basename } from 'path';\nimport { validatePathParameter } from '../utils/validation.js';\n\nexport interface MemoryExportDependencies {\n memoryManager: IMemoryManager;\n pathResolver: PathResolver;\n}\n\n/**\n * Safely resolve export path within designated exports directory\n * @throws Error if path contains traversal (..) or escapes boundary\n */\nfunction resolveExportPath(pathResolver: PathResolver, userPath: string): string {\n // Enhanced validation using comprehensive security checks\n const exportsDir = pathResolver.resolveProjectPath('.automatosx/memory/exports');\n validatePathParameter(userPath, 'export path', exportsDir);\n\n // Extract filename only (ignore directory components)\n const filename = basename(userPath);\n\n // Resolve within .automatosx/memory/exports directory\n const absolutePath = resolve(exportsDir, filename);\n\n // Double-check with PathResolver validation\n if (!pathResolver.validatePath(absolutePath, exportsDir)) {\n throw new Error('Export path must be within .automatosx/memory/exports directory');\n }\n\n return absolutePath;\n}\n\nexport function createMemoryExportHandler(\n deps: MemoryExportDependencies\n): ToolHandler<MemoryExportInput, MemoryExportOutput> {\n return async (input: MemoryExportInput): Promise<MemoryExportOutput> => {\n logger.info('[MCP] memory_export called', { input });\n\n try {\n const { path } = input;\n\n // Safely resolve path with boundary checks\n const absolutePath = resolveExportPath(deps.pathResolver, path);\n\n // Export memories to JSON file\n const exported = await deps.memoryManager.exportToJSON(absolutePath);\n\n const result: MemoryExportOutput = {\n success: true,\n path: absolutePath,\n entries: exported.entriesExported\n };\n\n logger.info('[MCP] memory_export completed', {\n path: absolutePath,\n entries: exported.entriesExported\n });\n\n return result;\n } catch (error) {\n logger.error('[MCP] memory_export failed', { error });\n throw new Error(`Memory export failed: ${(error as Error).message}`);\n }\n };\n}\n","/**\n * MCP Tool: memory_import\n *\n * Imports memory entries from a JSON file.\n *\n * Security: Restricts file operations to .automatosx/memory/exports directory\n * to prevent sandbox escape and arbitrary file reads.\n */\n\nimport type {\n ToolHandler,\n MemoryImportInput,\n MemoryImportOutput\n} from '../types.js';\nimport type { IMemoryManager } from '../../types/memory.js';\nimport type { PathResolver } from '../../core/path-resolver.js';\nimport { logger } from '../../utils/logger.js';\nimport { resolve, basename } from 'path';\nimport { validatePathParameter } from '../utils/validation.js';\n\nexport interface MemoryImportDependencies {\n memoryManager: IMemoryManager;\n pathResolver: PathResolver;\n}\n\n/**\n * Safely resolve import path within designated exports directory\n * @throws Error if path contains traversal (..) or escapes boundary\n */\nfunction resolveImportPath(pathResolver: PathResolver, userPath: string): string {\n // Enhanced validation using comprehensive security checks\n const exportsDir = pathResolver.resolveProjectPath('.automatosx/memory/exports');\n validatePathParameter(userPath, 'import path', exportsDir);\n\n // Extract filename only (ignore directory components)\n const filename = basename(userPath);\n\n // Resolve within .automatosx/memory/exports directory\n const absolutePath = resolve(exportsDir, filename);\n\n // Double-check with PathResolver validation\n if (!pathResolver.validatePath(absolutePath, exportsDir)) {\n throw new Error('Import path must be within .automatosx/memory/exports directory');\n }\n\n return absolutePath;\n}\n\nexport function createMemoryImportHandler(\n deps: MemoryImportDependencies\n): ToolHandler<MemoryImportInput, MemoryImportOutput> {\n return async (input: MemoryImportInput): Promise<MemoryImportOutput> => {\n logger.info('[MCP] memory_import called', { input });\n\n try {\n const { path } = input;\n\n // Safely resolve path with boundary checks\n const absolutePath = resolveImportPath(deps.pathResolver, path);\n\n // Import memories from JSON file\n const imported = await deps.memoryManager.importFromJSON(absolutePath);\n\n const result: MemoryImportOutput = {\n success: true,\n imported: imported.entriesImported,\n skipped: imported.entriesSkipped\n };\n\n logger.info('[MCP] memory_import completed', {\n path: absolutePath,\n imported: imported.entriesImported,\n skipped: imported.entriesSkipped\n });\n\n return result;\n } catch (error) {\n logger.error('[MCP] memory_import failed', { error });\n throw new Error(`Memory import failed: ${(error as Error).message}`);\n }\n };\n}\n","/**\n * MCP Tool: memory_stats\n *\n * Gets detailed memory statistics including breakdown by agent.\n */\n\nimport type { ToolHandler, MemoryStatsOutput } from '../types.js';\nimport { MemoryManager } from '../../core/memory-manager.js';\nimport { logger } from '../../utils/logger.js';\n\nexport interface MemoryStatsDependencies {\n memoryManager: MemoryManager;\n}\n\nexport function createMemoryStatsHandler(\n deps: MemoryStatsDependencies\n): ToolHandler<Record<string, never>, MemoryStatsOutput> {\n return async (): Promise<MemoryStatsOutput> => {\n logger.info('[MCP] memory_stats called');\n\n try {\n // Get overall stats\n const stats = await deps.memoryManager.getStats();\n\n // Get all entries to calculate per-agent breakdown\n const allEntries = await deps.memoryManager.getAll();\n const byAgent: Record<string, number> = {};\n\n for (const entry of allEntries) {\n const agent = (entry.metadata?.agent as string | undefined) || 'unknown';\n byAgent[agent] = (byAgent[agent] || 0) + 1;\n }\n\n // Format dbSize as human-readable string\n const formatBytes = (bytes: number): string => {\n if (bytes === 0) return '0 B';\n const k = 1024;\n const sizes = ['B', 'KB', 'MB', 'GB'];\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n return `${Math.round((bytes / Math.pow(k, i)) * 100) / 100} ${sizes[i]}`;\n };\n\n const result: MemoryStatsOutput = {\n totalEntries: stats.totalEntries,\n dbSize: formatBytes(stats.dbSize),\n byAgent\n };\n\n logger.info('[MCP] memory_stats completed', {\n totalEntries: stats.totalEntries,\n agents: Object.keys(byAgent).length\n });\n\n return result;\n } catch (error) {\n logger.error('[MCP] memory_stats failed', { error });\n throw new Error(`Memory stats failed: ${(error as Error).message}`);\n }\n };\n}\n","/**\n * MCP Tool: memory_clear\n *\n * Clears all memory entries from the database.\n */\n\nimport type { ToolHandler, MemoryClearOutput } from '../types.js';\nimport type { IMemoryManager } from '../../types/memory.js';\nimport { logger } from '../../utils/logger.js';\n\nexport interface MemoryClearDependencies {\n memoryManager: IMemoryManager;\n}\n\nexport function createMemoryClearHandler(\n deps: MemoryClearDependencies\n): ToolHandler<Record<string, never>, MemoryClearOutput> {\n return async (): Promise<MemoryClearOutput> => {\n logger.info('[MCP] memory_clear called');\n\n try {\n // Get count before clearing\n const statsBefore = await deps.memoryManager.getStats();\n const countBefore = statsBefore.totalEntries;\n\n // Clear all memories\n await deps.memoryManager.clear();\n\n const result: MemoryClearOutput = {\n success: true,\n deleted: countBefore\n };\n\n logger.info('[MCP] memory_clear completed', {\n deleted: countBefore\n });\n\n return result;\n } catch (error) {\n logger.error('[MCP] memory_clear failed', { error });\n throw new Error(`Memory clear failed: ${(error as Error).message}`);\n }\n };\n}\n","/**\n * Memory CLI Commands\n */\n\nimport type { CommandModule } from 'yargs';\nimport { resolve } from 'path';\nimport { MemoryManager } from '../../core/memory-manager.js';\nimport chalk from 'chalk';\nimport Table from 'cli-table3';\nimport { printError } from '../../utils/error-formatter.js';\nimport { ProgressIndicator } from '../../utils/progress.js';\nimport { printSuccess } from '../../utils/message-formatter.js';\n\ninterface BaseMemoryArgs {\n db?: string;\n}\n\ninterface SearchArgs extends BaseMemoryArgs {\n query: string; // v4.11.0: Required, no vector file support\n limit?: number;\n threshold?: number;\n type?: string;\n tags?: string;\n output?: 'json' | 'table';\n}\n\ninterface ExportArgs extends BaseMemoryArgs {\n output: string;\n type?: string;\n from?: string;\n to?: string;\n // v4.11.0: includeEmbeddings removed (no embeddings in FTS5 mode)\n}\n\ninterface ImportArgs extends BaseMemoryArgs {\n input: string;\n validate?: boolean;\n batchSize?: number;\n skipDuplicates?: boolean;\n}\n\ninterface StatsArgs extends BaseMemoryArgs {\n output?: 'json' | 'table';\n}\n\ninterface ClearArgs extends BaseMemoryArgs {\n all?: boolean;\n type?: string;\n olderThan?: number;\n confirm?: boolean;\n}\n\nconst DEFAULT_DB_PATH = '.automatosx/memory/memory.db';\n\n/**\n * Get memory manager instance\n *\n * v4.11.0: No embedding provider needed (uses FTS5)\n */\nasync function getMemoryManager(dbPath?: string): Promise<MemoryManager> {\n const path = dbPath || DEFAULT_DB_PATH;\n\n return await MemoryManager.create({\n dbPath: resolve(path),\n maxEntries: 100000,\n autoCleanup: false,\n trackAccess: true\n });\n}\n\n/**\n * Memory search command\n *\n * v4.11.0: FTS5 full-text search only (no vector file support)\n */\nexport const searchCommand: CommandModule = {\n command: 'search <query>',\n describe: 'Search memory entries using full-text search',\n builder: (yargs) => {\n return (yargs as any).positional('query', {\n describe: 'Search query text (required)',\n type: 'string',\n demandOption: true\n })\n .option('limit', {\n alias: 'l',\n describe: 'Maximum number of results',\n type: 'number',\n default: 10\n })\n .option('threshold', {\n alias: 't',\n describe: 'Minimum similarity threshold (0-1)',\n type: 'number',\n default: 0\n })\n .option('type', {\n describe: 'Filter by entry type',\n type: 'string',\n choices: ['conversation', 'code', 'document', 'task', 'other']\n })\n .option('tags', {\n describe: 'Filter by tags (comma-separated)',\n type: 'string'\n })\n .option('output', {\n alias: 'o',\n describe: 'Output format',\n type: 'string',\n choices: ['json', 'table'],\n default: 'table'\n })\n .option('db', {\n describe: 'Database path',\n type: 'string'\n });\n },\n handler: async (argv: any) => {\n try {\n const manager = await getMemoryManager(argv.db);\n\n // Build search query (v4.11.0: FTS5 text search only)\n const searchQuery: any = {\n text: argv.query,\n limit: argv.limit,\n threshold: argv.threshold\n };\n\n // Add filters\n if (argv.type || argv.tags) {\n searchQuery.filters = {};\n if (argv.type) {\n searchQuery.filters.type = argv.type;\n }\n if (argv.tags) {\n searchQuery.filters.tags = argv.tags.split(',').map((t: string) => t.trim());\n }\n }\n\n // Execute search\n const results = await manager.search(searchQuery);\n\n // Output results\n if (argv.output === 'json') {\n console.log(JSON.stringify(results, null, 2));\n } else {\n if (results.length === 0) {\n console.log(chalk.yellow('\\n⚠ No matching entries found.'));\n } else {\n console.log(chalk.bold(`\\n🔍 Found ${results.length} matching entries:\\n`));\n\n const table = new Table({\n head: [\n chalk.cyan('ID'),\n chalk.cyan('Similarity'),\n chalk.cyan('Type'),\n chalk.cyan('Content'),\n chalk.cyan('Created')\n ],\n colWidths: [6, 12, 12, 60, 20],\n wordWrap: true\n });\n\n for (const result of results) {\n const content = result.entry.content.length > 57\n ? `${result.entry.content.substring(0, 57)}...`\n : result.entry.content;\n\n const similarity = `${(result.similarity * 100).toFixed(1)}%`;\n const similarityColored = result.similarity > 0.8 ? chalk.green(similarity) :\n result.similarity > 0.5 ? chalk.yellow(similarity) :\n chalk.red(similarity);\n\n table.push([\n chalk.white(result.entry.id.toString()),\n similarityColored,\n chalk.magenta(result.entry.metadata.type),\n chalk.white(content),\n chalk.gray(new Date(result.entry.createdAt).toLocaleString())\n ]);\n }\n\n console.log(table.toString());\n console.log();\n }\n }\n\n await manager.close();\n } catch (error) {\n printError(error, { verbose: false, showCode: true, showSuggestions: true, colors: true });\n process.exit(1);\n }\n }\n};\n\n/**\n * Memory export command\n */\nexport const exportCommand: CommandModule = {\n command: 'export <output>',\n describe: 'Export memory to JSON file',\n builder: (yargs) => {\n return yargs\n .positional('output', {\n describe: 'Output file path',\n type: 'string',\n demandOption: true\n })\n .option('type', {\n describe: 'Filter by entry type',\n type: 'string',\n choices: ['conversation', 'code', 'document', 'task', 'other']\n })\n .option('from', {\n describe: 'Start date (ISO format)',\n type: 'string'\n })\n .option('to', {\n describe: 'End date (ISO format)',\n type: 'string'\n })\n .option('db', {\n describe: 'Database path',\n type: 'string'\n });\n },\n handler: async (argv: any) => {\n try {\n const manager = await getMemoryManager(argv.db);\n\n // Build export options (v4.11.0: no embeddings in FTS5 mode)\n const exportOptions: any = {\n includeEmbeddings: false,\n pretty: true\n };\n\n // Add filters\n if (argv.type || argv.from || argv.to) {\n exportOptions.filters = {};\n\n if (argv.type) {\n exportOptions.filters.type = argv.type;\n }\n\n if (argv.from || argv.to) {\n exportOptions.filters.dateRange = {};\n if (argv.from) {\n exportOptions.filters.dateRange.from = new Date(argv.from);\n }\n if (argv.to) {\n exportOptions.filters.dateRange.to = new Date(argv.to);\n }\n }\n }\n\n // Execute export with progress\n const progress = new ProgressIndicator();\n progress.start('Exporting memory...');\n\n const result = await manager.exportToJSON(argv.output, exportOptions);\n\n progress.succeed('Export complete');\n\n console.log(`- Entries exported: ${result.entriesExported}`);\n console.log(`- File size: ${(result.sizeBytes / 1024).toFixed(2)} KB`);\n console.log(`- Output: ${result.filePath}`);\n\n await manager.close();\n } catch (error) {\n printError(error, { verbose: false, showCode: true, showSuggestions: true, colors: true });\n process.exit(1);\n }\n }\n};\n\n/**\n * Memory import command\n */\nexport const importCommand: CommandModule = {\n command: 'import <input>',\n describe: 'Import memory from JSON file',\n builder: (yargs) => {\n return yargs\n .positional('input', {\n describe: 'Input file path',\n type: 'string',\n demandOption: true\n })\n .option('validate', {\n describe: 'Validate entries before import',\n type: 'boolean',\n default: true\n })\n .option('batch-size', {\n describe: 'Batch size for processing',\n type: 'number',\n default: 100\n })\n .option('skip-duplicates', {\n describe: 'Skip duplicate entries',\n type: 'boolean',\n default: true\n })\n .option('db', {\n describe: 'Database path',\n type: 'string'\n });\n },\n handler: async (argv: any) => {\n try {\n const manager = await getMemoryManager(argv.db);\n\n const progress = new ProgressIndicator();\n progress.start('Importing memory...');\n\n const result = await manager.importFromJSON(argv.input, {\n skipDuplicates: argv.skipDuplicates,\n batchSize: argv.batchSize,\n validate: argv.validate\n });\n\n progress.succeed('Import complete');\n\n console.log(`- Entries imported: ${result.entriesImported}`);\n console.log(`- Entries skipped: ${result.entriesSkipped}`);\n console.log(`- Entries failed: ${result.entriesFailed}`);\n\n if (result.errors.length > 0) {\n console.log(`\\nErrors (${result.errors.length}):`);\n result.errors.slice(0, 5).forEach(e => {\n console.log(` - ${e.error}`);\n });\n }\n\n await manager.close();\n } catch (error) {\n printError(error, { verbose: false, showCode: true, showSuggestions: true, colors: true });\n process.exit(1);\n }\n }\n};\n\n/**\n * Memory add command\n */\nexport const addCommand: CommandModule = {\n command: 'add <content>',\n describe: 'Add a new memory entry',\n builder: (yargs) => {\n return yargs\n .positional('content', {\n describe: 'Content to store',\n type: 'string',\n demandOption: true\n })\n .option('type', {\n alias: 't',\n describe: 'Entry type',\n type: 'string',\n choices: ['conversation', 'code', 'document', 'task', 'other'],\n default: 'other'\n })\n .option('tags', {\n describe: 'Tags (comma-separated)',\n type: 'string'\n })\n .option('metadata', {\n alias: 'm',\n describe: 'Custom metadata as JSON string',\n type: 'string'\n })\n .option('db', {\n describe: 'Database path',\n type: 'string'\n });\n },\n handler: async (argv: any) => {\n try {\n const manager = await getMemoryManager(argv.db);\n\n // Build metadata\n const metadata: any = {\n type: argv.type,\n source: 'cli',\n timestamp: new Date().toISOString()\n };\n\n if (argv.tags) {\n metadata.tags = argv.tags.split(',').map((t: string) => t.trim());\n }\n\n // Parse custom metadata if provided\n if (argv.metadata) {\n try {\n const customMetadata = JSON.parse(argv.metadata);\n // Merge custom metadata, preserving required fields\n Object.assign(metadata, customMetadata);\n } catch (error) {\n throw new Error(`Invalid metadata JSON: ${(error as Error).message}`);\n }\n }\n\n // For CLI, we don't have an embedding provider by default\n // Use a zero vector as placeholder (will be updated later if needed)\n const embedding = new Array(1536).fill(0);\n\n const entry = await manager.add(argv.content, embedding, metadata);\n\n printSuccess('\\nMemory entry added successfully\\n');\n console.log(`${chalk.bold('ID:')} ${chalk.white(entry.id)}`);\n console.log(`${chalk.bold('Type:')} ${chalk.magenta(entry.metadata.type)}`);\n const content = entry.content.length > 100 ? `${entry.content.substring(0, 100)}...` : entry.content;\n console.log(`${chalk.bold('Content:')} ${chalk.white(content)}`);\n if (entry.metadata.tags && entry.metadata.tags.length > 0) {\n console.log(`${chalk.bold('Tags:')} ${chalk.yellow(entry.metadata.tags.join(', '))}`);\n }\n console.log();\n\n await manager.close();\n } catch (error) {\n printError(error, { verbose: false, showCode: true, showSuggestions: true, colors: true });\n process.exit(1);\n }\n }\n};\n\n/**\n * Memory delete command\n */\nexport const deleteCommand: CommandModule = {\n command: 'delete <id>',\n describe: 'Delete a memory entry by ID',\n builder: (yargs) => {\n return yargs\n .positional('id', {\n describe: 'Entry ID to delete',\n type: 'number',\n demandOption: true\n })\n .option('confirm', {\n alias: 'y',\n describe: 'Skip confirmation prompt',\n type: 'boolean',\n default: false\n })\n .option('db', {\n describe: 'Database path',\n type: 'string'\n });\n },\n handler: async (argv: any) => {\n try {\n const manager = await getMemoryManager(argv.db);\n\n // Get entry to show details\n const entry = await manager.get(argv.id);\n if (!entry) {\n console.error(chalk.red(`\\n✗ Entry not found: ${argv.id}\\n`));\n process.exit(1);\n }\n\n // Show entry details\n console.log(chalk.bold('\\n🗑️ Entry to delete:\\n'));\n console.log(`${chalk.bold('ID:')} ${chalk.white(entry.id)}`);\n console.log(`${chalk.bold('Type:')} ${chalk.magenta(entry.metadata.type)}`);\n const content = entry.content.length > 100 ? `${entry.content.substring(0, 100)}...` : entry.content;\n console.log(`${chalk.bold('Content:')} ${chalk.white(content)}`);\n\n // Confirm deletion (unless --confirm flag is used)\n if (!argv.confirm) {\n const { createInterface } = await import('readline');\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout\n });\n\n const answer = await new Promise<string>((resolve) => {\n rl.question(chalk.yellow('\\nAre you sure you want to delete this entry? (y/N): '), resolve);\n });\n rl.close();\n\n if (answer.toLowerCase() !== 'y' && answer.toLowerCase() !== 'yes') {\n console.log(chalk.gray('\\nDeletion cancelled.\\n'));\n await manager.close();\n return;\n }\n }\n\n await manager.delete(argv.id);\n printSuccess('\\nMemory entry deleted successfully\\n');\n\n await manager.close();\n } catch (error) {\n printError(error, { verbose: false, showCode: true, showSuggestions: true, colors: true });\n process.exit(1);\n }\n }\n};\n\n/**\n * Memory list command\n */\nexport const listCommand: CommandModule = {\n command: 'list',\n describe: 'List all memory entries',\n builder: (yargs) => {\n return (yargs as any).option('type', {\n describe: 'Filter by entry type',\n type: 'string',\n choices: ['conversation', 'code', 'document', 'task', 'other']\n })\n .option('tags', {\n describe: 'Filter by tags (comma-separated)',\n type: 'string'\n })\n .option('limit', {\n alias: 'l',\n describe: 'Maximum number of entries',\n type: 'number',\n default: 50\n })\n .option('offset', {\n describe: 'Number of entries to skip',\n type: 'number',\n default: 0\n })\n .option('order-by', {\n describe: 'Sort by field',\n type: 'string',\n choices: ['created', 'accessed', 'count'],\n default: 'created'\n })\n .option('order', {\n describe: 'Sort direction',\n type: 'string',\n choices: ['asc', 'desc'],\n default: 'desc'\n })\n .option('output', {\n alias: 'o',\n describe: 'Output format',\n type: 'string',\n choices: ['json', 'table'],\n default: 'table'\n })\n .option('db', {\n describe: 'Database path',\n type: 'string'\n });\n },\n handler: async (argv: any) => {\n try {\n const manager = await getMemoryManager(argv.db);\n\n const options: any = {\n limit: argv.limit,\n offset: argv.offset,\n orderBy: argv.orderBy,\n order: argv.order\n };\n\n if (argv.type) {\n options.type = argv.type;\n }\n\n if (argv.tags) {\n options.tags = argv.tags.split(',').map((t: string) => t.trim());\n }\n\n const entries = await manager.getAll(options);\n\n if (argv.output === 'json') {\n console.log(JSON.stringify(entries, null, 2));\n } else {\n if (entries.length === 0) {\n console.log(chalk.yellow('\\n⚠ No entries found.'));\n } else {\n console.log(chalk.bold(`\\n📚 Found ${entries.length} entries:\\n`));\n\n const table = new Table({\n head: [\n chalk.cyan('ID'),\n chalk.cyan('Type'),\n chalk.cyan('Content'),\n chalk.cyan('Tags'),\n chalk.cyan('Created'),\n chalk.cyan('Accessed')\n ],\n colWidths: [6, 12, 50, 20, 20, 10],\n wordWrap: true\n });\n\n for (const entry of entries) {\n const content = entry.content.length > 47\n ? `${entry.content.substring(0, 47)}...`\n : entry.content;\n\n const tags = entry.metadata.tags && entry.metadata.tags.length > 0\n ? entry.metadata.tags.join(', ')\n : chalk.gray('-');\n\n const created = new Date(entry.createdAt).toLocaleString();\n const accessCount = `${entry.accessCount || 0}x`;\n\n table.push([\n chalk.white(entry.id.toString()),\n chalk.magenta(entry.metadata.type),\n chalk.white(content),\n chalk.yellow(tags),\n chalk.gray(created),\n chalk.blue(accessCount)\n ]);\n }\n\n console.log(table.toString());\n\n // Show pagination info\n if (entries.length === argv.limit) {\n console.log(chalk.gray(`\\n💡 Showing ${argv.limit} entries. Use --offset to see more.\\n`));\n }\n }\n }\n\n await manager.close();\n } catch (error) {\n printError(error, { verbose: false, showCode: true, showSuggestions: true, colors: true });\n process.exit(1);\n }\n }\n};\n\n/**\n * Memory stats command\n */\nexport const statsCommand: CommandModule = {\n command: 'stats',\n describe: 'Show memory statistics',\n builder: (yargs) => {\n return (yargs as any).option('output', {\n alias: 'o',\n describe: 'Output format',\n type: 'string',\n choices: ['json', 'table'],\n default: 'table'\n })\n .option('db', {\n describe: 'Database path',\n type: 'string'\n });\n },\n handler: async (argv: any) => {\n try {\n const manager = await getMemoryManager(argv.db);\n const stats = await manager.getStats();\n\n if (argv.output === 'json') {\n console.log(JSON.stringify(stats, null, 2));\n } else {\n console.log('\\nMemory Statistics:');\n console.log(`- Total entries: ${stats.totalEntries}`);\n console.log(`- Database size: ${(stats.dbSize / 1024).toFixed(2)} KB`);\n console.log(`- Index size: ${(stats.indexSize / 1024).toFixed(2)} KB`);\n console.log(`- Memory usage: ${(stats.memoryUsage / 1024 / 1024).toFixed(2)} MB`);\n }\n\n await manager.close();\n } catch (error) {\n console.error('Stats failed:', (error as Error).message);\n process.exit(1);\n }\n }\n};\n\n/**\n * Memory clear command\n */\nexport const clearCommand: CommandModule = {\n command: 'clear',\n describe: 'Clear memory entries',\n builder: (yargs) => {\n return yargs\n .option('all', {\n describe: 'Clear all entries',\n type: 'boolean',\n default: false\n })\n .option('type', {\n describe: 'Clear specific entry type',\n type: 'string',\n choices: ['conversation', 'code', 'document', 'task', 'other']\n })\n .option('older-than', {\n describe: 'Clear entries older than N days',\n type: 'number'\n })\n .option('confirm', {\n alias: 'y',\n describe: 'Skip confirmation prompt',\n type: 'boolean',\n default: false\n })\n .option('db', {\n describe: 'Database path',\n type: 'string'\n })\n .check((argv) => {\n if (!argv.all && !argv.type && !argv.olderThan) {\n throw new Error('Must specify --all, --type, or --older-than');\n }\n return true;\n });\n },\n handler: async (argv: any) => {\n try {\n const manager = await getMemoryManager(argv.db);\n\n // Get stats before clearing\n const statsBefore = await manager.getStats();\n\n // Confirm deletion\n if (!argv.confirm) {\n console.log(`\\nThis will delete entries from the memory database.`);\n console.log(`Current total: ${statsBefore.totalEntries} entries`);\n\n if (argv.all) {\n console.log('Action: Delete ALL entries');\n } else if (argv.type) {\n console.log(`Action: Delete entries of type \"${argv.type}\"`);\n } else if (argv.olderThan) {\n console.log(`Action: Delete entries older than ${argv.olderThan} days`);\n }\n\n console.log('\\nPress Ctrl+C to cancel, or use --confirm to skip this prompt');\n process.exit(0);\n }\n\n // Execute clear operation\n if (argv.all) {\n await manager.clear();\n console.log('\\n✓ All entries cleared');\n } else if (argv.olderThan) {\n const deleted = await manager.cleanup(argv.olderThan);\n console.log(`\\n✓ Deleted ${deleted} entries older than ${argv.olderThan} days`);\n } else {\n // Type-specific deletion (not implemented in current MemoryManager)\n console.error('Type-specific deletion not yet implemented');\n process.exit(1);\n }\n\n const statsAfter = await manager.getStats();\n console.log(`Remaining entries: ${statsAfter.totalEntries}`);\n\n await manager.close();\n } catch (error) {\n console.error('Clear failed:', (error as Error).message);\n process.exit(1);\n }\n }\n};\n\n/**\n * Main memory command\n */\nexport const memoryCommand: CommandModule = {\n command: 'memory <command>',\n describe: 'Memory management commands',\n builder: (yargs) => {\n return yargs\n .command(searchCommand)\n .command(listCommand)\n .command(addCommand)\n .command(deleteCommand)\n .command(exportCommand)\n .command(importCommand)\n .command(statsCommand)\n .command(clearCommand)\n .demandCommand(1, 'You must provide a memory command');\n },\n handler: () => {\n // Will be handled by sub-commands\n }\n};\n","/**\n * Progress Indicator - CLI progress display using ora\n *\n * Provides consistent progress feedback for long-running operations\n */\n\nimport ora, { Ora } from 'ora';\nimport chalk from 'chalk';\n\nexport interface ProgressOptions {\n /**\n * Show spinner animation\n */\n spinner?: boolean;\n\n /**\n * Custom spinner type\n */\n spinnerType?: 'dots' | 'line' | 'arrow' | 'aesthetic';\n\n /**\n * Use colors\n */\n colors?: boolean;\n}\n\n/**\n * Progress Indicator\n *\n * Wrapper around ora for consistent progress display\n */\nexport class ProgressIndicator {\n private spinner: Ora | null = null;\n private options: ProgressOptions;\n\n constructor(options: ProgressOptions = {}) {\n this.options = {\n spinner: true,\n spinnerType: 'dots',\n colors: true,\n ...options\n };\n }\n\n /**\n * Start progress indicator\n */\n start(message: string): void {\n if (!this.options.spinner) {\n console.log(message);\n return;\n }\n\n this.spinner = ora({\n text: message,\n spinner: this.options.spinnerType,\n color: this.options.colors ? 'cyan' : undefined\n }).start();\n }\n\n /**\n * Update progress message\n */\n update(message: string): void {\n if (this.spinner) {\n this.spinner.text = message;\n } else {\n console.log(message);\n }\n }\n\n /**\n * Mark as success and stop\n */\n succeed(message?: string): void {\n if (this.spinner) {\n this.spinner.succeed(message);\n this.spinner = null;\n } else if (message) {\n const text = this.options.colors\n ? chalk.green(`✓ ${message}`)\n : `✓ ${message}`;\n console.log(text);\n }\n }\n\n /**\n * Mark as failure and stop\n */\n fail(message?: string): void {\n if (this.spinner) {\n this.spinner.fail(message);\n this.spinner = null;\n } else if (message) {\n const text = this.options.colors\n ? chalk.red(`✗ ${message}`)\n : `✗ ${message}`;\n console.log(text);\n }\n }\n\n /**\n * Mark as warning and stop\n */\n warn(message?: string): void {\n if (this.spinner) {\n this.spinner.warn(message);\n this.spinner = null;\n } else if (message) {\n const text = this.options.colors\n ? chalk.yellow(`⚠ ${message}`)\n : `⚠ ${message}`;\n console.log(text);\n }\n }\n\n /**\n * Mark as info and stop\n */\n info(message?: string): void {\n if (this.spinner) {\n this.spinner.info(message);\n this.spinner = null;\n } else if (message) {\n const text = this.options.colors\n ? chalk.blue(`ℹ ${message}`)\n : `ℹ ${message}`;\n console.log(text);\n }\n }\n\n /**\n * Stop spinner without status\n */\n stop(): void {\n if (this.spinner) {\n this.spinner.stop();\n this.spinner = null;\n }\n }\n\n /**\n * Clear spinner\n */\n clear(): void {\n if (this.spinner) {\n this.spinner.clear();\n }\n }\n\n /**\n * Check if spinner is active\n */\n isSpinning(): boolean {\n return this.spinner !== null && this.spinner.isSpinning;\n }\n}\n\n/**\n * Create a simple progress indicator\n */\nexport function createProgress(message: string, options?: ProgressOptions): ProgressIndicator {\n const progress = new ProgressIndicator(options);\n progress.start(message);\n return progress;\n}\n","/**\n * Run Command - Execute an agent with a specific task\n */\n\nimport type { CommandModule } from 'yargs';\nimport { ContextManager } from '../../agents/context-manager.js';\nimport { ProfileLoader } from '../../agents/profile-loader.js';\nimport { AbilitiesManager } from '../../agents/abilities-manager.js';\nimport { AgentExecutor } from '../../agents/executor.js';\nimport { StageExecutor } from '../../agents/stage-executor.js';\nimport { AdvancedStageExecutor } from '../../agents/advanced-stage-executor.js';\nimport type { MultiStageExecutionResult } from '../../agents/stage-executor.js';\nimport type { Stage } from '../../types/agent.js';\nimport { AgentNotFoundError } from '../../types/agent.js';\nimport { MemoryManager } from '../../core/memory-manager.js';\nimport { Router } from '../../core/router.js';\nimport { PathResolver } from '../../core/path-resolver.js';\nimport { SessionManager } from '../../core/session-manager.js';\nimport { WorkspaceManager } from '../../core/workspace-manager.js';\nimport { TeamManager } from '../../core/team-manager.js';\nimport { ClaudeProvider } from '../../providers/claude-provider.js';\nimport { GeminiProvider } from '../../providers/gemini-provider.js';\nimport { OpenAIProvider } from '../../providers/openai-provider.js';\nimport { loadConfig } from '../../core/config.js';\nimport { logger } from '../../utils/logger.js';\nimport chalk from 'chalk';\nimport { join } from 'path';\nimport { writeFileSync } from 'fs';\nimport { mkdir } from 'fs/promises';\nimport boxen from 'boxen';\nimport type { ExecutionResult } from '../../agents/executor.js';\nimport { formatOutput, formatForSave } from '../../utils/output-formatter.js';\n\ninterface RunOptions {\n provider?: string;\n model?: string;\n memory?: boolean;\n saveMemory?: boolean;\n verbose?: boolean;\n format?: 'text' | 'json' | 'markdown';\n save?: string;\n timeout?: number;\n session?: string;\n}\n\nexport const runCommand: CommandModule<Record<string, unknown>, RunOptions> = {\n command: 'run <agent> <task>',\n describe: 'Run an agent with a specific task',\n\n builder: (yargs) => {\n return yargs\n .positional('agent', {\n describe: 'Agent name',\n type: 'string',\n demandOption: true\n })\n .positional('task', {\n describe: 'Task to execute',\n type: 'string',\n demandOption: true\n })\n .option('provider', {\n describe: 'Override provider (claude, gemini, openai)',\n type: 'string'\n })\n .option('model', {\n describe: 'Override model',\n type: 'string'\n })\n .option('memory', {\n describe: 'Inject memory',\n type: 'boolean',\n default: true\n })\n .option('save-memory', {\n describe: 'Save result to memory',\n type: 'boolean',\n default: true\n })\n .option('verbose', {\n alias: 'v',\n describe: 'Verbose output',\n type: 'boolean',\n default: false\n })\n .option('format', {\n describe: 'Output format',\n type: 'string',\n choices: ['text', 'json', 'markdown'],\n default: 'text'\n })\n .option('save', {\n describe: 'Save result to file',\n type: 'string'\n })\n .option('timeout', {\n describe: 'Execution timeout in seconds',\n type: 'number'\n })\n .option('session', {\n describe: 'Join existing multi-agent session',\n type: 'string'\n })\n },\n\n handler: async (argv) => {\n // Validate inputs\n if (!argv.agent || typeof argv.agent !== 'string') {\n console.log(chalk.red.bold('\\n❌ Error: Agent name is required\\n'));\n process.exit(1);\n }\n\n if (!argv.task || typeof argv.task !== 'string') {\n console.log(chalk.red.bold('\\n❌ Error: Task is required\\n'));\n process.exit(1);\n }\n\n console.log(chalk.blue.bold(`\\n🤖 AutomatosX - Running ${argv.agent}\\n`));\n\n // Declare resources in outer scope for cleanup\n let memoryManager: MemoryManager | undefined;\n let router: Router | undefined;\n let contextManager: ContextManager | undefined;\n let context: any;\n let resolvedAgentName: string = argv.agent as string; // Default to input, will be resolved later\n\n try {\n // 1. Load configuration\n const config = await loadConfig(process.cwd());\n\n // 2. Detect project directory\n const projectDir = process.cwd(); // Use cwd for now\n\n if (argv.verbose) {\n console.log(chalk.gray(`Project: ${projectDir}`));\n console.log(chalk.gray(`Working directory: ${process.cwd()}`));\n console.log();\n }\n\n // 3. Initialize components\n // v4.10.0+: Initialize TeamManager for team-based configuration\n const teamManager = new TeamManager(\n join(projectDir, '.automatosx', 'teams')\n );\n\n const profileLoader = new ProfileLoader(\n join(projectDir, '.automatosx', 'agents'),\n undefined, // fallbackProfilesDir (uses default)\n teamManager\n );\n\n // Resolve agent name early (supports displayName → actual name)\n // This ensures consistency across session, memory, and all operations\n try {\n resolvedAgentName = await profileLoader.resolveAgentName(argv.agent as string);\n\n if (argv.verbose) {\n if (resolvedAgentName !== argv.agent) {\n console.log(chalk.gray(`Resolved agent: ${argv.agent} → ${resolvedAgentName}`));\n }\n }\n } catch (error) {\n // Agent not found - show helpful suggestions\n console.error(chalk.red.bold(`\\n❌ Agent not found: ${argv.agent}\\n`));\n\n // Try to suggest similar agents\n try {\n const suggestions = await profileLoader.findSimilarAgents(argv.agent as string, 3);\n const closeSuggestions = suggestions.filter(s => s.distance <= 3);\n\n if (closeSuggestions.length > 0) {\n console.log(chalk.yellow('💡 Did you mean:\\n'));\n closeSuggestions.forEach((s, i) => {\n const displayInfo = s.displayName ? `${s.displayName} (${s.name})` : s.name;\n const roleInfo = s.role ? ` - ${s.role}` : '';\n console.log(chalk.cyan(` ${i + 1}. ${displayInfo}${roleInfo}`));\n });\n console.log();\n } else {\n console.log(chalk.gray('Run \"ax agent list\" to see available agents.\\n'));\n }\n } catch {\n console.log(chalk.gray('Run \"ax agent list\" to see available agents.\\n'));\n }\n\n process.exit(1);\n }\n\n const abilitiesManager = new AbilitiesManager(\n join(projectDir, '.automatosx', 'abilities')\n );\n\n // Initialize memory manager (v4.11.0: No embedding provider required)\n // Initialize if either --memory (inject) or --save-memory (save) is enabled\n try {\n if (argv.memory || argv.saveMemory) {\n // v4.11.0: Memory uses FTS5, no embedding provider needed\n memoryManager = await MemoryManager.create({\n dbPath: join(projectDir, '.automatosx', 'memory', 'memory.db')\n });\n\n if (argv.verbose) {\n console.log(chalk.green('✓ Memory system initialized (FTS5 full-text search)\\n'));\n }\n }\n } catch (error) {\n // Graceful fallback if memory initialization fails\n const errMsg = error instanceof Error ? error.message : String(error);\n if (argv.verbose) {\n console.log(chalk.yellow(`⚠ Memory features disabled: ${errMsg}\\n`));\n }\n argv.memory = false;\n argv.saveMemory = false;\n }\n\n const pathResolver = new PathResolver({\n projectDir,\n workingDir: process.cwd(),\n agentWorkspace: join(projectDir, '.automatosx', 'workspaces')\n });\n\n // 4. Initialize providers from config\n const providers = [];\n\n if (config.providers['claude-code']?.enabled) {\n providers.push(new ClaudeProvider({\n name: 'claude-code',\n enabled: true,\n priority: config.providers['claude-code'].priority,\n timeout: config.providers['claude-code'].timeout,\n command: config.providers['claude-code'].command\n }));\n }\n\n if (config.providers['gemini-cli']?.enabled) {\n providers.push(new GeminiProvider({\n name: 'gemini-cli',\n enabled: true,\n priority: config.providers['gemini-cli'].priority,\n timeout: config.providers['gemini-cli'].timeout,\n command: config.providers['gemini-cli'].command\n }));\n }\n\n if (config.providers['openai']?.enabled) {\n providers.push(new OpenAIProvider({\n name: 'openai',\n enabled: true,\n priority: config.providers['openai'].priority,\n timeout: config.providers['openai'].timeout,\n command: config.providers['openai'].command\n }));\n }\n\n router = new Router({\n providers,\n fallbackEnabled: true\n });\n\n // 5. Initialize orchestration managers\n // v4.7.8+: Always initialize for delegation support (all agents can delegate)\n let sessionManager: SessionManager | undefined;\n let workspaceManager: WorkspaceManager | undefined;\n\n // Initialize SessionManager\n sessionManager = new SessionManager({\n persistencePath: join(projectDir, '.automatosx', 'sessions', 'sessions.json')\n });\n await sessionManager.initialize();\n\n // Initialize WorkspaceManager\n workspaceManager = new WorkspaceManager(projectDir);\n await workspaceManager.initialize();\n\n // If session ID provided, verify and join it\n if (argv.session) {\n // Verify session exists\n const session = await sessionManager.getSession(argv.session);\n if (!session) {\n console.log(chalk.red.bold(`\\n✗ Session not found: ${argv.session}\\n`));\n process.exit(1);\n }\n\n // Add this agent to the session (use resolved name for consistency)\n await sessionManager.addAgent(argv.session, resolvedAgentName);\n\n if (argv.verbose) {\n console.log(chalk.cyan(`\\n🔗 Joined session: ${argv.session}`));\n console.log(chalk.gray(`Session task: ${session.task}`));\n console.log(chalk.gray(`Agents in session: ${session.agents.join(', ')}\\n`));\n }\n }\n\n // 6. Create context manager\n contextManager = new ContextManager({\n profileLoader,\n abilitiesManager,\n memoryManager: memoryManager || null,\n router,\n pathResolver,\n sessionManager,\n workspaceManager\n });\n\n // 7. Create execution context\n if (argv.verbose) {\n console.log(chalk.gray('Creating execution context...'));\n console.log();\n }\n\n try {\n context = await contextManager.createContext(\n resolvedAgentName,\n argv.task as string,\n {\n provider: argv.provider,\n model: argv.model,\n skipMemory: !argv.memory,\n sessionId: argv.session\n }\n );\n } catch (error) {\n // Handle agent not found error with suggestions\n if (error instanceof AgentNotFoundError) {\n const agentName = resolvedAgentName;\n console.log(chalk.red.bold(`\\n❌ Agent not found: ${agentName}\\n`));\n\n // Find similar agents (loads profiles silently from cache or disk)\n const suggestions = await profileLoader.findSimilarAgents(agentName, 3);\n\n if (suggestions.length > 0) {\n // Filter to only very similar agents (distance <= 3)\n const closeSuggestions = suggestions.filter(s => s.distance <= 3);\n\n if (closeSuggestions.length > 0) {\n console.log(chalk.yellow('💡 Did you mean:\\n'));\n closeSuggestions.forEach((s, i) => {\n const displayInfo = s.displayName ? `${s.displayName} (${s.name})` : s.name;\n const roleInfo = s.role ? ` - ${s.role}` : '';\n console.log(chalk.cyan(` ${i + 1}. ${displayInfo}${roleInfo}`));\n });\n\n console.log(chalk.gray('\\nTo use one of these agents:'));\n console.log(chalk.gray(` automatosx run ${closeSuggestions[0]!.name} \"${argv.task}\"`));\n console.log();\n } else {\n // No close matches, show all available agents\n console.log(chalk.yellow('💡 Available agents:\\n'));\n const allAgents = await profileLoader.listProfiles();\n allAgents.slice(0, 10).forEach(name => {\n console.log(chalk.cyan(` • ${name}`));\n });\n if (allAgents.length > 10) {\n console.log(chalk.gray(` ... and ${allAgents.length - 10} more`));\n }\n console.log(chalk.gray('\\nRun \"automatosx list agents\" to see all agents\\n'));\n }\n }\n\n process.exit(1);\n }\n // Re-throw other errors\n throw error;\n }\n\n // 8. Detect if agent has multi-stage workflow\n const hasStages = context.agent.stages && context.agent.stages.length > 0;\n\n if (hasStages) {\n const stages = context.agent.stages;\n\n // Check if any stages have advanced features (dependencies, parallel, conditions)\n const hasAdvancedFeatures = stages.filter((s: Stage | undefined): s is Stage => s !== undefined).some((s: Stage) =>\n (s.dependencies && s.dependencies.length > 0) ||\n s.parallel ||\n s.condition\n );\n\n // Use StageExecutor for multi-stage execution\n if (argv.verbose) {\n console.log(chalk.cyan(`\\n📋 Multi-stage execution detected (${context.agent.stages.length} stages)\\n`));\n\n if (hasAdvancedFeatures) {\n console.log(chalk.cyan('✨ Advanced features enabled (dependencies/parallel/conditions)\\n'));\n }\n }\n\n let multiStageResult: MultiStageExecutionResult;\n\n // v5.0.8: Create AbortController for timeout support\n let controller: AbortController | undefined;\n let timeoutId: NodeJS.Timeout | undefined;\n\n if (argv.timeout) {\n const timeoutMs = argv.timeout * 1000;\n controller = new AbortController();\n timeoutId = setTimeout(() => {\n controller!.abort();\n }, timeoutMs);\n }\n\n try {\n if (hasAdvancedFeatures) {\n // Use AdvancedStageExecutor for Phase 3 features\n const advancedExecutor = new AdvancedStageExecutor();\n\n // Show dependency graph if verbose\n if (argv.verbose) {\n console.log(advancedExecutor.visualizeDependencyGraph(stages));\n }\n\n multiStageResult = await advancedExecutor.executeAdvanced(context, {\n verbose: argv.verbose,\n showProgress: !argv.verbose,\n continueOnFailure: false,\n saveToMemory: argv.saveMemory,\n memoryManager: memoryManager || null,\n timeout: argv.timeout ? argv.timeout * 1000 : undefined, // v5.0.8: Pass timeout\n signal: controller?.signal // v5.0.8: Pass abort signal\n });\n\n // Display multi-stage result\n advancedExecutor.displayResult(multiStageResult, argv.verbose || false);\n } else {\n // Use regular StageExecutor for simple multi-stage\n const stageExecutor = new StageExecutor();\n multiStageResult = await stageExecutor.executeStages(context, {\n verbose: argv.verbose,\n showProgress: !argv.verbose,\n continueOnFailure: false,\n saveToMemory: argv.saveMemory,\n memoryManager: memoryManager || null,\n timeout: argv.timeout ? argv.timeout * 1000 : undefined, // v5.0.8: Pass timeout\n signal: controller?.signal // v5.0.8: Pass abort signal\n });\n\n // Display multi-stage result\n stageExecutor.displayResult(multiStageResult, argv.verbose || false);\n }\n } finally {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n }\n\n // Check if execution was aborted (v5.0.8)\n if (controller?.signal.aborted) {\n throw new Error(`Multi-stage execution timeout after ${argv.timeout} seconds`);\n }\n\n // Save multi-stage result to file if requested\n if (argv.save) {\n try {\n const savePath = argv.save;\n const saveDir = join(savePath, '..');\n await mkdir(saveDir, { recursive: true });\n\n let outputData: string;\n if (argv.format === 'json') {\n outputData = JSON.stringify({\n agent: resolvedAgentName,\n task: argv.task,\n stages: multiStageResult.stages.map(s => ({\n name: s.stageName,\n index: s.stageIndex,\n success: s.success,\n output: s.output,\n duration: s.duration,\n tokensUsed: s.tokensUsed,\n model: s.model,\n error: s.error?.message // Include error message if stage failed\n })),\n totalDuration: multiStageResult.totalDuration,\n totalTokens: multiStageResult.totalTokens,\n success: multiStageResult.success,\n failedStage: multiStageResult.failedStage,\n timestamp: new Date().toISOString()\n }, null, 2);\n } else {\n outputData = multiStageResult.finalOutput;\n }\n\n writeFileSync(savePath, outputData, 'utf-8');\n console.log(chalk.green(`\\n✅ Result saved to: ${savePath}\\n`));\n } catch (error) {\n console.log(chalk.yellow(`⚠ Failed to save result: ${(error as Error).message}\\n`));\n }\n }\n\n // Save multi-stage result to memory\n if (argv.saveMemory && memoryManager) {\n try {\n const metadata = {\n type: 'conversation' as const,\n source: 'agent-execution',\n agentId: resolvedAgentName,\n tags: ['agent-execution', resolvedAgentName, 'multi-stage'],\n provider: context.provider.name,\n timestamp: new Date().toISOString()\n };\n\n // FTS5 doesn't need real embeddings - use null\n const embedding = null;\n\n // Build content from multi-stage result\n const content = `Agent: ${resolvedAgentName}\\nTask: ${argv.task}\\n\\nResult: ${multiStageResult.finalOutput}`;\n\n // Save to memory\n await memoryManager.add(content, embedding, metadata);\n\n if (argv.verbose) {\n console.log(chalk.green('✓ Conversation saved to memory'));\n }\n } catch (error) {\n // Don't fail the command if memory save fails\n if (argv.verbose) {\n console.log(chalk.yellow(`⚠ Failed to save to memory: ${(error as Error).message}`));\n }\n }\n }\n\n } else {\n // Use regular AgentExecutor for single-stage execution\n // Configure with orchestration support if managers are available\n const executor = new AgentExecutor({\n sessionManager,\n workspaceManager,\n contextManager,\n profileLoader\n });\n let result: ExecutionResult;\n\n if (argv.timeout) {\n const timeoutMs = argv.timeout * 1000;\n const controller = new AbortController();\n\n const timeoutId = setTimeout(() => {\n controller.abort();\n }, timeoutMs);\n\n try {\n result = await executor.execute(context, {\n verbose: argv.verbose,\n showProgress: !argv.verbose,\n signal: controller.signal\n });\n } finally {\n clearTimeout(timeoutId);\n }\n\n // Check if execution was aborted\n if (controller.signal.aborted) {\n throw new Error(`Execution timeout after ${argv.timeout} seconds`);\n }\n } else {\n result = await executor.execute(context, {\n verbose: argv.verbose,\n showProgress: !argv.verbose\n });\n }\n\n // 9. Format and display result\n const formattedOutput = formatOutput(result, argv.format || 'text', argv.verbose || false);\n console.log(formattedOutput);\n\n // 10. Save result to file\n if (argv.save) {\n try {\n const savePath = argv.save;\n const saveDir = join(savePath, '..');\n await mkdir(saveDir, { recursive: true });\n\n const outputData = formatForSave(result, argv.format || 'text', {\n agent: resolvedAgentName,\n task: argv.task\n });\n\n writeFileSync(savePath, outputData, 'utf-8');\n console.log(chalk.green(`\\n✅ Result saved to: ${savePath}\\n`));\n } catch (error) {\n console.log(chalk.yellow(`⚠ Failed to save result: ${(error as Error).message}\\n`));\n }\n }\n\n // 11. Save result to memory\n if (argv.saveMemory && memoryManager) {\n try {\n const metadata = {\n type: 'conversation' as const,\n source: 'agent-execution',\n agentId: resolvedAgentName,\n tags: ['agent-execution', resolvedAgentName],\n provider: context.provider.name,\n timestamp: new Date().toISOString()\n };\n\n // FTS5 doesn't need real embeddings - use null\n const embedding = null;\n\n // Build content from execution result\n const content = `Agent: ${resolvedAgentName}\\nTask: ${argv.task}\\n\\nResponse: ${result.response.content}`;\n\n // Save to memory\n await memoryManager.add(content, embedding, metadata);\n\n if (argv.verbose) {\n console.log(chalk.green('✓ Conversation saved to memory'));\n }\n } catch (error) {\n // Don't fail the command if memory save fails\n if (argv.verbose) {\n console.log(chalk.yellow(`⚠ Failed to save to memory: ${(error as Error).message}`));\n }\n }\n }\n }\n\n // 12. Cleanup resources\n await contextManager.cleanup(context);\n\n // Clean up memory manager (close database connections)\n if (memoryManager) {\n await memoryManager.close();\n }\n\n // Clean up router (stop health checks)\n if (router) {\n router.destroy();\n }\n\n // Ensure event loop completes all pending operations\n await new Promise(resolve => setImmediate(resolve));\n\n console.log(chalk.green.bold('✅ Complete\\n'));\n\n // Explicitly exit process to prevent hanging\n // (Required for integration tests and clean process termination)\n process.exit(0);\n\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n const executor = new AgentExecutor();\n\n // Display error with helpful suggestions\n executor.displayError(err, resolvedAgentName, { verbose: argv.verbose });\n\n // Log error\n logger.error('Agent execution failed', {\n error: err.message,\n agent: resolvedAgentName,\n task: argv.task,\n provider: argv.provider,\n stack: err.stack\n });\n\n // Cleanup resources even on error\n try {\n if (memoryManager) {\n await memoryManager.close();\n }\n if (router) {\n router.destroy();\n }\n // Clean up context (workspace, temp files)\n if (contextManager && context) {\n await contextManager.cleanup(context).catch(cleanupErr => {\n const errMsg = cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr);\n logger.debug('Context cleanup error', { error: errMsg });\n });\n }\n // Ensure event loop completes all pending operations\n await new Promise(resolve => setImmediate(resolve));\n } catch (cleanupError) {\n const errMsg = cleanupError instanceof Error ? cleanupError.message : String(cleanupError);\n logger.debug('Cleanup error ignored', { error: errMsg });\n }\n\n process.exit(1);\n }\n }\n};\n","/**\n * Stage Executor - Multi-Stage Agent Execution\n *\n * Executes agents with multiple stages (workflow steps) in sequence.\n * Each stage builds on the outputs of previous stages.\n *\n * Features:\n * - Sequential stage execution\n * - Context accumulation (previous outputs fed to next stage)\n * - Per-stage configuration (model, temperature)\n * - Progress tracking\n * - Stage failure handling\n * - Memory persistence between stages\n */\n\nimport type { ExecutionContext, Stage } from '../types/agent.js';\nimport type { ExecutionResponse } from '../types/provider.js';\nimport type { IMemoryManager } from '../types/memory.js';\nimport { logger } from '../utils/logger.js';\nimport chalk from 'chalk';\nimport ora from 'ora';\n\n/**\n * Result of a single stage execution\n */\nexport interface StageExecutionResult {\n stageName: string;\n stageIndex: number;\n output: string;\n duration: number;\n tokensUsed: number;\n success: boolean;\n error?: Error;\n model?: string;\n}\n\n/**\n * Complete multi-stage execution result\n */\nexport interface MultiStageExecutionResult {\n stages: StageExecutionResult[];\n totalDuration: number;\n totalTokens: number;\n success: boolean;\n failedStage?: number;\n finalOutput: string;\n}\n\n/**\n * Options for stage execution\n */\nexport interface StageExecutionOptions {\n verbose?: boolean;\n showProgress?: boolean;\n continueOnFailure?: boolean;\n saveToMemory?: boolean;\n memoryManager?: IMemoryManager | null;\n timeout?: number; // v5.0.8: Execution timeout in milliseconds\n signal?: AbortSignal; // v5.0.8: Abort signal for cancellation\n retry?: boolean; // v5.0.8: Enable retry on failure\n}\n\n/**\n * Stage Executor\n *\n * Executes agents with multi-stage workflows where each stage:\n * 1. Receives context from previous stages\n * 2. Executes with stage-specific configuration\n * 3. Produces output for next stages\n * 4. Can optionally save to memory\n */\nexport class StageExecutor {\n /**\n * Execute all stages of an agent workflow\n */\n async executeStages(\n context: ExecutionContext,\n options: StageExecutionOptions = {}\n ): Promise<MultiStageExecutionResult> {\n const {\n verbose = false,\n showProgress = true,\n continueOnFailure = false,\n saveToMemory = false,\n memoryManager = null\n } = options;\n\n const stages = context.agent.stages || [];\n\n if (stages.length === 0) {\n throw new Error('Agent has no stages defined');\n }\n\n logger.info('Starting multi-stage execution', {\n agent: context.agent.name,\n stageCount: stages.length\n });\n\n const stageResults: StageExecutionResult[] = [];\n const previousOutputs: string[] = [];\n const startTime = Date.now();\n\n // Execute each stage sequentially\n for (let i = 0; i < stages.length; i++) {\n const stage = stages[i];\n\n // TypeScript strict mode: ensure stage exists\n if (!stage) {\n logger.error('Stage is undefined', { index: i });\n continue;\n }\n\n if (verbose) {\n console.log(chalk.cyan(`\\n${'='.repeat(60)}`));\n console.log(chalk.cyan(`Stage ${i + 1}/${stages.length}: ${stage.name}`));\n console.log(chalk.cyan(`${'='.repeat(60)}\\n`));\n console.log(chalk.gray(`Description: ${stage.description}`));\n console.log();\n }\n\n try {\n // Execute stage\n const result = await this.executeStage(\n stage,\n i,\n context,\n previousOutputs,\n { verbose, showProgress, signal: options.signal }\n );\n\n stageResults.push(result);\n\n // Save output for next stages\n if (result.success) {\n previousOutputs.push(result.output);\n\n // Optionally save to memory\n if (saveToMemory && memoryManager) {\n await this.saveStageToMemory(\n context.agent.name,\n stage,\n result,\n memoryManager\n );\n }\n } else {\n // Stage failed\n if (!continueOnFailure) {\n logger.warn('Stage failed, stopping execution', {\n stage: stage.name,\n index: i\n });\n break;\n } else {\n logger.warn('Stage failed, continuing to next stage', {\n stage: stage.name,\n index: i\n });\n }\n }\n\n } catch (error) {\n const failedResult: StageExecutionResult = {\n stageName: stage.name,\n stageIndex: i,\n output: '',\n duration: 0,\n tokensUsed: 0,\n success: false,\n error: error as Error\n };\n\n stageResults.push(failedResult);\n\n if (!continueOnFailure) {\n logger.error('Stage execution failed, stopping', {\n stage: stage.name,\n error: (error as Error).message\n });\n break;\n }\n }\n }\n\n const totalDuration = Date.now() - startTime;\n const totalTokens = stageResults.reduce((sum, r) => sum + r.tokensUsed, 0);\n const success = stageResults.every(r => r.success);\n const failedStageIndex = stageResults.findIndex(r => !r.success);\n const finalOutput = this.assembleFinalOutput(stageResults);\n\n const result: MultiStageExecutionResult = {\n stages: stageResults,\n totalDuration,\n totalTokens,\n success,\n failedStage: failedStageIndex >= 0 ? failedStageIndex : undefined,\n finalOutput\n };\n\n logger.info('Multi-stage execution complete', {\n totalStages: stages.length,\n successfulStages: stageResults.filter(r => r.success).length,\n totalDuration,\n totalTokens,\n success\n });\n\n return result;\n }\n\n /**\n * Execute a single stage\n */\n private async executeStage(\n stage: Stage,\n index: number,\n context: ExecutionContext,\n previousOutputs: string[],\n options: { verbose?: boolean; showProgress?: boolean; signal?: AbortSignal }\n ): Promise<StageExecutionResult> {\n const { verbose = false, showProgress = true } = options;\n\n // Build stage-specific prompt\n const prompt = this.buildStagePrompt(\n stage,\n context.task,\n previousOutputs,\n context.agent.stages || []\n );\n\n // Create spinner\n const spinner = showProgress\n ? ora({\n text: `Executing stage: ${stage.name}`,\n spinner: 'dots'\n }).start()\n : null;\n\n try {\n const startTime = Date.now();\n\n // Execute via provider with stage-specific config\n const response = await context.provider.execute({\n prompt,\n systemPrompt: context.agent.systemPrompt,\n model: stage.model || context.agent.model,\n temperature: stage.temperature ?? context.agent.temperature,\n maxTokens: context.agent.maxTokens,\n signal: options.signal // v5.0.8: Pass abort signal for timeout cancellation\n });\n\n const duration = Date.now() - startTime;\n\n // Stop spinner\n if (spinner) {\n spinner.succeed(`Stage complete: ${stage.name} (${duration}ms)`);\n }\n\n if (verbose) {\n console.log(chalk.green('\\n✓ Stage output:'));\n console.log(response.content);\n const tokensUsed = response.tokensUsed?.total ?? 0;\n console.log(chalk.gray(`\\nTokens used: ${tokensUsed}`));\n console.log(chalk.gray(`Duration: ${duration}ms`));\n }\n\n return {\n stageName: stage.name,\n stageIndex: index,\n output: response.content,\n duration,\n tokensUsed: response.tokensUsed?.total ?? 0,\n success: true,\n model: stage.model || context.agent.model\n };\n\n } catch (error) {\n // Stop spinner with failure\n if (spinner) {\n spinner.fail(`Stage failed: ${stage.name}`);\n }\n\n if (verbose) {\n console.error(chalk.red(`\\n✗ Stage error: ${(error as Error).message}`));\n }\n\n throw error;\n }\n }\n\n /**\n * Build prompt for a specific stage\n */\n private buildStagePrompt(\n stage: Stage,\n originalTask: string,\n previousOutputs: string[],\n allStages: Stage[]\n ): string {\n let prompt = '';\n\n // Add stage context\n prompt += `# Current Stage: ${stage.name}\\n\\n`;\n prompt += `${stage.description}\\n\\n`;\n\n // Add key questions if available\n if (stage.key_questions && stage.key_questions.length > 0) {\n prompt += `## Key Questions to Address\\n\\n`;\n stage.key_questions.forEach(q => {\n prompt += `- ${q}\\n`;\n });\n prompt += `\\n`;\n }\n\n // Add expected outputs if available\n if (stage.outputs && stage.outputs.length > 0) {\n prompt += `## Expected Outputs\\n\\n`;\n stage.outputs.forEach(o => {\n prompt += `- ${o}\\n`;\n });\n prompt += `\\n`;\n }\n\n // Add original task\n prompt += `## Original Task\\n\\n${originalTask}\\n\\n`;\n\n // Add previous stage outputs (context accumulation)\n if (previousOutputs.length > 0) {\n prompt += `## Context from Previous Stages\\n\\n`;\n previousOutputs.forEach((output, i) => {\n const prevStage = allStages[i];\n if (prevStage) {\n prompt += `### Stage ${i + 1}: ${prevStage.name}\\n\\n`;\n } else {\n prompt += `### Stage ${i + 1}: Previous Stage\\n\\n`;\n }\n prompt += `${output}\\n\\n`;\n });\n }\n\n // Add focus instruction\n prompt += `## Your Task\\n\\n`;\n prompt += `Focus on completing **${stage.name}** based on the context above. `;\n prompt += `Build on the previous stages' work and produce the expected outputs for this stage.\\n`;\n\n return prompt;\n }\n\n /**\n * Assemble final output from all stages\n */\n protected assembleFinalOutput(results: StageExecutionResult[]): string {\n if (results.length === 0) {\n return '';\n }\n\n // If only one stage, return its output or error\n if (results.length === 1) {\n const result = results[0];\n if (!result) return '';\n\n if (result.success) {\n return result.output;\n } else {\n // For failed single stage, return error information\n return `# Execution Failed\\n\\n` +\n `**Stage**: ${result.stageName}\\n\\n` +\n `**Error**: ${result.error?.message || 'Unknown error'}\\n\\n` +\n `**Duration**: ${result.duration}ms\\n`;\n }\n }\n\n // Multiple stages: combine outputs\n let output = '# Multi-Stage Execution Results\\n\\n';\n\n results.forEach((result, i) => {\n const status = result.success ? '✓' : '✗';\n output += `## Stage ${i + 1}: ${result.stageName} ${status}\\n\\n`;\n\n if (result.success) {\n output += `${result.output}\\n\\n`;\n } else {\n output += `**Failed:** ${result.error?.message || 'Unknown error'}\\n\\n`;\n }\n\n output += `---\\n\\n`;\n });\n\n return output;\n }\n\n /**\n * Save stage result to memory\n *\n * v4.11.0: No embedding required (uses FTS5)\n */\n protected async saveStageToMemory(\n agentName: string,\n stage: Stage,\n result: StageExecutionResult,\n memoryManager: IMemoryManager\n ): Promise<void> {\n try {\n const memoryContent = `[${agentName}] Stage: ${stage.name}\\n\\n${result.output}`;\n\n // v4.11.0: Save directly without embedding (uses FTS5)\n await memoryManager.add(memoryContent, null, {\n type: 'task',\n source: agentName,\n agentId: agentName,\n stage: stage.name,\n stageIndex: result.stageIndex,\n timestamp: new Date().toISOString(),\n tokensUsed: result.tokensUsed,\n duration: result.duration\n });\n\n logger.info('Stage result saved to memory', {\n agent: agentName,\n stage: stage.name,\n contentLength: memoryContent.length,\n searchMethod: 'FTS5'\n });\n\n } catch (error) {\n logger.warn('Failed to save stage to memory', {\n stage: stage.name,\n error: (error as Error).message\n });\n // Don't throw - memory save is optional\n }\n }\n\n /**\n * Display multi-stage execution result\n */\n displayResult(result: MultiStageExecutionResult, verbose: boolean = false): void {\n console.log(chalk.cyan('\\n' + '='.repeat(60)));\n console.log(chalk.cyan('Multi-Stage Execution Summary'));\n console.log(chalk.cyan('='.repeat(60)));\n\n // Summary stats\n const successCount = result.stages.filter(s => s.success).length;\n const statusColor = result.success ? chalk.green : chalk.red;\n const statusIcon = result.success ? '✓' : '✗';\n\n console.log(statusColor(`\\n${statusIcon} Status: ${result.success ? 'Success' : 'Failed'}`));\n console.log(chalk.gray(`Stages completed: ${successCount}/${result.stages.length}`));\n console.log(chalk.gray(`Total duration: ${result.totalDuration}ms`));\n console.log(chalk.gray(`Total tokens: ${result.totalTokens}`));\n\n if (result.failedStage !== undefined) {\n const failedStageResult = result.stages[result.failedStage];\n if (failedStageResult) {\n console.log(chalk.red(`Failed at stage ${result.failedStage + 1}: ${failedStageResult.stageName}`));\n }\n }\n\n // Stage details\n if (verbose) {\n console.log(chalk.cyan('\\n' + '-'.repeat(60)));\n console.log(chalk.cyan('Stage Details'));\n console.log(chalk.cyan('-'.repeat(60)));\n\n result.stages.forEach((stage, i) => {\n const icon = stage.success ? '✓' : '✗';\n const color = stage.success ? chalk.green : chalk.red;\n\n console.log(color(`\\n${icon} Stage ${i + 1}: ${stage.stageName}`));\n console.log(chalk.gray(` Duration: ${stage.duration}ms`));\n console.log(chalk.gray(` Tokens: ${stage.tokensUsed}`));\n\n if (stage.model) {\n console.log(chalk.gray(` Model: ${stage.model}`));\n }\n\n if (!stage.success && stage.error) {\n console.log(chalk.red(` Error: ${stage.error.message}`));\n }\n });\n }\n\n // Final output\n console.log(chalk.cyan('\\n' + '='.repeat(60)));\n console.log(chalk.cyan('Final Output'));\n console.log(chalk.cyan('='.repeat(60) + '\\n'));\n console.log(result.finalOutput);\n }\n}\n","/**\n * Advanced Stage Executor - Phase 3 Features\n *\n * Advanced features for multi-stage execution:\n * - Parallel execution of independent stages\n * - Conditional stage execution\n * - Stage dependency graph resolution\n * - Memory persistence with embeddings\n * - Streaming stage output\n * - Dependency visualization\n */\n\nimport type { ExecutionContext, Stage } from '../types/agent.js';\nimport type { IMemoryManager } from '../types/memory.js';\nimport { StageExecutor } from './stage-executor.js';\nimport type {\n StageExecutionResult,\n MultiStageExecutionResult,\n StageExecutionOptions\n} from './stage-executor.js';\nimport { logger } from '../utils/logger.js';\nimport chalk from 'chalk';\n\n/**\n * Stage execution plan node\n */\ninterface StageNode {\n stage: Stage;\n index: number;\n dependencies: string[];\n level: number; // Execution level (0 = no deps, 1 = depends on level 0, etc.)\n}\n\n/**\n * Execution timeline entry\n */\ninterface TimelineEntry {\n stageName: string;\n startTime: number;\n endTime: number;\n duration: number;\n level: number;\n}\n\n/**\n * Advanced Stage Executor\n *\n * Extends StageExecutor with:\n * - Dependency resolution\n * - Parallel execution\n * - Conditional execution\n * - Memory persistence\n */\nexport class AdvancedStageExecutor extends StageExecutor {\n /**\n * Execute stages with advanced features\n */\n async executeAdvanced(\n context: ExecutionContext,\n options: StageExecutionOptions = {}\n ): Promise<MultiStageExecutionResult> {\n const stages = context.agent.stages || [];\n\n if (stages.length === 0) {\n throw new Error('Agent has no stages defined');\n }\n\n // Build dependency graph\n const graph = this.buildDependencyGraph(stages);\n\n // Check for circular dependencies\n this.detectCircularDependencies(graph);\n\n // Check if any stages support parallel execution\n const hasParallelStages = stages.some(s => s.parallel);\n\n if (!hasParallelStages) {\n // Fallback to sequential execution\n logger.info('No parallel stages detected, using sequential execution');\n return this.executeStages(context, options);\n }\n\n // Execute with parallel support\n return this.executeWithParallel(context, graph, options);\n }\n\n /**\n * Build dependency graph from stages\n */\n private buildDependencyGraph(stages: Stage[]): StageNode[] {\n const graph: StageNode[] = [];\n\n // First pass: create nodes\n for (let i = 0; i < stages.length; i++) {\n const stage = stages[i];\n if (!stage) continue;\n\n graph.push({\n stage,\n index: i,\n dependencies: stage.dependencies || [],\n level: 0 // Will be calculated\n });\n }\n\n // Second pass: calculate execution levels\n this.calculateLevels(graph);\n\n return graph;\n }\n\n /**\n * Calculate execution level for each stage\n * Level 0 = no dependencies, Level N = depends on stages at level N-1\n */\n private calculateLevels(graph: StageNode[]): void {\n const maxIterations = graph.length;\n let iteration = 0;\n\n while (iteration < maxIterations) {\n let changed = false;\n\n for (const node of graph) {\n if (node.dependencies.length === 0) {\n node.level = 0;\n continue;\n }\n\n // Find max level of dependencies\n let maxDepLevel = -1;\n for (const depName of node.dependencies) {\n const depNode = graph.find(n => n.stage.name === depName);\n if (depNode) {\n maxDepLevel = Math.max(maxDepLevel, depNode.level);\n }\n }\n\n const newLevel = maxDepLevel + 1;\n if (newLevel !== node.level) {\n node.level = newLevel;\n changed = true;\n }\n }\n\n if (!changed) break;\n iteration++;\n }\n }\n\n /**\n * Detect circular dependencies\n */\n private detectCircularDependencies(graph: StageNode[]): void {\n const visiting = new Set<string>();\n const visited = new Set<string>();\n\n const visit = (nodeName: string): void => {\n if (visiting.has(nodeName)) {\n throw new Error(`Circular dependency detected involving stage: ${nodeName}`);\n }\n\n if (visited.has(nodeName)) {\n return;\n }\n\n visiting.add(nodeName);\n\n const node = graph.find(n => n.stage.name === nodeName);\n if (node) {\n for (const dep of node.dependencies) {\n visit(dep);\n }\n }\n\n visiting.delete(nodeName);\n visited.add(nodeName);\n };\n\n for (const node of graph) {\n visit(node.stage.name);\n }\n }\n\n /**\n * Execute stages with parallel support\n */\n private async executeWithParallel(\n context: ExecutionContext,\n graph: StageNode[],\n options: StageExecutionOptions\n ): Promise<MultiStageExecutionResult> {\n const { verbose = false, memoryManager = null, continueOnFailure = false } = options;\n\n // Group stages by execution level\n const maxLevel = Math.max(...graph.map(n => n.level));\n const levelGroups: StageNode[][] = [];\n\n for (let level = 0; level <= maxLevel; level++) {\n levelGroups.push(graph.filter(n => n.level === level));\n }\n\n if (verbose) {\n console.log(chalk.cyan('\\n📊 Execution Plan:'));\n for (let level = 0; level <= maxLevel; level++) {\n const nodesAtLevel = levelGroups[level];\n if (!nodesAtLevel) continue;\n\n console.log(chalk.gray(` Level ${level}: ${nodesAtLevel.map(n => n.stage.name).join(', ')}`));\n }\n console.log();\n }\n\n const allResults: StageExecutionResult[] = [];\n const stageOutputs = new Map<string, string>(); // stageName -> output\n const stageResults = new Map<string, StageExecutionResult>(); // stageName -> result\n const timeline: TimelineEntry[] = [];\n const startTime = Date.now();\n\n // Execute level by level\n for (let level = 0; level <= maxLevel; level++) {\n const nodesAtLevel = levelGroups[level];\n if (!nodesAtLevel || nodesAtLevel.length === 0) continue;\n\n if (verbose) {\n console.log(chalk.cyan(`\\n▶ Executing Level ${level} (${nodesAtLevel.length} stage${nodesAtLevel.length > 1 ? 's' : ''})...\\n`));\n }\n\n // Check which stages can run in parallel\n const parallelNodes = nodesAtLevel.filter(n => n.stage.parallel);\n const sequentialNodes = nodesAtLevel.filter(n => !n.stage.parallel);\n\n // Execute parallel stages\n if (parallelNodes.length > 0) {\n const parallelPromises = parallelNodes.map(node =>\n this.executeNode(node, context, stageOutputs, stageResults, options, timeline)\n );\n\n const parallelResults = await Promise.all(parallelPromises);\n allResults.push(...parallelResults);\n\n // Store outputs and results (skip '[Skipped due to condition]' outputs)\n for (const result of parallelResults) {\n stageResults.set(result.stageName, result);\n if (result.success && result.output !== '[Skipped due to condition]') {\n stageOutputs.set(result.stageName, result.output);\n }\n }\n\n // Check for failures in parallel stages\n if (!continueOnFailure) {\n const failedStage = parallelResults.find(r => !r.success);\n if (failedStage) {\n logger.warn('Parallel stage failed, stopping execution', {\n stage: failedStage.stageName\n });\n // Skip remaining levels\n const totalDuration = Date.now() - startTime;\n const totalTokens = allResults.reduce((sum, r) => sum + r.tokensUsed, 0);\n return {\n stages: allResults,\n totalDuration,\n totalTokens,\n success: false,\n failedStage: allResults.findIndex(r => !r.success),\n finalOutput: this.assembleFinalOutput(allResults)\n };\n }\n }\n }\n\n // Execute sequential stages\n for (const node of sequentialNodes) {\n const result = await this.executeNode(node, context, stageOutputs, stageResults, options, timeline);\n allResults.push(result);\n\n stageResults.set(result.stageName, result);\n if (result.success && result.output !== '[Skipped due to condition]') {\n stageOutputs.set(result.stageName, result.output);\n } else if (!result.success && !continueOnFailure) {\n // Stage failed and continueOnFailure is false\n logger.warn('Sequential stage failed, stopping execution', {\n stage: result.stageName\n });\n // Skip remaining levels\n const totalDuration = Date.now() - startTime;\n const totalTokens = allResults.reduce((sum, r) => sum + r.tokensUsed, 0);\n return {\n stages: allResults,\n totalDuration,\n totalTokens,\n success: false,\n failedStage: allResults.findIndex(r => !r.success),\n finalOutput: this.assembleFinalOutput(allResults)\n };\n }\n }\n }\n\n const totalDuration = Date.now() - startTime;\n const totalTokens = allResults.reduce((sum, r) => sum + r.tokensUsed, 0);\n const success = allResults.every(r => r.success);\n const failedStageIndex = allResults.findIndex(r => !r.success);\n\n // Generate final output\n const finalOutput = this.assembleFinalOutput(allResults);\n\n return {\n stages: allResults,\n totalDuration,\n totalTokens,\n success,\n failedStage: failedStageIndex >= 0 ? failedStageIndex : undefined,\n finalOutput\n };\n }\n\n /**\n * Execute a single stage node\n */\n private async executeNode(\n node: StageNode,\n context: ExecutionContext,\n stageOutputs: Map<string, string>,\n stageResults: Map<string, StageExecutionResult>,\n options: StageExecutionOptions,\n timeline: TimelineEntry[]\n ): Promise<StageExecutionResult> {\n const { stage } = node;\n const { verbose = false, memoryManager = null } = options;\n\n // Check if all dependencies succeeded\n for (const dep of node.dependencies) {\n const depResult = stageResults.get(dep);\n if (!depResult) {\n // Dependency hasn't been executed yet (shouldn't happen with proper dependency graph)\n if (verbose) {\n console.log(chalk.red(`⚠ Skipping stage \"${stage.name}\" (dependency \"${dep}\" not executed)\\n`));\n }\n return {\n stageName: stage.name,\n stageIndex: node.index,\n output: `[Skipped: dependency \"${dep}\" not executed]`,\n duration: 0,\n tokensUsed: 0,\n success: false,\n error: new Error(`Dependency \"${dep}\" not executed`)\n };\n }\n\n if (!depResult.success) {\n // Dependency failed\n if (verbose) {\n console.log(chalk.yellow(`⊘ Skipping stage \"${stage.name}\" (dependency \"${dep}\" failed)\\n`));\n }\n return {\n stageName: stage.name,\n stageIndex: node.index,\n output: `[Skipped: dependency \"${dep}\" failed]`,\n duration: 0,\n tokensUsed: 0,\n success: false,\n error: new Error(`Dependency \"${dep}\" failed`)\n };\n }\n }\n\n // Check condition\n if (stage.condition) {\n const shouldExecute = this.evaluateCondition(stage.condition, stageOutputs, stageResults);\n if (!shouldExecute) {\n if (verbose) {\n console.log(chalk.yellow(`⊘ Skipping stage \"${stage.name}\" (condition not met)\\n`));\n }\n\n return {\n stageName: stage.name,\n stageIndex: node.index,\n output: '[Skipped due to condition]',\n duration: 0,\n tokensUsed: 0,\n success: true\n };\n }\n }\n\n // Build context from dependencies\n const previousOutputs: string[] = [];\n for (const dep of node.dependencies) {\n const output = stageOutputs.get(dep);\n if (output) {\n previousOutputs.push(output);\n }\n }\n\n // Execute stage\n const stageStartTime = Date.now();\n\n try {\n const result = await this.executeStageInternal(\n stage,\n node.index,\n context,\n previousOutputs,\n options\n );\n\n const stageEndTime = Date.now();\n\n // Record timeline\n timeline.push({\n stageName: stage.name,\n startTime: stageStartTime,\n endTime: stageEndTime,\n duration: stageEndTime - stageStartTime,\n level: node.level\n });\n\n // Save to memory if requested\n if (stage.saveToMemory && result.success && memoryManager) {\n await this.saveStageToMemory(\n context.agent.name,\n stage,\n result,\n memoryManager\n );\n }\n\n return result;\n\n } catch (error) {\n return {\n stageName: stage.name,\n stageIndex: node.index,\n output: '',\n duration: Date.now() - stageStartTime,\n tokensUsed: 0,\n success: false,\n error: error as Error\n };\n }\n }\n\n /**\n * Execute stage internal (copied from parent but made accessible)\n */\n private async executeStageInternal(\n stage: Stage,\n index: number,\n context: ExecutionContext,\n previousOutputs: string[],\n options: { verbose?: boolean; showProgress?: boolean; signal?: AbortSignal }\n ): Promise<StageExecutionResult> {\n // Call parent's private method via public interface\n // Note: This is a workaround - in production we'd refactor StageExecutor\n const allStages = context.agent.stages || [];\n const tempContext = { ...context, agent: { ...context.agent, stages: [stage] } };\n\n // Build prompt manually\n const prompt = this.buildStagePromptManual(stage, context.task, previousOutputs, allStages);\n\n const startTime = Date.now();\n const response = await context.provider.execute({\n prompt,\n systemPrompt: context.agent.systemPrompt,\n model: stage.model || context.agent.model,\n temperature: stage.temperature ?? context.agent.temperature,\n maxTokens: context.agent.maxTokens,\n signal: options.signal // v5.0.8: Pass abort signal for timeout cancellation\n });\n\n const duration = Date.now() - startTime;\n\n return {\n stageName: stage.name,\n stageIndex: index,\n output: response.content,\n duration,\n tokensUsed: response.tokensUsed?.total ?? 0,\n success: true,\n model: stage.model || context.agent.model\n };\n }\n\n /**\n * Build stage prompt manually\n */\n private buildStagePromptManual(\n stage: Stage,\n originalTask: string,\n previousOutputs: string[],\n allStages: Stage[]\n ): string {\n let prompt = '';\n\n prompt += `# Current Stage: ${stage.name}\\n\\n`;\n prompt += `${stage.description}\\n\\n`;\n\n if (stage.key_questions && stage.key_questions.length > 0) {\n prompt += `## Key Questions to Address\\n\\n`;\n stage.key_questions.forEach(q => {\n prompt += `- ${q}\\n`;\n });\n prompt += `\\n`;\n }\n\n if (stage.outputs && stage.outputs.length > 0) {\n prompt += `## Expected Outputs\\n\\n`;\n stage.outputs.forEach(o => {\n prompt += `- ${o}\\n`;\n });\n prompt += `\\n`;\n }\n\n prompt += `## Original Task\\n\\n${originalTask}\\n\\n`;\n\n if (previousOutputs.length > 0) {\n prompt += `## Context from Previous Stages\\n\\n`;\n previousOutputs.forEach((output, i) => {\n prompt += `### Previous Stage ${i + 1}\\n\\n${output}\\n\\n`;\n });\n }\n\n prompt += `## Your Task\\n\\n`;\n prompt += `Focus on completing **${stage.name}** based on the context above.\\n`;\n\n return prompt;\n }\n\n /**\n * Evaluate condition string\n * Simple implementation - supports basic conditions\n */\n private evaluateCondition(\n condition: string,\n stageOutputs: Map<string, string>,\n stageResults: Map<string, StageExecutionResult>\n ): boolean {\n // Simple condition evaluation\n // Example: \"previous.success\" or \"data_fetch.success\"\n\n if (condition === 'previous.success') {\n // Check if all previous stages succeeded\n if (stageResults.size === 0) {\n return false;\n }\n // Check if any stage failed\n for (const result of stageResults.values()) {\n if (!result.success && result.output !== '[Skipped due to condition]') {\n return false;\n }\n }\n return true;\n }\n\n // Check specific stage success\n const match = condition.match(/^(\\w+)\\.success$/);\n if (match && match[1]) {\n const stageName = match[1];\n const result = stageResults.get(stageName);\n return result !== undefined && result.success;\n }\n\n // Default: execute the stage\n return true;\n }\n\n /**\n * Generate dependency graph visualization (ASCII art)\n */\n visualizeDependencyGraph(stages: Stage[]): string {\n const graph = this.buildDependencyGraph(stages);\n let output = '\\n' + chalk.cyan('📊 Stage Dependency Graph\\n\\n');\n\n const maxLevel = Math.max(...graph.map(n => n.level));\n\n for (let level = 0; level <= maxLevel; level++) {\n const nodesAtLevel = graph.filter(n => n.level === level);\n\n output += chalk.gray(`Level ${level}:\\n`);\n\n for (const node of nodesAtLevel) {\n const parallel = node.stage.parallel ? chalk.green(' [parallel]') : '';\n const condition = node.stage.condition ? chalk.yellow(` [if: ${node.stage.condition}]`) : '';\n\n output += ` ${chalk.cyan('○')} ${node.stage.name}${parallel}${condition}\\n`;\n\n // Show dependencies\n if (node.dependencies.length > 0) {\n output += chalk.gray(` ↳ depends on: ${node.dependencies.join(', ')}\\n`);\n }\n }\n\n output += '\\n';\n }\n\n return output;\n }\n\n /**\n * Generate execution timeline visualization\n */\n visualizeTimeline(timeline: TimelineEntry[]): string {\n let output = '\\n' + chalk.cyan('⏱️ Execution Timeline\\n\\n');\n\n const maxLevel = Math.max(...timeline.map(t => t.level));\n const totalDuration = Math.max(...timeline.map(t => t.endTime)) - Math.min(...timeline.map(t => t.startTime));\n\n for (let level = 0; level <= maxLevel; level++) {\n const entriesAtLevel = timeline.filter(t => t.level === level);\n\n output += chalk.gray(`Level ${level}:\\n`);\n\n for (const entry of entriesAtLevel) {\n const bar = '█'.repeat(Math.max(1, Math.floor((entry.duration / totalDuration) * 40)));\n output += ` ${entry.stageName.padEnd(20)} ${chalk.green(bar)} ${entry.duration}ms\\n`;\n }\n\n output += '\\n';\n }\n\n return output;\n }\n}\n","/**\n * Output Formatter - Format execution results in different formats\n */\n\nimport chalk from 'chalk';\nimport type { ExecutionResult } from '../agents/executor.js';\n\nexport type OutputFormat = 'text' | 'json' | 'markdown';\n\n/**\n * Format execution result based on output format\n */\nexport function formatOutput(\n result: ExecutionResult,\n format: OutputFormat,\n verbose: boolean = false\n): string {\n switch (format) {\n case 'json':\n return formatAsJson(result);\n\n case 'markdown':\n return formatAsMarkdown(result, verbose);\n\n case 'text':\n default:\n return formatAsText(result, verbose);\n }\n}\n\n/**\n * Format as JSON\n */\nfunction formatAsJson(result: ExecutionResult): string {\n return JSON.stringify({\n content: result.response.content,\n tokensUsed: result.response.tokensUsed,\n latencyMs: result.response.latencyMs,\n model: result.response.model,\n finishReason: result.response.finishReason\n }, null, 2);\n}\n\n/**\n * Format as Markdown\n */\nfunction formatAsMarkdown(result: ExecutionResult, verbose: boolean): string {\n const md: string[] = [\n `# Execution Result\\n`,\n `**Model**: ${result.response.model}`,\n `**Latency**: ${result.response.latencyMs}ms`,\n `**Tokens**: ${result.response.tokensUsed?.total || 'N/A'}\\n`,\n `## Response\\n`,\n result.response.content,\n `\\n`\n ];\n\n if (verbose && result.response.tokensUsed) {\n md.push(`## Token Usage\\n`);\n md.push(`- Prompt: ${result.response.tokensUsed.prompt || 'N/A'}`);\n md.push(`- Completion: ${result.response.tokensUsed.completion || 'N/A'}`);\n md.push(`- Total: ${result.response.tokensUsed.total || 'N/A'}\\n`);\n }\n\n return md.join('\\n');\n}\n\n/**\n * Format as plain text\n */\nfunction formatAsText(result: ExecutionResult, verbose: boolean): string {\n const output: string[] = [];\n\n if (!verbose) {\n output.push(chalk.cyan('\\n📝 Result:\\n'));\n output.push(result.response.content);\n output.push('\\n');\n }\n\n if (verbose) {\n output.push(chalk.gray(`\\nModel: ${result.response.model}`));\n output.push(chalk.gray(`Latency: ${result.response.latencyMs}ms`));\n if (result.response.tokensUsed) {\n output.push(chalk.gray(`Tokens: ${result.response.tokensUsed.total || 'N/A'}`));\n }\n }\n\n return output.join('\\n');\n}\n\n/**\n * Format for file save (includes metadata)\n */\nexport function formatForSave(\n result: ExecutionResult,\n format: OutputFormat,\n metadata: {\n agent: string;\n task: string;\n timestamp?: string;\n }\n): string {\n if (format === 'json') {\n return JSON.stringify({\n agent: metadata.agent,\n task: metadata.task,\n timestamp: metadata.timestamp || new Date().toISOString(),\n result: {\n content: result.response.content,\n tokensUsed: result.response.tokensUsed,\n latencyMs: result.response.latencyMs,\n model: result.response.model,\n finishReason: result.response.finishReason\n }\n }, null, 2);\n }\n\n // For text and markdown, just return the formatted output\n return formatOutput(result, format, true);\n}\n","/**\n * Session Command - Manage multi-agent collaborative sessions\n *\n * @since v4.7.0\n */\n\nimport type { CommandModule, Argv } from 'yargs';\nimport { createSessionManager } from '../utils/session-utils.js';\nimport chalk from 'chalk';\nimport Table from 'cli-table3';\n\ninterface SessionCreateOptions {\n task: string;\n initiator: string;\n}\n\ninterface SessionListOptions {\n agent?: string;\n status?: 'active' | 'completed' | 'failed';\n json?: boolean;\n}\n\ninterface SessionStatusOptions {\n id: string;\n json?: boolean;\n}\n\ninterface SessionCompleteOptions {\n id: string;\n}\n\ninterface SessionFailOptions {\n id: string;\n}\n\n/**\n * Session Create Command\n */\nconst createCommand: CommandModule<Record<string, unknown>, SessionCreateOptions> = {\n command: 'create <task> <initiator>',\n describe: 'Create a new multi-agent session',\n\n builder: (yargs: Argv<Record<string, unknown>>): Argv<SessionCreateOptions> => {\n return yargs\n .positional('task', {\n describe: 'Overall task/goal for the session',\n type: 'string',\n demandOption: true\n })\n .positional('initiator', {\n describe: 'Agent that initiates the session',\n type: 'string',\n demandOption: true\n }) as Argv<SessionCreateOptions>;\n },\n\n handler: async (argv) => {\n try {\n const sessionManager = await createSessionManager();\n\n const session = await sessionManager.createSession(argv.task, argv.initiator);\n\n console.log(chalk.green.bold('\\n✓ Session created successfully\\n'));\n console.log(chalk.gray(`Session ID: ${chalk.white(session.id)}`));\n console.log(chalk.gray(`Task: ${chalk.white(session.task)}`));\n console.log(chalk.gray(`Initiator: ${chalk.white(session.initiator)}`));\n console.log(chalk.gray(`Status: ${chalk.white(session.status)}`));\n console.log(chalk.gray(`Created: ${chalk.white(session.createdAt.toISOString())}`));\n console.log();\n\n process.exit(0);\n } catch (error) {\n console.error(chalk.red.bold('\\n✗ Failed to create session\\n'));\n console.error(chalk.red((error as Error).message));\n process.exit(1);\n }\n }\n};\n\n/**\n * Session List Command\n */\nconst listCommand: CommandModule<Record<string, unknown>, SessionListOptions> = {\n command: 'list',\n describe: 'List all sessions',\n\n builder: (yargs) => {\n return yargs\n .option('agent', {\n describe: 'Filter by agent name',\n type: 'string'\n })\n .option('status', {\n describe: 'Filter by status',\n type: 'string',\n choices: ['active', 'completed', 'failed']\n })\n .option('json', {\n describe: 'Output as JSON',\n type: 'boolean',\n default: false\n });\n },\n\n handler: async (argv) => {\n try {\n const sessionManager = await createSessionManager();\n\n let sessions = argv.agent\n ? await sessionManager.getActiveSessionsForAgent(argv.agent)\n : await sessionManager.getActiveSessions();\n\n // Filter by status if specified\n if (argv.status) {\n sessions = sessions.filter(s => s.status === argv.status);\n }\n\n if (argv.json) {\n console.log(JSON.stringify(sessions, null, 2));\n process.exit(0);\n }\n\n if (sessions.length === 0) {\n console.log(chalk.yellow('\\nNo sessions found\\n'));\n process.exit(0);\n }\n\n console.log(chalk.blue.bold(`\\n📋 Sessions (${sessions.length})\\n`));\n\n const table = new Table({\n head: ['ID', 'Task', 'Initiator', 'Agents', 'Status', 'Created'],\n colWidths: [38, 40, 15, 25, 12, 12]\n });\n\n sessions.forEach(session => {\n table.push([\n session.id.substring(0, 8) + '...',\n session.task.substring(0, 37) + (session.task.length > 37 ? '...' : ''),\n session.initiator,\n session.agents.join(', ').substring(0, 22),\n session.status,\n new Date(session.createdAt).toLocaleDateString()\n ]);\n });\n\n console.log(table.toString());\n console.log();\n\n process.exit(0);\n } catch (error) {\n console.error(chalk.red.bold('\\n✗ Failed to list sessions\\n'));\n console.error(chalk.red((error as Error).message));\n process.exit(1);\n }\n }\n};\n\n/**\n * Session Status Command\n */\nconst statusCommand: CommandModule<Record<string, unknown>, SessionStatusOptions> = {\n command: 'status <id>',\n describe: 'Show session status',\n\n builder: (yargs: Argv<Record<string, unknown>>): Argv<SessionStatusOptions> => {\n return yargs\n .positional('id', {\n describe: 'Session ID',\n type: 'string',\n demandOption: true\n })\n .option('json', {\n describe: 'Output as JSON',\n type: 'boolean',\n default: false\n }) as Argv<SessionStatusOptions>;\n },\n\n handler: async (argv) => {\n try {\n const sessionManager = await createSessionManager();\n const session = await sessionManager.getSession(argv.id);\n\n if (!session) {\n console.log(chalk.red.bold(`\\n✗ Session not found: ${argv.id}\\n`));\n process.exit(1);\n }\n\n if (argv.json) {\n console.log(JSON.stringify(session, null, 2));\n process.exit(0);\n }\n\n console.log(chalk.blue.bold('\\n📊 Session Status\\n'));\n console.log(chalk.gray(`ID: ${chalk.white(session.id)}`));\n console.log(chalk.gray(`Task: ${chalk.white(session.task)}`));\n console.log(chalk.gray(`Initiator: ${chalk.white(session.initiator)}`));\n console.log(chalk.gray(`Status: ${chalk.white(session.status)}`));\n console.log(chalk.gray(`Agents: ${chalk.white(session.agents.join(', '))}`));\n console.log(chalk.gray(`Created: ${chalk.white(session.createdAt.toISOString())}`));\n console.log(chalk.gray(`Updated: ${chalk.white(session.updatedAt.toISOString())}`));\n\n if (session.metadata && Object.keys(session.metadata).length > 0) {\n console.log(chalk.gray(`\\nMetadata:`));\n Object.entries(session.metadata).forEach(([key, value]) => {\n console.log(chalk.gray(` ${key}: ${JSON.stringify(value)}`));\n });\n }\n\n console.log();\n process.exit(0);\n } catch (error) {\n console.error(chalk.red.bold('\\n✗ Failed to get session status\\n'));\n console.error(chalk.red((error as Error).message));\n process.exit(1);\n }\n }\n};\n\n/**\n * Session Complete Command\n */\nconst completeCommand: CommandModule<Record<string, unknown>, SessionCompleteOptions> = {\n command: 'complete <id>',\n describe: 'Mark session as completed',\n\n builder: (yargs) => {\n return yargs.positional('id', {\n describe: 'Session ID',\n type: 'string',\n demandOption: true\n });\n },\n\n handler: async (argv) => {\n try {\n const sessionManager = await createSessionManager();\n await sessionManager.completeSession(argv.id);\n\n console.log(chalk.green.bold(`\\n✓ Session marked as completed: ${argv.id}\\n`));\n process.exit(0);\n } catch (error) {\n console.error(chalk.red.bold('\\n✗ Failed to complete session\\n'));\n console.error(chalk.red((error as Error).message));\n process.exit(1);\n }\n }\n};\n\n/**\n * Session Fail Command\n */\nconst failCommand: CommandModule<Record<string, unknown>, SessionFailOptions> = {\n command: 'fail <id>',\n describe: 'Mark session as failed',\n\n builder: (yargs) => {\n return yargs.positional('id', {\n describe: 'Session ID',\n type: 'string',\n demandOption: true\n });\n },\n\n handler: async (argv) => {\n try {\n const sessionManager = await createSessionManager();\n await sessionManager.failSession(argv.id, new Error('Manually marked as failed'));\n\n console.log(chalk.yellow.bold(`\\n⚠ Session marked as failed: ${argv.id}\\n`));\n process.exit(0);\n } catch (error) {\n console.error(chalk.red.bold('\\n✗ Failed to mark session as failed\\n'));\n console.error(chalk.red((error as Error).message));\n process.exit(1);\n }\n }\n};\n\n/**\n * Main Session Command\n */\nexport const sessionCommand: CommandModule = {\n command: 'session <command>',\n describe: 'Manage multi-agent collaborative sessions',\n\n builder: (yargs) => {\n return yargs\n .command(createCommand)\n .command(listCommand)\n .command(statusCommand)\n .command(completeCommand)\n .command(failCommand)\n .demandCommand(1, 'You must specify a session command')\n .help();\n },\n\n handler: () => {\n // Parent command handler (not used, subcommands handle everything)\n }\n};\n","/**\n * Session Utils - Shared utilities for session management in CLI commands\n *\n * @module cli/utils/session-utils\n * @since v4.7.0\n */\n\nimport { SessionManager } from '../../core/session-manager.js';\nimport { PathResolver } from '../../core/path-resolver.js';\nimport { join } from 'path';\n\n/**\n * Create SessionManager instance with persistence\n *\n * Detects project root and initializes SessionManager with persistence file.\n * This is the standard way to create SessionManager in CLI commands.\n *\n * @returns Initialized SessionManager instance\n * @throws {Error} If project root cannot be detected or initialization fails\n *\n * @example\n * ```typescript\n * try {\n * const sessionManager = await createSessionManager();\n * const session = await sessionManager.createSession('Task', 'agent');\n * } catch (error) {\n * console.error('Failed to initialize session manager:', error.message);\n * process.exit(1);\n * }\n * ```\n */\nexport async function createSessionManager(): Promise<SessionManager> {\n try {\n const projectDir = await new PathResolver({\n projectDir: process.cwd(),\n workingDir: process.cwd(),\n agentWorkspace: join(process.cwd(), '.automatosx', 'workspaces')\n }).detectProjectRoot();\n\n const sessionManager = new SessionManager({\n persistencePath: join(projectDir, '.automatosx', 'sessions', 'sessions.json')\n });\n\n await sessionManager.initialize();\n return sessionManager;\n } catch (error) {\n const err = error as Error;\n throw new Error(\n `Failed to initialize SessionManager: ${err.message}\\n` +\n `Make sure you're in an AutomatosX project directory or run 'automatosx init' first.`\n );\n }\n}\n","/**\n * Status Command - Display system status and health\n *\n * Shows comprehensive system information including:\n * - Project and configuration info\n * - Directory structure and existence\n * - Provider availability and health\n * - Workspace statistics\n * - Memory system status\n */\n\nimport type { CommandModule } from 'yargs';\nimport { Router } from '../../core/router.js';\nimport { PathResolver } from '../../core/path-resolver.js';\nimport { ClaudeProvider } from '../../providers/claude-provider.js';\nimport { GeminiProvider } from '../../providers/gemini-provider.js';\nimport { OpenAIProvider } from '../../providers/openai-provider.js';\nimport { loadConfig } from '../../core/config.js';\nimport { logger } from '../../utils/logger.js';\nimport chalk from 'chalk';\nimport { existsSync, statSync } from 'fs';\nimport { readdir, stat } from 'fs/promises';\nimport { join, basename } from 'path';\nimport { createRequire } from 'module';\nimport os from 'os';\nimport { printError } from '../../utils/error-formatter.js';\n\n// Read version from version.json (single source of truth)\nconst require = createRequire(import.meta.url);\nlet VERSION = 'unknown';\ntry {\n // Try to load from same directory first (when built to dist/)\n const versionData = require('../version.json');\n VERSION = versionData.version || 'unknown';\n} catch (err) {\n // Fallback: try parent directory\n try {\n const versionData = require('../../version.json');\n VERSION = versionData.version || 'unknown';\n } catch (err2) {\n // Fallback: try grandparent directory (development mode from src/cli/commands/)\n try {\n const versionData = require('../../../version.json');\n VERSION = versionData.version || 'unknown';\n } catch (err3) {\n // Final fallback: package.json\n try {\n const packageJson = require('../../../package.json');\n VERSION = packageJson.version || 'unknown';\n } catch (err4) {\n logger.debug('Version file not found, using fallback');\n }\n }\n }\n}\n\ninterface StatusOptions {\n verbose?: boolean;\n json?: boolean;\n}\n\nexport const statusCommand: CommandModule<Record<string, unknown>, StatusOptions> = {\n command: 'status',\n describe: 'Display system status and health',\n\n builder: (yargs) => {\n return yargs\n .option('verbose', {\n describe: 'Verbose output with detailed statistics',\n type: 'boolean',\n default: false\n })\n .option('json', {\n describe: 'Output as JSON',\n type: 'boolean',\n default: false\n });\n },\n\n handler: async (argv) => {\n try {\n const startTime = Date.now();\n const config = await loadConfig(process.cwd());\n const projectDir = process.cwd();\n\n // Initialize path resolver\n const pathResolver = new PathResolver({\n projectDir,\n workingDir: process.cwd(),\n agentWorkspace: join(projectDir, '.automatosx', 'workspaces')\n });\n\n // Detect project root\n const detectedProjectDir = await pathResolver.detectProjectRoot();\n\n // Check directories\n const automatosxDir = join(detectedProjectDir, '.automatosx');\n const agentsDir = join(automatosxDir, 'agents');\n const abilitiesDir = join(automatosxDir, 'abilities');\n const memoryDir = join(automatosxDir, 'memory');\n const workspacesDir = join(automatosxDir, 'workspaces');\n\n // Initialize providers\n const providers = [];\n\n if (config.providers['claude-code']?.enabled) {\n providers.push(new ClaudeProvider({\n name: 'claude-code',\n enabled: true,\n priority: config.providers['claude-code'].priority,\n timeout: config.providers['claude-code'].timeout,\n command: config.providers['claude-code'].command\n }));\n }\n\n if (config.providers['gemini-cli']?.enabled) {\n providers.push(new GeminiProvider({\n name: 'gemini-cli',\n enabled: true,\n priority: config.providers['gemini-cli'].priority,\n timeout: config.providers['gemini-cli'].timeout,\n command: config.providers['gemini-cli'].command\n }));\n }\n\n if (config.providers['openai']?.enabled) {\n providers.push(new OpenAIProvider({\n name: 'openai',\n enabled: true,\n priority: config.providers['openai'].priority,\n timeout: config.providers['openai'].timeout,\n command: config.providers['openai'].command\n }));\n }\n\n const router = new Router({\n providers,\n fallbackEnabled: true\n });\n\n // Get provider health\n const availableProviders = await router.getAvailableProviders();\n const providerHealth = await Promise.all(\n providers.map(async (p) => ({\n name: p.name,\n available: await p.isAvailable(),\n health: await p.getHealth(),\n priority: p.priority\n }))\n );\n\n // Collect workspace statistics\n const workspaceStats = await getWorkspaceStatistics(workspacesDir);\n\n // Collect memory statistics\n const memoryStats = await getMemoryStatistics(memoryDir);\n\n // Collect agent and ability counts\n const agentCount = await countFiles(agentsDir, ['.yaml', '.yml']);\n const abilityCount = await countFiles(abilitiesDir, ['.md']);\n\n // Get project info\n const projectInfo = await getProjectInfo(detectedProjectDir);\n\n // Build status object\n const status = {\n system: {\n version: VERSION,\n nodeVersion: process.version,\n platform: `${os.platform()} ${os.arch()}`,\n uptime: Math.floor(process.uptime()),\n projectDir: detectedProjectDir,\n workingDir: process.cwd()\n },\n project: projectInfo,\n configuration: {\n configFile: join(detectedProjectDir, 'automatosx.config.json'),\n configExists: existsSync(join(detectedProjectDir, 'automatosx.config.json')),\n logLevel: config.logging.level,\n memoryMaxEntries: config.memory.maxEntries,\n memoryRetentionDays: config.memory.cleanupDays\n },\n directories: {\n automatosx: { path: automatosxDir, exists: existsSync(automatosxDir) },\n agents: { path: agentsDir, exists: existsSync(agentsDir), count: agentCount },\n abilities: { path: abilitiesDir, exists: existsSync(abilitiesDir), count: abilityCount },\n memory: { path: memoryDir, exists: existsSync(memoryDir), ...memoryStats },\n workspaces: { path: workspacesDir, exists: existsSync(workspacesDir), ...workspaceStats }\n },\n providers: providerHealth,\n router: {\n totalProviders: providers.length,\n availableProviders: availableProviders.length,\n fallbackEnabled: true\n },\n performance: {\n statusCheckMs: Date.now() - startTime\n }\n };\n\n // Output\n if (argv.json) {\n console.log(JSON.stringify(status, null, 2));\n } else {\n console.log(chalk.blue.bold('\\n📊 AutomatosX Status\\n'));\n\n // System\n console.log(chalk.cyan('System:'));\n console.log(` Version: ${chalk.white(status.system.version)}`);\n console.log(` Node: ${chalk.white(status.system.nodeVersion)}`);\n console.log(` Platform: ${chalk.white(status.system.platform)}`);\n if (argv.verbose) {\n console.log(` Process Uptime: ${chalk.white(formatUptime(status.system.uptime))}`);\n }\n console.log();\n\n // Project Info\n if (status.project.name || argv.verbose) {\n console.log(chalk.cyan('Project:'));\n if (status.project.name) {\n console.log(` Name: ${chalk.white(status.project.name)}`);\n }\n if (status.project.type) {\n console.log(` Type: ${chalk.white(status.project.type)}`);\n }\n console.log(` Directory: ${chalk.white(status.system.projectDir)}`);\n if (status.system.workingDir !== status.system.projectDir) {\n console.log(` Working Dir: ${chalk.white(status.system.workingDir)}`);\n }\n console.log();\n }\n\n // Configuration\n console.log(chalk.cyan('Configuration:'));\n const configIcon = status.configuration.configExists ? chalk.green('✓') : chalk.yellow('⚠');\n const configText = status.configuration.configExists ? 'found' : 'using defaults';\n console.log(` ${configIcon} Config: ${configText}`);\n if (argv.verbose && status.configuration.configExists) {\n console.log(chalk.gray(` ${status.configuration.configFile}`));\n }\n console.log(` Log Level: ${chalk.white(status.configuration.logLevel)}`);\n console.log(` Memory Limit: ${chalk.white(status.configuration.memoryMaxEntries.toLocaleString())} entries`);\n console.log(` Retention: ${chalk.white(status.configuration.memoryRetentionDays)} days`);\n console.log();\n\n // Directories\n console.log(chalk.cyan('Resources:'));\n for (const [name, dir] of Object.entries(status.directories)) {\n const statusIcon = dir.exists ? chalk.green('✓') : chalk.red('✗');\n\n let info = '';\n if (name === 'agents' && 'count' in dir) {\n const agentDir = dir as { count: number };\n info = ` (${agentDir.count} ${agentDir.count === 1 ? 'agent' : 'agents'})`;\n } else if (name === 'abilities' && 'count' in dir) {\n const abilityDir = dir as { count: number };\n info = ` (${abilityDir.count} ${abilityDir.count === 1 ? 'ability' : 'abilities'})`;\n } else if (name === 'memory' && 'files' in dir) {\n const memDir = dir as { files: number; sizeBytes: number };\n info = ` (${memDir.files} ${memDir.files === 1 ? 'file' : 'files'}, ${formatBytes(memDir.sizeBytes || 0)})`;\n } else if (name === 'workspaces' && 'workspaces' in dir) {\n const wsDir = dir as { workspaces: number; totalSizeBytes: number };\n info = ` (${wsDir.workspaces} ${wsDir.workspaces === 1 ? 'workspace' : 'workspaces'}, ${formatBytes(wsDir.totalSizeBytes || 0)})`;\n }\n\n console.log(` ${statusIcon} ${name}${info}`);\n if (argv.verbose) {\n console.log(chalk.gray(` ${dir.path}`));\n }\n }\n console.log();\n\n // Providers\n console.log(chalk.cyan('Providers:'));\n for (const provider of status.providers) {\n const statusIcon = provider.available ? chalk.green('✓') : chalk.red('✗');\n const statusText = provider.available ? chalk.green('available') : chalk.red('unavailable');\n console.log(` ${statusIcon} ${provider.name}: ${statusText} (priority: ${provider.priority})`);\n\n if (argv.verbose) {\n console.log(chalk.gray(` Failures: ${provider.health.consecutiveFailures}`));\n console.log(chalk.gray(` Latency: ${provider.health.latencyMs}ms`));\n console.log(chalk.gray(` Error rate: ${(provider.health.errorRate * 100).toFixed(2)}%`));\n }\n }\n console.log();\n\n // Router\n console.log(chalk.cyan('Router:'));\n console.log(` Total providers: ${chalk.white(status.router.totalProviders)}`);\n console.log(` Available: ${chalk.white(status.router.availableProviders)}`);\n console.log(` Fallback: ${chalk.white(status.router.fallbackEnabled ? 'enabled' : 'disabled')}`);\n console.log();\n\n // Performance (verbose only)\n if (argv.verbose) {\n console.log(chalk.cyan('Performance:'));\n console.log(` Status check: ${chalk.white(status.performance.statusCheckMs)}ms`);\n console.log();\n }\n\n // Overall status\n const allDirsExist = Object.values(status.directories).every(d => d.exists);\n const hasAvailableProviders = status.router.availableProviders > 0;\n const isHealthy = allDirsExist && hasAvailableProviders;\n\n if (isHealthy) {\n console.log(chalk.green.bold('✅ System is healthy\\n'));\n } else {\n console.log(chalk.yellow.bold('⚠️ System has issues\\n'));\n if (!allDirsExist) {\n console.log(chalk.yellow(' Some directories are missing. Run `automatosx init` to initialize.'));\n }\n if (!hasAvailableProviders) {\n console.log(chalk.yellow(' No providers available. Check provider configuration.'));\n }\n console.log();\n }\n }\n\n } catch (error) {\n printError(error, {\n verbose: argv.verbose,\n showCode: true,\n showSuggestions: true,\n colors: true\n });\n logger.error('Status check failed', { error: (error as Error).message });\n process.exit(1);\n }\n }\n};\n\n/**\n * Helper Functions\n */\n\n/**\n * Get workspace statistics\n */\nasync function getWorkspaceStatistics(workspacesDir: string): Promise<{\n workspaces: number;\n totalSizeBytes: number;\n files: number;\n}> {\n if (!existsSync(workspacesDir)) {\n return { workspaces: 0, totalSizeBytes: 0, files: 0 };\n }\n\n try {\n const entries = await readdir(workspacesDir, { withFileTypes: true });\n const workspaces = entries.filter(e => e.isDirectory());\n\n let totalSizeBytes = 0;\n let files = 0;\n\n for (const workspace of workspaces) {\n const workspacePath = join(workspacesDir, workspace.name);\n const stats = await getDirectoryStats(workspacePath);\n totalSizeBytes += stats.size;\n files += stats.files;\n }\n\n return {\n workspaces: workspaces.length,\n totalSizeBytes,\n files\n };\n } catch (error) {\n logger.warn('Failed to get workspace statistics', { error: (error as Error).message });\n return { workspaces: 0, totalSizeBytes: 0, files: 0 };\n }\n}\n\n/**\n * Get memory statistics\n */\nasync function getMemoryStatistics(memoryDir: string): Promise<{\n files: number;\n sizeBytes: number;\n}> {\n if (!existsSync(memoryDir)) {\n return { files: 0, sizeBytes: 0 };\n }\n\n try {\n const stats = await getDirectoryStats(memoryDir);\n return {\n files: stats.files,\n sizeBytes: stats.size\n };\n } catch (error) {\n logger.warn('Failed to get memory statistics', { error: (error as Error).message });\n return { files: 0, sizeBytes: 0 };\n }\n}\n\n/**\n * Get directory statistics recursively\n */\nasync function getDirectoryStats(dirPath: string): Promise<{ size: number; files: number }> {\n let totalSize = 0;\n let totalFiles = 0;\n\n try {\n const entries = await readdir(dirPath, { withFileTypes: true });\n\n for (const entry of entries) {\n const fullPath = join(dirPath, entry.name);\n\n if (entry.isDirectory()) {\n const subStats = await getDirectoryStats(fullPath);\n totalSize += subStats.size;\n totalFiles += subStats.files;\n } else if (entry.isFile()) {\n const stats = await stat(fullPath);\n totalSize += stats.size;\n totalFiles++;\n }\n }\n } catch (error) {\n // Silently ignore errors (permission denied, etc.)\n }\n\n return { size: totalSize, files: totalFiles };\n}\n\n/**\n * Count files with specific extensions in a directory\n */\nasync function countFiles(dirPath: string, extensions: string[]): Promise<number> {\n if (!existsSync(dirPath)) {\n return 0;\n }\n\n try {\n const files = await readdir(dirPath);\n return files.filter(f => extensions.some(ext => f.endsWith(ext))).length;\n } catch (error) {\n logger.warn('Failed to count files', { dirPath, error: (error as Error).message });\n return 0;\n }\n}\n\n/**\n * Get project information from package.json\n */\nasync function getProjectInfo(projectDir: string): Promise<{\n name?: string;\n version?: string;\n type?: string;\n}> {\n const packageJsonPath = join(projectDir, 'package.json');\n\n if (!existsSync(packageJsonPath)) {\n return {};\n }\n\n try {\n const { readFile } = await import('fs/promises');\n const content = await readFile(packageJsonPath, 'utf-8');\n const pkg = JSON.parse(content);\n\n return {\n name: pkg.name,\n version: pkg.version,\n type: pkg.type || 'commonjs'\n };\n } catch (error) {\n logger.warn('Failed to read package.json', { error: (error as Error).message });\n return {};\n }\n}\n\n/**\n * Format bytes to human-readable string\n */\nfunction formatBytes(bytes: number): string {\n if (bytes === 0) return '0 B';\n\n const k = 1024;\n const sizes = ['B', 'KB', 'MB', 'GB'];\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n\n return `${(bytes / Math.pow(k, i)).toFixed(1)} ${sizes[i]}`;\n}\n\n/**\n * Format uptime to human-readable string\n */\nfunction formatUptime(seconds: number): string {\n const hours = Math.floor(seconds / 3600);\n const minutes = Math.floor((seconds % 3600) / 60);\n const secs = seconds % 60;\n\n const parts = [];\n if (hours > 0) parts.push(`${hours}h`);\n if (minutes > 0) parts.push(`${minutes}m`);\n if (secs > 0 || parts.length === 0) parts.push(`${secs}s`);\n\n return parts.join(' ');\n}\n","/**\n * Update Command - Check for updates and upgrade AutomatosX\n */\n\nimport type { CommandModule } from 'yargs';\nimport { exec } from 'child_process';\nimport { promisify } from 'util';\nimport chalk from 'chalk';\nimport { logger } from '../../utils/logger.js';\nimport { printError } from '../../utils/error-formatter.js';\n\nconst execAsync = promisify(exec);\n\ninterface UpdateOptions {\n check?: boolean;\n yes?: boolean;\n}\n\nexport const updateCommand: CommandModule<Record<string, unknown>, UpdateOptions> = {\n command: 'update',\n describe: 'Check for updates and upgrade AutomatosX to the latest version',\n\n builder: (yargs) => {\n return yargs\n .option('check', {\n describe: 'Only check for updates without installing',\n type: 'boolean',\n default: false\n })\n .option('yes', {\n alias: 'y',\n describe: 'Skip confirmation prompt',\n type: 'boolean',\n default: false\n })\n .example('automatosx update', 'Check and install latest version')\n .example('automatosx update --check', 'Only check for updates')\n .example('automatosx update --yes', 'Update without confirmation');\n },\n\n handler: async (argv) => {\n console.log(chalk.blue.bold('\\n🔄 AutomatosX Update Checker\\n'));\n\n try {\n // Get current version\n const currentVersion = await getCurrentVersion();\n console.log(chalk.gray(`Current version: ${currentVersion}`));\n\n // Check for latest version\n console.log(chalk.cyan('Checking for updates...'));\n const latestVersion = await getLatestVersion();\n console.log(chalk.gray(`Latest version: ${latestVersion}\\n`));\n\n // Compare versions\n if (currentVersion === latestVersion) {\n console.log(chalk.green('✅ You are already running the latest version!\\n'));\n return;\n }\n\n if (isNewer(latestVersion, currentVersion)) {\n console.log(chalk.yellow(`📦 New version available: ${currentVersion} → ${latestVersion}\\n`));\n\n // Show changelog\n await showChangelog(currentVersion, latestVersion);\n\n // If only checking, exit here\n if (argv.check) {\n console.log(chalk.gray('\\nTo install the update, run:'));\n console.log(chalk.cyan(` npm install -g @defai.digital/automatosx@${latestVersion}\\n`));\n return;\n }\n\n // Confirm update\n if (!argv.yes) {\n const readline = await import('readline');\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n });\n\n const answer = await new Promise<string>((resolve) => {\n rl.question(chalk.yellow('Would you like to update now? (y/N) '), resolve);\n });\n rl.close();\n\n if (answer.toLowerCase() !== 'y' && answer.toLowerCase() !== 'yes') {\n console.log(chalk.gray('\\nUpdate cancelled.\\n'));\n return;\n }\n }\n\n // Perform update\n console.log(chalk.cyan('\\n📥 Installing update...\\n'));\n await installUpdate(latestVersion);\n\n console.log(chalk.green.bold('\\n✅ AutomatosX updated successfully!\\n'));\n console.log(chalk.gray('New version:'), chalk.cyan(latestVersion));\n console.log(chalk.gray('\\nRun'), chalk.cyan('automatosx --version'), chalk.gray('to verify.\\n'));\n\n logger.info('AutomatosX updated', { from: currentVersion, to: latestVersion });\n\n } else {\n console.log(chalk.yellow(`⚠️ Your version (${currentVersion}) is newer than the published version (${latestVersion})\\n`));\n console.log(chalk.gray('This might happen if you are running a development version.\\n'));\n }\n\n } catch (error) {\n printError(error, {\n verbose: false,\n showCode: true,\n showSuggestions: true,\n colors: true\n });\n logger.error('Update check failed', { error: (error as Error).message });\n process.exit(1);\n }\n }\n};\n\n/**\n * Get current installed version\n */\nasync function getCurrentVersion(): Promise<string> {\n try {\n const { stdout } = await execAsync('npm list -g @defai.digital/automatosx --depth=0 --json');\n const result = JSON.parse(stdout);\n return result.dependencies['@defai.digital/automatosx']?.version || 'unknown';\n } catch (error) {\n // Fallback to package.json\n const { readFile } = await import('fs/promises');\n const { dirname, join } = await import('path');\n const { fileURLToPath } = await import('url');\n\n const __filename = fileURLToPath(import.meta.url);\n const __dirname = dirname(__filename);\n const pkgPath = join(__dirname, '../../../package.json');\n\n const content = await readFile(pkgPath, 'utf-8');\n const pkg = JSON.parse(content);\n return pkg.version;\n }\n}\n\n/**\n * Get latest version from npm registry\n */\nasync function getLatestVersion(): Promise<string> {\n const { stdout } = await execAsync('npm view @defai.digital/automatosx version');\n return stdout.trim();\n}\n\n/**\n * Check if version a is newer than version b\n */\nfunction isNewer(a: string, b: string): boolean {\n const parseVersion = (v: string) => v.split('.').map(Number);\n const [aMajor = 0, aMinor = 0, aPatch = 0] = parseVersion(a);\n const [bMajor = 0, bMinor = 0, bPatch = 0] = parseVersion(b);\n\n if (aMajor !== bMajor) return aMajor > bMajor;\n if (aMinor !== bMinor) return aMinor > bMinor;\n return aPatch > bPatch;\n}\n\n/**\n * Show changelog between versions\n */\nasync function showChangelog(from: string, to: string): Promise<void> {\n try {\n console.log(chalk.cyan('What\\'s new:\\n'));\n\n // Fetch changelog from GitHub\n const { stdout } = await execAsync(\n `curl -s https://api.github.com/repos/defai-digital/automatosx/releases/tags/v${to}`\n );\n\n const release = JSON.parse(stdout);\n\n if (release.body) {\n // Parse and display first few lines of changelog\n const lines = release.body.split('\\n').slice(0, 10);\n lines.forEach((line: string) => {\n if (line.startsWith('#')) {\n console.log(chalk.bold(line));\n } else if (line.trim()) {\n console.log(chalk.gray(line));\n }\n });\n console.log(chalk.gray('\\n...'));\n console.log(chalk.gray(`Full changelog: https://github.com/defai-digital/automatosx/releases/tag/v${to}`));\n }\n } catch (error) {\n // If changelog fetch fails, continue silently\n logger.debug('Could not fetch changelog', { error: (error as Error).message });\n }\n}\n\n/**\n * Install update using npm\n */\nasync function installUpdate(version: string): Promise<void> {\n try {\n const { stdout, stderr } = await execAsync(\n `npm install -g @defai.digital/automatosx@${version}`,\n { maxBuffer: 10 * 1024 * 1024 }\n );\n\n if (stderr && !stderr.includes('npm warn')) {\n logger.warn('Update installation warnings', { stderr });\n }\n\n logger.debug('Update installation output', { stdout });\n } catch (error) {\n throw new Error(`Failed to install update: ${(error as Error).message}`);\n }\n}\n","/**\n * Workspace Command - Manage agent workspaces\n *\n * @since v4.7.0\n */\n\nimport type { CommandModule } from 'yargs';\nimport { WorkspaceManager } from '../../core/workspace-manager.js';\nimport { createSessionManager } from '../utils/session-utils.js';\nimport chalk from 'chalk';\nimport Table from 'cli-table3';\n\ninterface WorkspaceListOptions {\n session?: string;\n json?: boolean;\n}\n\ninterface WorkspaceStatsOptions {\n json?: boolean;\n}\n\ninterface WorkspaceCleanupOptions {\n olderThan?: number;\n confirm?: boolean;\n}\n\n/**\n * Workspace List Command\n */\nconst listCommand: CommandModule<Record<string, unknown>, WorkspaceListOptions> = {\n command: 'list',\n describe: 'List workspace files',\n\n builder: (yargs) => {\n return yargs\n .option('session', {\n describe: 'Session ID to list files for',\n type: 'string'\n })\n .option('json', {\n describe: 'Output as JSON',\n type: 'boolean',\n default: false\n });\n },\n\n handler: async (argv) => {\n try {\n const { detectProjectRoot } = await import('../../core/path-resolver.js');\n const projectDir = await detectProjectRoot(process.cwd());\n const workspaceManager = new WorkspaceManager(projectDir);\n\n if (argv.session) {\n const sessionManager = await createSessionManager();\n const session = await sessionManager.getSession(argv.session);\n\n if (!session) {\n console.log(chalk.red.bold(`\\n✗ Session not found: ${argv.session}\\n`));\n process.exit(1);\n }\n\n console.log(chalk.blue.bold(`\\n📁 Session Workspace Files\\n`));\n console.log(chalk.gray(`Session: ${argv.session}`));\n console.log(chalk.gray(`Task: ${session.task}\\n`));\n\n for (const agentName of session.agents) {\n const files = await workspaceManager.listSessionFiles(argv.session, agentName);\n\n if (files.length > 0) {\n console.log(chalk.cyan(`\\n${agentName}:`));\n files.forEach(file => {\n console.log(chalk.gray(` - ${file}`));\n });\n }\n }\n\n console.log();\n } else {\n const stats = await workspaceManager.getStats();\n\n if (argv.json) {\n console.log(JSON.stringify(stats, null, 2));\n process.exit(0);\n }\n\n console.log(chalk.blue.bold('\\n📊 Workspace Statistics\\n'));\n console.log(chalk.gray(`Session workspaces: ${chalk.white(stats.totalSessions)}`));\n console.log(chalk.gray(`Agent workspaces: ${chalk.white(stats.agentWorkspaces)}`));\n console.log();\n }\n\n process.exit(0);\n } catch (error) {\n console.error(chalk.red.bold('\\n✗ Failed to list workspaces\\n'));\n console.error(chalk.red((error as Error).message));\n process.exit(1);\n }\n }\n};\n\n/**\n * Workspace Stats Command\n */\nconst statsCommand: CommandModule<Record<string, unknown>, WorkspaceStatsOptions> = {\n command: 'stats',\n describe: 'Show workspace statistics',\n\n builder: (yargs) => {\n return yargs.option('json', {\n describe: 'Output as JSON',\n type: 'boolean',\n default: false\n });\n },\n\n handler: async (argv) => {\n try {\n const { detectProjectRoot } = await import('../../core/path-resolver.js');\n const projectDir = await detectProjectRoot(process.cwd());\n const workspaceManager = new WorkspaceManager(projectDir);\n\n const stats = await workspaceManager.getStats();\n\n if (argv.json) {\n console.log(JSON.stringify(stats, null, 2));\n process.exit(0);\n }\n\n console.log(chalk.blue.bold('\\n📊 Workspace Statistics\\n'));\n console.log(chalk.gray(`Session workspaces: ${chalk.white(stats.totalSessions)}`));\n console.log(chalk.gray(`Agent workspaces: ${chalk.white(stats.agentWorkspaces)}`));\n console.log(chalk.gray(`Total size: ${chalk.white((stats.totalSizeBytes / 1024 / 1024).toFixed(2))} MB`));\n console.log();\n\n process.exit(0);\n } catch (error) {\n console.error(chalk.red.bold('\\n✗ Failed to get workspace stats\\n'));\n console.error(chalk.red((error as Error).message));\n process.exit(1);\n }\n }\n};\n\n/**\n * Workspace Cleanup Command\n */\nconst cleanupCommand: CommandModule<Record<string, unknown>, WorkspaceCleanupOptions> = {\n command: 'cleanup',\n describe: 'Clean up old session workspaces',\n\n builder: (yargs) => {\n return yargs\n .option('older-than', {\n describe: 'Clean up sessions older than N days',\n type: 'number',\n default: 7\n })\n .option('confirm', {\n describe: 'Skip confirmation prompt',\n type: 'boolean',\n default: false\n });\n },\n\n handler: async (argv) => {\n try {\n const { detectProjectRoot } = await import('../../core/path-resolver.js');\n const projectDir = await detectProjectRoot(process.cwd());\n const workspaceManager = new WorkspaceManager(projectDir);\n const sessionManager = await createSessionManager();\n\n // Get active sessions\n const activeSessions = await sessionManager.getActiveSessions();\n const activeIds = activeSessions.map(s => s.id);\n\n if (!argv.confirm) {\n console.log(chalk.yellow(`\\n⚠ This will remove workspace files for inactive sessions`));\n console.log(chalk.gray(`Active sessions (${activeIds.length}) will be kept\\n`));\n console.log(chalk.gray('Run with --confirm to proceed\\n'));\n process.exit(0);\n }\n\n const removed = await workspaceManager.cleanupSessions(activeIds);\n\n console.log(chalk.green.bold(`\\n✓ Cleanup complete\\n`));\n console.log(chalk.gray(`Removed ${removed} session workspace(s)\\n`));\n\n process.exit(0);\n } catch (error) {\n console.error(chalk.red.bold('\\n✗ Failed to cleanup workspaces\\n'));\n console.error(chalk.red((error as Error).message));\n process.exit(1);\n }\n }\n};\n\n/**\n * Main Workspace Command\n */\nexport const workspaceCommand: CommandModule = {\n command: 'workspace <command>',\n describe: 'Manage agent workspaces',\n\n builder: (yargs) => {\n return yargs\n .command(listCommand)\n .command(statsCommand)\n .command(cleanupCommand)\n .demandCommand(1, 'You must specify a workspace command')\n .help();\n },\n\n handler: () => {\n // Parent command handler (not used, subcommands handle everything)\n }\n};\n","/**\n * Agent Command - Manage agents\n * @since v5.0.0\n */\n\nimport type { CommandModule } from 'yargs';\nimport { templatesCommand } from './templates.js';\nimport { createCommand } from './create.js';\nimport { listCommand } from './list.js';\nimport { showCommand } from './show.js';\nimport { removeCommand } from './remove.js';\n\nexport const agentCommand: CommandModule = {\n command: 'agent <command>',\n describe: 'Manage agents',\n\n builder: (yargs) => {\n return yargs\n .command(templatesCommand)\n .command(createCommand)\n .command(listCommand)\n .command(showCommand)\n .command(removeCommand)\n .demandCommand(1, 'You must provide a valid subcommand')\n .help();\n },\n\n handler: () => {\n // This will never be called because we have subcommands\n // Yargs will handle showing help automatically\n }\n};\n","/**\n * Agent Templates Command - List available agent templates\n * @since v5.0.0\n */\n\nimport type { CommandModule } from 'yargs';\nimport { readdir } from 'fs/promises';\nimport { join } from 'path';\nimport { existsSync } from 'fs';\nimport chalk from 'chalk';\n\ninterface TemplateInfo {\n name: string;\n team: string;\n description: string;\n}\n\nconst TEMPLATE_DESCRIPTIONS: Record<string, TemplateInfo> = {\n 'basic-agent': {\n name: 'basic-agent',\n team: 'core',\n description: 'Basic agent with minimal configuration'\n },\n 'developer': {\n name: 'developer',\n team: 'engineering',\n description: 'Software developer (code generation, review, testing)'\n },\n 'analyst': {\n name: 'analyst',\n team: 'business',\n description: 'Business analyst (requirements, user stories, strategy)'\n },\n 'designer': {\n name: 'designer',\n team: 'design',\n description: 'UI/UX designer (interface design, user experience)'\n },\n 'qa-specialist': {\n name: 'qa-specialist',\n team: 'core',\n description: 'QA specialist (test planning, automation, quality)'\n }\n};\n\nexport const templatesCommand: CommandModule = {\n command: 'templates',\n describe: 'List available agent templates',\n\n handler: async () => {\n try {\n console.log(chalk.blue.bold('\\n📋 Available Agent Templates\\n'));\n\n // Check for templates in project directory first\n const projectTemplatesDir = join(process.cwd(), '.automatosx', 'templates');\n const hasProjectTemplates = existsSync(projectTemplatesDir);\n\n // Default templates location (package examples)\n const defaultTemplatesDir = join(__dirname, '../../../../examples/templates');\n const hasDefaultTemplates = existsSync(defaultTemplatesDir);\n\n if (!hasProjectTemplates && !hasDefaultTemplates) {\n console.log(chalk.yellow('⚠ No templates found.'));\n console.log(chalk.gray('\\nRun \"ax init\" to set up default templates.\\n'));\n return;\n }\n\n // Use project templates if available, otherwise use defaults\n const templatesDir = hasProjectTemplates ? projectTemplatesDir : defaultTemplatesDir;\n const templateSource = hasProjectTemplates ? 'Project' : 'Default';\n\n const files = await readdir(templatesDir);\n const templates = files\n .filter(f => f.endsWith('.yaml'))\n .map(f => f.replace('.yaml', ''));\n\n if (templates.length === 0) {\n console.log(chalk.yellow('⚠ No templates found.\\n'));\n return;\n }\n\n console.log(chalk.gray(`Source: ${templateSource} (${templatesDir})\\n`));\n\n // Group by team\n const byTeam: Record<string, TemplateInfo[]> = {\n core: [],\n engineering: [],\n business: [],\n design: []\n };\n\n templates.forEach(template => {\n const info = TEMPLATE_DESCRIPTIONS[template] || {\n name: template,\n team: 'core',\n description: 'Custom template'\n };\n byTeam[info.team]?.push(info);\n });\n\n // Display by team\n const teamNames = {\n core: 'Core Team',\n engineering: 'Engineering Team',\n business: 'Business Team',\n design: 'Design Team'\n };\n\n for (const [team, name] of Object.entries(teamNames)) {\n const teamTemplates = byTeam[team];\n if (teamTemplates && teamTemplates.length > 0) {\n console.log(chalk.cyan.bold(`${name}:`));\n teamTemplates.forEach(t => {\n console.log(chalk.white(` ${t.name.padEnd(20)} - ${t.description}`));\n });\n console.log();\n }\n }\n\n console.log(chalk.gray('Usage: ax agent create <name> --template <template-name>\\n'));\n\n } catch (error) {\n console.error(chalk.red.bold('\\n✗ Error listing templates\\n'));\n console.error(chalk.red((error as Error).message));\n process.exit(1);\n }\n }\n};\n","/**\n * Agent Create Command - Create agent from template\n * @since v5.0.0\n */\n\nimport type { CommandModule } from 'yargs';\nimport { readFile, writeFile, mkdir } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { join } from 'path';\nimport { load as loadYaml } from 'js-yaml';\nimport chalk from 'chalk';\nimport * as readline from 'readline';\nimport { TemplateEngine, type TemplateVariables } from '../../../agents/template-engine.js';\nimport {\n listAvailableTemplates,\n listAvailableTeams,\n isValidAgentName,\n checkDisplayNameConflict,\n suggestValidAgentName\n} from './helpers.js';\n\ninterface CreateOptions {\n agent: string;\n template?: string;\n displayName?: string;\n role?: string;\n description?: string;\n team?: string;\n interactive?: boolean;\n}\n\nexport const createCommand: CommandModule<{}, CreateOptions> = {\n command: 'create <agent>',\n describe: 'Create a new agent from template',\n\n builder: (yargs) => {\n return yargs\n .positional('agent', {\n describe: 'Agent name (lowercase letters, numbers, and hyphens)',\n type: 'string',\n demandOption: true\n })\n .option('template', {\n describe: 'Template to use (run \"ax agent templates\" to see available)',\n type: 'string',\n alias: 't'\n })\n .option('display-name', {\n describe: 'Agent display name (friendly name)',\n type: 'string',\n alias: 'd'\n })\n .option('role', {\n describe: 'Agent role',\n type: 'string',\n alias: 'r'\n })\n .option('description', {\n describe: 'Agent description',\n type: 'string'\n })\n .option('team', {\n describe: 'Team name',\n type: 'string'\n })\n .option('interactive', {\n describe: 'Interactive mode (prompt for missing values)',\n type: 'boolean',\n alias: 'i',\n default: false\n });\n },\n\n handler: async (argv) => {\n try {\n const projectDir = process.cwd();\n const agentsDir = join(projectDir, '.automatosx', 'agents');\n const agentFile = join(agentsDir, `${argv.agent}.yaml`);\n\n // 1. Validate agent name format\n const nameValidation = isValidAgentName(argv.agent);\n if (!nameValidation.valid) {\n console.log(chalk.red.bold(`\\n✗ Invalid agent name: ${argv.agent}\\n`));\n console.log(chalk.red(nameValidation.error));\n const suggestion = suggestValidAgentName(argv.agent);\n if (suggestion !== argv.agent) {\n console.log(chalk.yellow(`\\n💡 Suggested name: ${suggestion}`));\n }\n console.log(chalk.gray('\\nAgent names must:'));\n console.log(chalk.gray(' • Start with a lowercase letter'));\n console.log(chalk.gray(' • Contain only lowercase letters, numbers, and hyphens'));\n console.log(chalk.gray(' • Be 2-50 characters long'));\n console.log(chalk.gray(' • Not contain consecutive hyphens\\n'));\n process.exit(1);\n }\n\n // 2. Check if agent already exists\n if (existsSync(agentFile)) {\n console.log(chalk.red.bold(`\\n✗ Agent already exists: ${argv.agent}\\n`));\n console.log(chalk.gray('Use a different name or remove the existing agent first.\\n'));\n process.exit(1);\n }\n\n // Ensure agents directory exists\n await mkdir(agentsDir, { recursive: true });\n\n // 3. Get template name\n let templateName = argv.template;\n if (!templateName) {\n if (argv.interactive) {\n // Interactive mode: ask user to select\n templateName = await askTemplate();\n } else {\n // Non-interactive mode: use default\n templateName = 'basic-agent';\n console.log(chalk.gray(`Using default template: ${templateName}`));\n }\n }\n\n // 4. Load template\n const templatePath = await findTemplate(templateName);\n const templateContent = await readFile(templatePath, 'utf-8');\n const templateYaml = loadYaml(templateContent) as any;\n\n // 5. Collect variables\n const variables: TemplateVariables = {\n AGENT_NAME: argv.agent,\n DISPLAY_NAME: argv.displayName || '',\n ROLE: argv.role || '',\n DESCRIPTION: argv.description || '',\n TEAM: argv.team || ''\n };\n\n // 6. Interactive mode - ask for missing values\n if (argv.interactive) {\n // Only ask in interactive mode\n if (!variables.DISPLAY_NAME) {\n variables.DISPLAY_NAME = await ask('Display Name', argv.agent);\n }\n\n if (!variables.ROLE && templateYaml.role?.includes('{{')) {\n variables.ROLE = await ask('Role', extractDefault(templateYaml.role) || 'AI Assistant');\n }\n\n if (!variables.DESCRIPTION && templateYaml.description?.includes('{{')) {\n variables.DESCRIPTION = await ask(\n 'Description',\n extractDefault(templateYaml.description) || 'A helpful AI assistant'\n );\n }\n\n if (!variables.TEAM && templateYaml.team?.includes('{{')) {\n variables.TEAM = await askTeam(extractDefault(templateYaml.team) || 'core');\n }\n } else {\n // Non-interactive mode: use defaults for missing values\n if (!variables.DISPLAY_NAME) {\n variables.DISPLAY_NAME = argv.agent;\n }\n if (!variables.ROLE && templateYaml.role?.includes('{{')) {\n variables.ROLE = extractDefault(templateYaml.role) || 'AI Assistant';\n }\n if (!variables.DESCRIPTION && templateYaml.description?.includes('{{')) {\n variables.DESCRIPTION = extractDefault(templateYaml.description) || 'A helpful AI assistant';\n }\n if (!variables.TEAM && templateYaml.team?.includes('{{')) {\n variables.TEAM = extractDefault(templateYaml.team) || 'core';\n }\n }\n\n // 7. Check displayName conflicts\n if (variables.DISPLAY_NAME) {\n const conflict = await checkDisplayNameConflict(variables.DISPLAY_NAME);\n if (conflict) {\n console.log(chalk.red.bold(`\\n✗ DisplayName conflict: \"${variables.DISPLAY_NAME}\" is already used by agent \"${conflict}\"\\n`));\n console.log(chalk.gray('Please choose a different displayName.\\n'));\n process.exit(1);\n }\n }\n\n // 8. Render template\n const engine = new TemplateEngine();\n const rendered = engine.render(templateContent, variables);\n\n // 9. Write agent file\n await writeFile(agentFile, rendered, 'utf-8');\n\n // 10. Success message\n console.log(chalk.green.bold(`\\n✓ Agent '${argv.agent}' created successfully\\n`));\n console.log(chalk.white(`Display Name: ${chalk.cyan(variables.DISPLAY_NAME)}`));\n console.log(chalk.white(`Team: ${chalk.cyan(variables.TEAM || 'core')}`));\n console.log(chalk.white(`Template: ${chalk.gray(templateName)}`));\n console.log(chalk.white(`File: ${chalk.gray(agentFile)}`));\n console.log();\n console.log(chalk.gray('Next steps:'));\n console.log(chalk.gray(' • View details: ax agent show ' + argv.agent));\n console.log(chalk.gray(' • Run agent: ax run ' + argv.agent + ' \"your task\"'));\n console.log(chalk.gray(' • Edit file: Open ' + agentFile + ' in your editor'));\n console.log();\n\n } catch (error) {\n console.error(chalk.red.bold('\\n✗ Error creating agent\\n'));\n console.error(chalk.red((error as Error).message));\n if ((error as Error).stack) {\n console.error(chalk.gray((error as Error).stack));\n }\n process.exit(1);\n }\n }\n};\n\n/**\n * Find template file\n */\nasync function findTemplate(name: string): Promise<string> {\n // Check project templates first\n const projectTemplate = join(process.cwd(), '.automatosx', 'templates', `${name}.yaml`);\n if (existsSync(projectTemplate)) {\n return projectTemplate;\n }\n\n // Check default templates\n const defaultTemplate = join(__dirname, '../../../../examples/templates', `${name}.yaml`);\n if (existsSync(defaultTemplate)) {\n return defaultTemplate;\n }\n\n throw new Error(`Template not found: ${name}\\nRun \"ax agent templates\" to see available templates.`);\n}\n\n/**\n * Ask for template selection\n */\nasync function askTemplate(): Promise<string> {\n const templates = await listAvailableTemplates();\n\n if (templates.length === 0) {\n throw new Error('No templates available. Please run \"ax init\" first.');\n }\n\n console.log(chalk.blue.bold('\\n📋 Available Templates:\\n'));\n templates.forEach((template, index) => {\n const desc = template.description || 'Custom template';\n console.log(chalk.white(` ${index + 1}. ${template.name.padEnd(20)} - ${desc}`));\n });\n console.log();\n\n const answer = await ask(`Select template (1-${templates.length})`, '1');\n const index = parseInt(answer) - 1;\n\n if (index >= 0 && index < templates.length) {\n return templates[index]?.name ?? templates[0]!.name;\n }\n\n return templates[0]!.name;\n}\n\n/**\n * Ask for team selection\n */\nasync function askTeam(defaultValue: string): Promise<string> {\n const teams = await listAvailableTeams();\n\n if (teams.length === 0) {\n throw new Error('No teams available. Please run \"ax init\" first.');\n }\n\n console.log(chalk.blue.bold('\\n👥 Available Teams:\\n'));\n teams.forEach((team, index) => {\n const desc = team.description || team.displayName;\n console.log(chalk.white(` ${index + 1}. ${team.name.padEnd(12)} - ${desc}`));\n });\n console.log();\n\n const defaultIndex = teams.findIndex(t => t.name === defaultValue) + 1;\n const answer = await ask(`Select team (1-${teams.length})`, defaultIndex > 0 ? defaultIndex.toString() : '1');\n const index = parseInt(answer) - 1;\n\n if (index >= 0 && index < teams.length) {\n return teams[index]?.name ?? defaultValue ?? 'core';\n }\n\n return defaultValue || teams[0]?.name || 'core';\n}\n\n/**\n * Extract default value from template variable\n */\nfunction extractDefault(value: string): string | undefined {\n if (!value || !value.includes('default:')) return undefined;\n\n const match = value.match(/default:\\s*([^}]+)/);\n return match?.[1]?.trim();\n}\n\n/**\n * Ask user for input\n */\nfunction ask(question: string, defaultValue?: string): Promise<string> {\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n });\n\n const prompt = defaultValue\n ? `${question} [${chalk.gray(defaultValue)}]: `\n : `${question}: `;\n\n return new Promise(resolve => {\n rl.question(prompt, answer => {\n rl.close();\n resolve(answer.trim() || defaultValue || '');\n });\n });\n}\n","/**\n * Agent Template Engine - v5.0+\n *\n * Provides variable substitution for agent templates.\n * Supports:\n * - Simple variables: {{AGENT_NAME}}\n * - Default values: {{ROLE | default: Software Developer}}\n * - Nested objects and arrays\n *\n * @module agents/template-engine\n * @since v5.0.0\n */\n\n/**\n * Template variables for agent creation\n */\nexport interface TemplateVariables {\n /** Agent name (required) */\n AGENT_NAME: string;\n\n /** Display name (required) */\n DISPLAY_NAME: string;\n\n /** Agent role (optional) */\n ROLE?: string;\n\n /** Agent description (optional) */\n DESCRIPTION?: string;\n\n /** Team name (optional) */\n TEAM?: string;\n\n /** Additional custom variables */\n [key: string]: string | undefined;\n}\n\n/**\n * Template Engine for agent configuration\n *\n * @example\n * ```typescript\n * const engine = new TemplateEngine();\n * const result = engine.render(template, {\n * AGENT_NAME: 'backend-api',\n * DISPLAY_NAME: 'Bob',\n * ROLE: 'Senior Backend Engineer'\n * });\n * ```\n */\nexport class TemplateEngine {\n /**\n * Regex for variable placeholders: {{VAR_NAME}} or {{VAR_NAME | default: value}}\n */\n private static readonly VARIABLE_REGEX = /\\{\\{([^}|]+)(?:\\s*\\|\\s*default:\\s*([^}]+))?\\}\\}/g;\n\n /**\n * Render template with variables\n *\n * @param template - Template string with {{VARIABLE}} placeholders\n * @param variables - Variables to substitute\n * @returns Rendered string\n *\n * @example\n * ```typescript\n * const result = engine.render(\n * 'Hello {{NAME | default: World}}!',\n * { NAME: 'Alice' }\n * );\n * // Result: \"Hello Alice!\"\n * ```\n */\n render(template: string, variables: TemplateVariables): string {\n return template.replace(\n TemplateEngine.VARIABLE_REGEX,\n (match, varName, defaultValue) => {\n const trimmedName = varName.trim();\n const value = variables[trimmedName];\n\n // Use provided value, or default, or keep original placeholder\n if (value !== undefined && value !== null) {\n return value;\n }\n\n if (defaultValue !== undefined) {\n return defaultValue.trim();\n }\n\n // Keep original placeholder if no value and no default\n return match;\n }\n );\n }\n\n /**\n * Render template object (YAML content parsed as object)\n *\n * Recursively processes all string values in the object.\n *\n * @param obj - Object to render (parsed YAML)\n * @param variables - Variables to substitute\n * @returns Rendered object\n *\n * @example\n * ```typescript\n * const template = {\n * name: '{{AGENT_NAME}}',\n * role: '{{ROLE | default: Developer}}'\n * };\n * const result = engine.renderObject(template, { AGENT_NAME: 'backend' });\n * // Result: { name: 'backend', role: 'Developer' }\n * ```\n */\n renderObject<T extends Record<string, any>>(\n obj: T,\n variables: TemplateVariables\n ): T {\n const result: any = Array.isArray(obj) ? [] : {};\n\n for (const key in obj) {\n const value = obj[key];\n\n if (typeof value === 'string') {\n // Render string values\n result[key] = this.render(value, variables);\n } else if (typeof value === 'object' && value !== null) {\n // Recursively render nested objects/arrays\n result[key] = this.renderObject(value, variables);\n } else {\n // Keep other types as-is\n result[key] = value;\n }\n }\n\n return result as T;\n }\n\n /**\n * Validate that all required variables are provided\n *\n * @param template - Template string\n * @param variables - Provided variables\n * @returns Array of missing required variable names\n *\n * @example\n * ```typescript\n * const missing = engine.validateVariables(\n * 'Name: {{NAME}}, Role: {{ROLE | default: Dev}}',\n * { ROLE: 'Engineer' }\n * );\n * // Result: ['NAME'] (ROLE is optional because it has default)\n * ```\n */\n validateVariables(\n template: string,\n variables: TemplateVariables\n ): string[] {\n const missing: string[] = [];\n const regex = new RegExp(TemplateEngine.VARIABLE_REGEX, 'g');\n\n let match: RegExpExecArray | null;\n while ((match = regex.exec(template)) !== null) {\n if (!match[1]) continue; // Skip if capture group is missing\n const varName = match[1].trim();\n const hasDefault = match[2] !== undefined;\n\n // Required if no default value and not provided\n if (!hasDefault && variables[varName] === undefined) {\n if (!missing.includes(varName)) {\n missing.push(varName);\n }\n }\n }\n\n return missing;\n }\n\n /**\n * Extract all variable names from template\n *\n * @param template - Template string\n * @returns Array of variable names (without {{}} and defaults)\n *\n * @example\n * ```typescript\n * const vars = engine.extractVariables('{{NAME}} and {{ROLE | default: Dev}}');\n * // Result: ['NAME', 'ROLE']\n * ```\n */\n extractVariables(template: string): string[] {\n const variables: string[] = [];\n const regex = new RegExp(TemplateEngine.VARIABLE_REGEX, 'g');\n\n let match: RegExpExecArray | null;\n while ((match = regex.exec(template)) !== null) {\n if (!match[1]) continue; // Skip if capture group is missing\n const varName = match[1].trim();\n if (!variables.includes(varName)) {\n variables.push(varName);\n }\n }\n\n return variables;\n }\n}\n\n/**\n * Singleton instance for convenience\n */\nexport const templateEngine = new TemplateEngine();\n","/**\n * Agent Command Helpers\n * Shared utilities for agent commands\n */\n\nimport { readdir } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { join, extname, dirname } from 'path';\nimport { fileURLToPath } from 'url';\nimport { ProfileLoader } from '../../../agents/profile-loader.js';\nimport { TeamManager } from '../../../core/team-manager.js';\nimport { logger } from '../../../utils/logger.js';\n\n// Get the directory of this file for ESM compatibility\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\n/**\n * Template information\n */\nexport interface TemplateInfo {\n name: string;\n path: string;\n description?: string;\n team?: string;\n}\n\n/**\n * Team information\n */\nexport interface TeamInfo {\n name: string;\n displayName: string;\n description?: string;\n}\n\n/**\n * List available templates (project + built-in)\n */\nexport async function listAvailableTemplates(): Promise<TemplateInfo[]> {\n const templates: TemplateInfo[] = [];\n\n // 1. Check project templates (.automatosx/templates/)\n const projectTemplatesDir = join(process.cwd(), '.automatosx', 'templates');\n if (existsSync(projectTemplatesDir)) {\n try {\n const files = await readdir(projectTemplatesDir);\n for (const file of files) {\n if (extname(file) === '.yaml' || extname(file) === '.yml') {\n const name = file.replace(/\\.(yaml|yml)$/, '');\n templates.push({\n name,\n path: join(projectTemplatesDir, file),\n description: 'Custom template'\n });\n }\n }\n } catch (error) {\n logger.debug('Failed to read project templates', { error });\n }\n }\n\n // 2. Check built-in templates (examples/templates/)\n // Note: In production, this should resolve to the correct path\n const builtinTemplatesDir = join(__dirname, '../../../../examples/templates');\n if (existsSync(builtinTemplatesDir)) {\n try {\n const files = await readdir(builtinTemplatesDir);\n for (const file of files) {\n if (extname(file) === '.yaml' || extname(file) === '.yml') {\n const name = file.replace(/\\.(yaml|yml)$/, '');\n\n // Skip if already added from project templates\n if (templates.find(t => t.name === name)) {\n continue;\n }\n\n // Map built-in templates to descriptions\n const descriptions: Record<string, string> = {\n 'basic-agent': 'Basic agent (core team)',\n 'developer': 'Software developer (engineering)',\n 'analyst': 'Business analyst (business)',\n 'designer': 'UI/UX designer (design)',\n 'qa-specialist': 'QA specialist (core)'\n };\n\n templates.push({\n name,\n path: join(builtinTemplatesDir, file),\n description: descriptions[name] || 'Built-in template'\n });\n }\n }\n } catch (error) {\n logger.debug('Failed to read built-in templates', { error });\n }\n }\n\n return templates.sort((a, b) => a.name.localeCompare(b.name));\n}\n\n/**\n * List available teams\n */\nexport async function listAvailableTeams(): Promise<TeamInfo[]> {\n const projectDir = process.cwd();\n const teamsDir = join(projectDir, '.automatosx', 'teams');\n\n const teamManager = new TeamManager(teamsDir);\n\n try {\n const teamNames = await teamManager.listTeams();\n const teams: TeamInfo[] = [];\n\n for (const name of teamNames) {\n try {\n const teamConfig = await teamManager.loadTeam(name);\n teams.push({\n name: teamConfig.name,\n displayName: teamConfig.displayName || teamConfig.name,\n description: teamConfig.description\n });\n } catch (error) {\n // If team fails to load, add basic info\n teams.push({\n name,\n displayName: name,\n description: undefined\n });\n }\n }\n\n return teams.sort((a, b) => a.name.localeCompare(b.name));\n } catch (error) {\n logger.warn('Failed to list teams, using defaults', { error });\n\n // Return default teams if listing fails\n return [\n { name: 'core', displayName: 'Core Team', description: 'Quality assurance, core functions' },\n { name: 'engineering', displayName: 'Engineering Team', description: 'Software development' },\n { name: 'business', displayName: 'Business Team', description: 'Business analysis, product' },\n { name: 'design', displayName: 'Design Team', description: 'UI/UX design' }\n ];\n }\n}\n\n/**\n * Validate agent name format\n * Rules:\n * - Only lowercase letters, numbers, and hyphens\n * - Must start with a letter\n * - No consecutive hyphens\n * - Length: 2-50 characters\n */\nexport function isValidAgentName(name: string): { valid: boolean; error?: string } {\n if (!name || typeof name !== 'string') {\n return { valid: false, error: 'Agent name is required' };\n }\n\n if (name.length < 2) {\n return { valid: false, error: 'Agent name must be at least 2 characters' };\n }\n\n if (name.length > 50) {\n return { valid: false, error: 'Agent name must be at most 50 characters' };\n }\n\n if (!/^[a-z]/.test(name)) {\n return { valid: false, error: 'Agent name must start with a lowercase letter' };\n }\n\n if (!/^[a-z0-9-]+$/.test(name)) {\n return {\n valid: false,\n error: 'Agent name must contain only lowercase letters, numbers, and hyphens'\n };\n }\n\n if (/--/.test(name)) {\n return { valid: false, error: 'Agent name cannot contain consecutive hyphens' };\n }\n\n if (name.endsWith('-')) {\n return { valid: false, error: 'Agent name cannot end with a hyphen' };\n }\n\n return { valid: true };\n}\n\n/**\n * Check if displayName conflicts with existing agents\n * Returns the conflicting agent name if found, undefined otherwise\n */\nexport async function checkDisplayNameConflict(\n displayName: string,\n excludeAgentName?: string\n): Promise<string | undefined> {\n if (!displayName) {\n return undefined;\n }\n\n const projectDir = process.cwd();\n const agentsDir = join(projectDir, '.automatosx', 'agents');\n const profileLoader = new ProfileLoader(agentsDir);\n\n try {\n // Build displayName map\n const allProfiles = await profileLoader.listProfiles();\n\n for (const profileName of allProfiles) {\n // Skip the agent we're updating (if provided)\n if (excludeAgentName && profileName === excludeAgentName) {\n continue;\n }\n\n try {\n const profile = await profileLoader.loadProfile(profileName);\n\n // Check if displayName matches (case-insensitive)\n if (profile.displayName?.toLowerCase() === displayName.toLowerCase()) {\n return profileName;\n }\n } catch (error) {\n // Skip profiles that fail to load\n logger.debug('Failed to load profile for displayName check', {\n profile: profileName,\n error\n });\n }\n }\n\n return undefined;\n } catch (error) {\n logger.warn('Failed to check displayName conflicts', { error });\n return undefined;\n }\n}\n\n/**\n * Suggest valid agent name from invalid input\n */\nexport function suggestValidAgentName(input: string): string {\n let suggestion = input.toLowerCase();\n\n // Replace invalid characters with hyphens\n suggestion = suggestion.replace(/[^a-z0-9-]/g, '-');\n\n // Remove consecutive hyphens\n suggestion = suggestion.replace(/-+/g, '-');\n\n // Remove leading/trailing hyphens\n suggestion = suggestion.replace(/^-+|-+$/g, '');\n\n // Minimum length check before adding prefix\n if (suggestion.length < 2) {\n return 'agent';\n }\n\n // Ensure it starts with a letter\n if (!/^[a-z]/.test(suggestion)) {\n suggestion = 'agent-' + suggestion;\n }\n\n // Limit length\n if (suggestion.length > 50) {\n suggestion = suggestion.substring(0, 50).replace(/-+$/, '');\n }\n\n return suggestion;\n}\n","/**\n * Agent List Command - List all agents\n * @since v5.0.0\n */\n\nimport type { CommandModule } from 'yargs';\nimport { ProfileLoader } from '../../../agents/profile-loader.js';\nimport { TeamManager } from '../../../core/team-manager.js';\nimport { join } from 'path';\nimport chalk from 'chalk';\n\ninterface ListOptions {\n byTeam?: string;\n}\n\nexport const listCommand: CommandModule<{}, ListOptions> = {\n command: 'list',\n describe: 'List all agents',\n\n builder: (yargs) => {\n return yargs\n .option('by-team', {\n describe: 'Filter agents by team',\n type: 'string',\n choices: ['core', 'engineering', 'business', 'design', 'research']\n });\n },\n\n handler: async (argv) => {\n try {\n const projectDir = process.cwd();\n const agentsDir = join(projectDir, '.automatosx', 'agents');\n const teamsDir = join(projectDir, '.automatosx', 'teams');\n\n // Initialize managers\n const teamManager = new TeamManager(teamsDir);\n const profileLoader = new ProfileLoader(agentsDir, undefined, teamManager);\n\n // List all agents\n const agentNames = await profileLoader.listProfiles();\n\n if (agentNames.length === 0) {\n console.log(chalk.yellow('\\n⚠ No agents found.\\n'));\n console.log(chalk.gray('Run \"ax agent create\" to create your first agent.\\n'));\n return;\n }\n\n console.log(chalk.blue.bold(`\\n🤖 Agents (${agentNames.length} total)\\n`));\n\n // Load all profiles\n const profiles = await Promise.all(\n agentNames.map(async name => {\n try {\n return await profileLoader.loadProfile(name);\n } catch (error) {\n return null;\n }\n })\n );\n\n // Group by team\n const byTeam: Record<string, typeof profiles> = {\n core: [],\n engineering: [],\n business: [],\n design: [],\n research: [],\n other: []\n };\n\n profiles.forEach(profile => {\n if (!profile) return;\n const team = profile.team || 'other';\n if (byTeam[team]) {\n byTeam[team]?.push(profile);\n } else {\n byTeam.other?.push(profile);\n }\n });\n\n // Filter by team if specified\n const teamsToShow = argv.byTeam\n ? [argv.byTeam]\n : ['core', 'engineering', 'business', 'design', 'research', 'other'];\n\n const teamNames: Record<string, string> = {\n core: 'Core Team',\n engineering: 'Engineering Team',\n business: 'Business Team',\n design: 'Design Team',\n research: 'Research Team',\n other: 'Other'\n };\n\n // Display by team\n for (const team of teamsToShow) {\n const teamAgents = byTeam[team];\n if (teamAgents && teamAgents.length > 0) {\n console.log(chalk.cyan.bold(`${teamNames[team]} (${teamAgents.length}):`));\n\n teamAgents.forEach(profile => {\n if (!profile) return;\n const displayName = profile.displayName ? ` (${profile.displayName})` : '';\n const role = profile.role ? chalk.gray(` - ${profile.role}`) : '';\n console.log(chalk.white(` ${profile.name}${displayName}${role}`));\n });\n\n console.log();\n }\n }\n\n console.log(chalk.gray('Usage: ax agent show <name> for details\\n'));\n\n } catch (error) {\n console.error(chalk.red.bold('\\n✗ Error listing agents\\n'));\n console.error(chalk.red((error as Error).message));\n process.exit(1);\n }\n }\n};\n","/**\n * Agent Show Command - Show agent details\n * @since v5.0.0\n */\n\nimport type { CommandModule } from 'yargs';\nimport { ProfileLoader } from '../../../agents/profile-loader.js';\nimport { TeamManager } from '../../../core/team-manager.js';\nimport { join } from 'path';\nimport chalk from 'chalk';\n\ninterface ShowOptions {\n agent: string;\n}\n\nexport const showCommand: CommandModule<{}, ShowOptions> = {\n command: 'show <agent>',\n describe: 'Show agent details',\n\n builder: (yargs) => {\n return yargs\n .positional('agent', {\n describe: 'Agent name',\n type: 'string',\n demandOption: true\n });\n },\n\n handler: async (argv) => {\n try {\n const projectDir = process.cwd();\n const agentsDir = join(projectDir, '.automatosx', 'agents');\n const teamsDir = join(projectDir, '.automatosx', 'teams');\n\n // Initialize managers\n const teamManager = new TeamManager(teamsDir);\n const profileLoader = new ProfileLoader(agentsDir, undefined, teamManager);\n\n // Resolve agent name (supports displayName)\n const resolvedName = await profileLoader.resolveAgentName(argv.agent);\n\n // Load profile using resolved name\n const profile = await profileLoader.loadProfile(resolvedName);\n\n console.log(chalk.blue.bold(`\\n🤖 Agent: ${profile.name}\\n`));\n\n // Basic info\n if (profile.displayName) {\n console.log(chalk.white(`Display Name: ${chalk.cyan(profile.displayName)}`));\n }\n if (profile.team) {\n console.log(chalk.white(`Team: ${chalk.cyan(profile.team)}`));\n }\n if (profile.role) {\n console.log(chalk.white(`Role: ${chalk.gray(profile.role)}`));\n }\n if (profile.description) {\n console.log(chalk.white(`Description: ${chalk.gray(profile.description)}`));\n }\n\n console.log();\n\n // Abilities\n if (profile.abilities && profile.abilities.length > 0) {\n console.log(chalk.cyan.bold('Abilities:'));\n profile.abilities.forEach(ability => {\n console.log(chalk.white(` • ${ability}`));\n });\n console.log();\n }\n\n // Configuration\n console.log(chalk.cyan.bold('Configuration:'));\n if (profile.provider) {\n console.log(chalk.white(` Provider: ${profile.provider}`));\n }\n if (profile.model) {\n console.log(chalk.white(` Model: ${profile.model}`));\n }\n if (profile.temperature !== undefined) {\n console.log(chalk.white(` Temperature: ${profile.temperature}`));\n }\n if (profile.maxTokens !== undefined) {\n console.log(chalk.white(` Max Tokens: ${profile.maxTokens}`));\n }\n console.log();\n\n // Orchestration\n if (profile.orchestration) {\n console.log(chalk.cyan.bold('Orchestration:'));\n\n const orch = profile.orchestration;\n\n if (orch.maxDelegationDepth !== undefined) {\n console.log(chalk.white(` Max Delegation Depth: ${orch.maxDelegationDepth}`));\n }\n\n if (orch.canReadWorkspaces && orch.canReadWorkspaces.length > 0) {\n console.log(chalk.white(` Can Read Workspaces: ${orch.canReadWorkspaces.join(', ')}`));\n }\n\n if (orch.canWriteToShared !== undefined) {\n console.log(chalk.white(` Can Write to Shared: ${orch.canWriteToShared ? 'Yes' : 'No'}`));\n }\n\n console.log();\n }\n\n // File location\n const filePath = join(agentsDir, `${argv.agent}.yaml`);\n console.log(chalk.gray(`File: ${filePath}`));\n console.log();\n\n } catch (error) {\n console.error(chalk.red.bold(`\\n✗ Agent not found: ${argv.agent}\\n`));\n console.error(chalk.red((error as Error).message));\n\n // Try to suggest similar agents\n try {\n const projectDir = process.cwd();\n const agentsDir = join(projectDir, '.automatosx', 'agents');\n const teamsDir = join(projectDir, '.automatosx', 'teams');\n const teamManager = new TeamManager(teamsDir);\n const profileLoader = new ProfileLoader(agentsDir, undefined, teamManager);\n\n const suggestions = await profileLoader.findSimilarAgents(argv.agent, 3);\n const closeSuggestions = suggestions.filter(s => s.distance <= 3);\n\n if (closeSuggestions.length > 0) {\n console.log(chalk.yellow('\\n💡 Did you mean:\\n'));\n closeSuggestions.forEach((s, i) => {\n const displayInfo = s.displayName ? `${s.displayName} (${s.name})` : s.name;\n const roleInfo = s.role ? ` - ${s.role}` : '';\n console.log(chalk.cyan(` ${i + 1}. ${displayInfo}${roleInfo}`));\n });\n console.log();\n } else {\n console.log(chalk.gray('\\nRun \"ax agent list\" to see available agents.\\n'));\n }\n } catch {\n console.log(chalk.gray('\\nRun \"ax agent list\" to see available agents.\\n'));\n }\n\n process.exit(1);\n }\n }\n};\n","/**\n * Agent Remove Command - Remove an agent\n * @since v5.0.0\n */\n\nimport type { CommandModule } from 'yargs';\nimport { unlink } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { join } from 'path';\nimport chalk from 'chalk';\nimport * as readline from 'readline';\nimport { ProfileLoader } from '../../../agents/profile-loader.js';\nimport { TeamManager } from '../../../core/team-manager.js';\n\ninterface RemoveOptions {\n agent: string;\n confirm?: boolean;\n}\n\nexport const removeCommand: CommandModule<{}, RemoveOptions> = {\n command: 'remove <agent>',\n describe: 'Remove an agent',\n aliases: ['rm', 'delete'],\n\n builder: (yargs) => {\n return yargs\n .positional('agent', {\n describe: 'Agent name',\n type: 'string',\n demandOption: true\n })\n .option('confirm', {\n describe: 'Skip confirmation prompt',\n type: 'boolean',\n alias: 'y'\n });\n },\n\n handler: async (argv) => {\n try {\n const projectDir = process.cwd();\n const agentsDir = join(projectDir, '.automatosx', 'agents');\n const teamsDir = join(projectDir, '.automatosx', 'teams');\n\n // Initialize managers\n const teamManager = new TeamManager(teamsDir);\n const profileLoader = new ProfileLoader(agentsDir, undefined, teamManager);\n\n // Resolve agent name (supports displayName)\n let resolvedName: string;\n try {\n resolvedName = await profileLoader.resolveAgentName(argv.agent);\n } catch (error) {\n console.log(chalk.red.bold(`\\n✗ Agent not found: ${argv.agent}\\n`));\n\n // Try to suggest similar agents\n try {\n const suggestions = await profileLoader.findSimilarAgents(argv.agent, 3);\n const closeSuggestions = suggestions.filter(s => s.distance <= 3);\n\n if (closeSuggestions.length > 0) {\n console.log(chalk.yellow('💡 Did you mean:\\n'));\n closeSuggestions.forEach((s, i) => {\n const displayInfo = s.displayName ? `${s.displayName} (${s.name})` : s.name;\n const roleInfo = s.role ? ` - ${s.role}` : '';\n console.log(chalk.cyan(` ${i + 1}. ${displayInfo}${roleInfo}`));\n });\n console.log();\n } else {\n console.log(chalk.gray('Run \"ax agent list\" to see available agents.\\n'));\n }\n } catch {\n console.log(chalk.gray('Run \"ax agent list\" to see available agents.\\n'));\n }\n\n process.exit(1);\n }\n\n const agentFile = join(agentsDir, `${resolvedName}.yaml`);\n\n // Check if agent file exists\n if (!existsSync(agentFile)) {\n console.log(chalk.red.bold(`\\n✗ Agent file not found: ${resolvedName}\\n`));\n console.log(chalk.gray('Run \"ax agent list\" to see available agents.\\n'));\n process.exit(1);\n }\n\n // Load profile to get display name for confirmation message\n const profile = await profileLoader.loadProfile(resolvedName);\n const displayInfo = profile.displayName ? `${profile.displayName} (${resolvedName})` : resolvedName;\n\n // Confirm deletion\n if (!argv.confirm) {\n const confirmed = await askConfirmation(\n `Are you sure you want to remove agent '${chalk.cyan(displayInfo)}'?`\n );\n\n if (!confirmed) {\n console.log(chalk.yellow('\\nCancelled.\\n'));\n process.exit(0);\n }\n }\n\n // Remove file\n await unlink(agentFile);\n\n console.log(chalk.green.bold(`\\n✓ Agent '${displayInfo}' removed successfully\\n`));\n console.log(chalk.gray(`Deleted: ${agentFile}\\n`));\n\n } catch (error) {\n console.error(chalk.red.bold('\\n✗ Error removing agent\\n'));\n console.error(chalk.red((error as Error).message));\n process.exit(1);\n }\n }\n};\n\n/**\n * Ask for user confirmation\n */\nfunction askConfirmation(question: string): Promise<boolean> {\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n });\n\n return new Promise(resolve => {\n rl.question(chalk.yellow(`\\n${question} (y/N): `), answer => {\n rl.close();\n resolve(answer.toLowerCase() === 'y' || answer.toLowerCase() === 'yes');\n });\n });\n}\n"],"mappings":";;;;;;;;;;;;AACA,OAAO,UAAU;AACjB,SAAS,qBAAqB;AAF9B,IAIM,aACA,YAEO;AAPb;AAAA;AAAA;AAIA,IAAM,cAAc,MAAM,cAAc,YAAY,GAAG;AACvD,IAAM,aAAa,MAAM,KAAK,QAAQ,YAAY,CAAC;AAE5C,IAAM,YAA4B,2BAAW;AAAA;AAAA;;;ACMpD,SAAoB,YAAY,aAAa;AAC7C,SAAS,kBAAkB;AAC3B,SAAS,eAAe;AAyCxB,SAAS,eAAe,KAAU,WAAW,GAAG,eAAe,GAAQ;AAErE,MAAI,eAAe,UAAU;AAC3B,WAAO;AAAA,EACT;AAGA,MAAI,QAAQ,QAAQ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AAQ;AACf,UAAQ,IAAI,yBAAyB,KAAK;AAC1C,SAAO,MAAM,0BAA0B,EAAE,MAAM,KAAK,OAAO,CAAC;AAC9D;AAGA,IAAI,KAAK,OAAO;AACd,SAAO,MAAM,0BAA0B;AAAA,IACrC,SAASA;AAAA,IACT,SAAS,KAAK,EAAE,CAAC;AAAA,IACjB,SAAS;AAAA,MACP,OAAO,KAAK;AAAA,MACZ,OAAO,KAAK;AAAA,MACZ,QAAQ,KAAK;AAAA,IACf;AAAA,EACF,CAAC;AACH;AAEA,cAAc,KAAK,mBAAmB;AACtC,cAAc,QAAQ,iBAAiB,uBAAuB,mBAAmB;AAGjF,cAAc,KAAK,WAAW;AAC9B,cAAc,QAAQ,eAAe,aAAa,WAAW;AAG7D,IAAI,cAAc,UAAU,KAAK,KAAK,OAAO;AAC3C,UAAQ,MAAM,OAAO,cAAc,eAAe,IAAI,IAAI;AAC5D;","names":["PathError","resolve","dirname","path","PathError","resolve","resolve","resolve","resolve","createRequire","resolve","chalk","path","chalk","chalk","chalk","writeFile","existsSync","path","existsSync","path","validateConfig","writeFile","yargs","argv","resolve","fs","chalk","path","mkdir","writeFile","access","resolve","join","dirname","fileURLToPath","constants","chalk","__filename","fileURLToPath","__dirname","dirname","join","yargs","argv","resolve","chalk","checkExists","path","access","constants","mkdir","readdir","copyFile","writeFile","readFile","join","chalk","yargs","argv","existsSync","load","readFile","createRequire","join","existsSync","dirname","dirname","existsSync","deletedCount","mkdir","writeFile","readFile","readFile","writeFile","mkdir","dirname","mkdir","dirname","writeFile","readFile","path","path","mkdir","join","resolve","join","resolve","mkdir","provider","readFile","readdir","join","extname","dirname","fileURLToPath","load","__filename","fileURLToPath","__dirname","dirname","getPackageRoot","join","readdir","extname","readFile","load","readFile","readdir","join","extname","basename","dirname","fileURLToPath","__filename","__dirname","getPackageRoot","readFile","readdir","join","extname","basename","load","join","readFile","load","readdir","extname","basename","randomUUID","chalk","resolve","resolve","isAbsolute","sep","path","isAbsolute","resolve","sep","require","formatBytes","resolve","basename","basename","resolve","path","resolve","basename","basename","resolve","path","formatBytes","require","createRequire","join","ClaudeProvider","GeminiProvider","OpenAIProvider","yargs","argv","resolve","chalk","ora","chalk","path","resolve","yargs","argv","chalk","createInterface","listCommand","chalk","ora","result","chalk","totalDuration","totalTokens","chalk","join","mkdir","chalk","yargs","argv","chalk","join","mkdir","resolve","join","chalk","Table","yargs","argv","listCommand","chalk","existsSync","readdir","join","createRequire","require","createRequire","statusCommand","yargs","argv","join","existsSync","chalk","readdir","readFile","chalk","yargs","argv","chalk","readline","resolve","readFile","dirname","join","fileURLToPath","__filename","__dirname","chalk","listCommand","yargs","argv","detectProjectRoot","statsCommand","readdir","join","existsSync","chalk","readFile","writeFile","mkdir","existsSync","join","loadYaml","chalk","readdir","existsSync","join","extname","dirname","fileURLToPath","__filename","fileURLToPath","__dirname","dirname","join","existsSync","readdir","extname","createCommand","yargs","argv","join","chalk","existsSync","mkdir","readFile","loadYaml","writeFile","index","resolve","join","chalk","listCommand","yargs","argv","join","chalk","yargs","argv","unlink","existsSync","join","chalk","readline","yargs","argv","join","chalk","displayInfo","existsSync","unlink","resolve","yargs","createCommand","listCommand","require","createRequire","VERSION","statusCommand"]}