juno-code 1.0.49 → 1.0.51

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 (33) hide show
  1. package/README.md +508 -202
  2. package/dist/bin/cli.d.mts +1 -1
  3. package/dist/bin/cli.d.ts +1 -1
  4. package/dist/bin/cli.js +3332 -1421
  5. package/dist/bin/cli.js.map +1 -1
  6. package/dist/bin/cli.mjs +3316 -1405
  7. package/dist/bin/cli.mjs.map +1 -1
  8. package/dist/bin/feedback-collector.js.map +1 -1
  9. package/dist/bin/feedback-collector.mjs.map +1 -1
  10. package/dist/index.d.mts +56 -19
  11. package/dist/index.d.ts +56 -19
  12. package/dist/index.js +240 -36
  13. package/dist/index.js.map +1 -1
  14. package/dist/index.mjs +240 -36
  15. package/dist/index.mjs.map +1 -1
  16. package/dist/templates/scripts/install_requirements.sh +55 -5
  17. package/dist/templates/scripts/kanban.sh +11 -0
  18. package/dist/templates/services/README.md +23 -4
  19. package/dist/templates/services/__pycache__/pi.cpython-313.pyc +0 -0
  20. package/dist/templates/services/pi.py +1933 -262
  21. package/dist/templates/skills/claude/kanban-workflow/SKILL.md +138 -0
  22. package/dist/templates/skills/claude/plan-kanban-tasks/SKILL.md +1 -1
  23. package/dist/templates/skills/claude/ralph-loop/scripts/kanban.sh +11 -0
  24. package/dist/templates/skills/claude/understand-project/SKILL.md +1 -1
  25. package/dist/templates/skills/codex/kanban-workflow/SKILL.md +139 -0
  26. package/dist/templates/skills/codex/plan-kanban-tasks/SKILL.md +32 -0
  27. package/dist/templates/skills/codex/ralph-loop/scripts/kanban.sh +11 -0
  28. package/dist/templates/skills/codex/understand-project/SKILL.md +46 -0
  29. package/dist/templates/skills/pi/kanban-workflow/SKILL.md +139 -0
  30. package/dist/templates/skills/pi/plan-kanban-tasks/SKILL.md +1 -1
  31. package/dist/templates/skills/pi/ralph-loop/SKILL.md +4 -0
  32. package/dist/templates/skills/pi/understand-project/SKILL.md +1 -1
  33. package/package.json +7 -5
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/version.ts","../src/core/errors.ts","../src/cli/utils/advanced-logger.ts","../src/types/execution.ts","../src/core/backends/shell-backend.ts","../src/index.ts","../src/core/config.ts","../src/templates/default-hooks.ts","../src/core/engine.ts","../src/utils/hooks.ts","../src/core/session.ts","../src/utils/environment.ts","../src/utils/validation.ts","../src/cli/types.ts","../src/types/index.ts"],"names":["version","LogLevel","chalk","fs","path2","fsExtra","resolve","env","os","spawn","stdout","z","path","fsPromises","yaml","nodeFs","result","execa","success","ExecutionStatus","EventEmitter","ShellBackend","resetTimeStr","path3","fs3","uuidv4","process2","delimiter","os2","path4","platform","LogLevelSchema"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKaA;AALb,IAAA,YAAA,GAAA,KAAA,CAAA;AAAA,EAAA,gBAAA,GAAA;AAKO,IAAMA,eAAA,GAAU,QAAA;AAAA,EAAA;AAAA,CAAA,CAAA;;;ACy2BhB,SAAS,wBAAwB,OAAA,EAAmC;AACzE,EAAA,KAAA,MAAW,WAAW,mBAAA,EAAqB;AACzC,IAAA,MAAM,KAAA,GAAQ,OAAA,CAAQ,KAAA,CAAM,OAAO,CAAA;AACnC,IAAA,IAAI,KAAA,EAAO;AACT,MAAA,IAAI;AACF,QAAA,OAAO,mBAAmB,KAAK,CAAA;AAAA,MACjC,CAAA,CAAA,MAAQ;AAAA,MAER;AAAA,IACF;AAAA,EACF;AACA,EAAA,OAAO,MAAA;AACT;AAKA,SAAS,mBAAmB,KAAA,EAA2C;AACrE,EAAA,MAAM,GAAG,KAAA,EAAO,KAAA,EAAO,MAAM,CAAA,GAAI,KAAA;AAGjC,EAAA,IAAI,KAAA,IAAS,KAAA,CAAM,QAAA,CAAS,GAAG,CAAA,EAAG;AAChC,IAAA,OAAO,IAAI,KAAK,KAAK,CAAA;AAAA,EACvB;AAGA,EAAA,IAAI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MAAA;AAC9C,UAAA;AAAA;AACJ,IACF,SAAS,KAAA,EAAO;AACd,MAAA,IAAI,iBAAiB,KAAA,EAAO;AAC1B,QAAA,MAAA,CAAO,KAAK,CAAA,EAAG,GAAG,CAAA,EAAA,EAAK,KAAA,CAAM,OAAO,CAAA,CAAE,CAAA;AAAA,MACxC;AAAA,IACF;AAAA,EACF,CAAC,CAAA;AAED,EAAA,IAAI,MAAA,CAAO,SAAS,CAAA,EAAG;AACrB,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA;AAAA,EAA4C,MAAA,CAAO,IAAA,CAAK,IAAI,CAAC,CAAA,CAAE,CAAA;AAAA,EACjF;AAEA,EAAA,OAAO,MAAA;AACT;;;AE5LA,YAAA,EAAA;;;ATyCA,YAAA,EAAA","file":"index.js","sourcesContent":["/**\n * Version information for juno-task-ts\n */\n\n// This will be replaced by the build process\nexport const version = __VERSION__ || '1.0.0';\n\n// Development flag\nexport const isDevelopment = __DEV__ || false;\n","/**\n * Execution error definitions for juno-task-ts\n *\n * Provides comprehensive error classes and utilities for execution operations,\n * including error codes, context tracking, recovery suggestions, and\n * specialized error types for different failure scenarios.\n *\n * Originally migrated from the MCP error module. The MCP system has been\n * removed; these are now the canonical execution error definitions.\n * Deprecated MCP-prefixed aliases are retained below for backward compatibility.\n *\n * @module core/errors\n * @version 2.0.0\n */\n\n// =============================================================================\n// Error Type Enums and Constants\n// =============================================================================\n\n/**\n * Execution error categories for targeted error handling\n */\nexport enum ExecutionErrorType {\n CONNECTION = 'connection',\n TIMEOUT = 'timeout',\n RATE_LIMIT = 'rate_limit',\n TOOL_EXECUTION = 'tool_execution',\n VALIDATION = 'validation',\n SERVER_NOT_FOUND = 'server_not_found',\n PROTOCOL = 'protocol',\n AUTHENTICATION = 'authentication',\n}\n\n/**\n * Error codes for specific error conditions\n */\nexport enum ExecutionErrorCode {\n // Connection errors\n CONNECTION_FAILED = 'MCP_CONNECTION_FAILED',\n CONNECTION_TIMEOUT = 'MCP_CONNECTION_TIMEOUT',\n CONNECTION_REFUSED = 'MCP_CONNECTION_REFUSED',\n CONNECTION_LOST = 'MCP_CONNECTION_LOST',\n RECONNECTION_FAILED = 'MCP_RECONNECTION_FAILED',\n\n // Tool execution errors\n TOOL_NOT_FOUND = 'MCP_TOOL_NOT_FOUND',\n TOOL_EXECUTION_FAILED = 'MCP_TOOL_EXECUTION_FAILED',\n TOOL_TIMEOUT = 'MCP_TOOL_TIMEOUT',\n TOOL_INVALID_ARGUMENTS = 'MCP_TOOL_INVALID_ARGUMENTS',\n\n // Rate limit errors\n RATE_LIMIT_EXCEEDED = 'MCP_RATE_LIMIT_EXCEEDED',\n RATE_LIMIT_HOURLY = 'MCP_RATE_LIMIT_HOURLY',\n RATE_LIMIT_DAILY = 'MCP_RATE_LIMIT_DAILY',\n\n // Validation errors\n VALIDATION_FAILED = 'MCP_VALIDATION_FAILED',\n INVALID_REQUEST = 'MCP_INVALID_REQUEST',\n MISSING_PARAMETERS = 'MCP_MISSING_PARAMETERS',\n INVALID_PARAMETERS = 'MCP_INVALID_PARAMETERS',\n\n // Server errors\n SERVER_NOT_FOUND = 'MCP_SERVER_NOT_FOUND',\n SERVER_NOT_EXECUTABLE = 'MCP_SERVER_NOT_EXECUTABLE',\n SERVER_STARTUP_FAILED = 'MCP_SERVER_STARTUP_FAILED',\n SERVER_CRASHED = 'MCP_SERVER_CRASHED',\n\n // Protocol errors\n PROTOCOL_ERROR = 'MCP_PROTOCOL_ERROR',\n INVALID_RESPONSE = 'MCP_INVALID_RESPONSE',\n VERSION_MISMATCH = 'MCP_VERSION_MISMATCH',\n\n // Authentication errors\n AUTHENTICATION_FAILED = 'MCP_AUTHENTICATION_FAILED',\n UNAUTHORIZED = 'MCP_UNAUTHORIZED',\n TOKEN_EXPIRED = 'MCP_TOKEN_EXPIRED',\n}\n\n/**\n * Rate limit message patterns for parsing reset times\n */\nexport const RATE_LIMIT_PATTERNS = [\n // Unix timestamp patterns (must come first to avoid conflicts)\n /resets?\\s+(?:at\\s+)?(\\d{10,13})/i,\n\n // ISO date patterns\n /resets?\\s+(?:at\\s+)?([\\d-]+T[\\d:.]+Z?)/i,\n\n // Standard patterns\n /resets\\s+(?:at\\s+)?(\\d{1,2}):?(\\d{2})?\\s*(am|pm)?/i,\n /resets\\s+(?:at\\s+)?(\\d{1,2})\\s*(am|pm)/i,\n\n // Duration-based patterns\n /try again in (\\d+)\\s*(minutes?|hours?|seconds?)/i,\n /wait\\s+(\\d+)\\s*(minutes?|hours?|seconds?)/i,\n\n // Specific service patterns\n /5-hour limit reached.*resets\\s+(?:at\\s+)?(\\d{1,2})\\s*(am|pm)/i,\n /hourly limit.*resets\\s+(?:at\\s+)?(\\d{1,2}):(\\d{2})/i,\n] as const;\n\n// =============================================================================\n// Error Context Interfaces\n// =============================================================================\n\n/**\n * Base error options for execution errors\n */\nexport interface ExecutionErrorOptions {\n /** Error code for programmatic handling */\n readonly code?: ExecutionErrorCode | undefined;\n\n /** Operation context when error occurred */\n readonly context?: string | undefined;\n\n /** Retry information */\n readonly retryInfo?: RetryInfo | undefined;\n\n /** Recovery suggestions for the user */\n readonly recoverySuggestions?: readonly string[] | undefined;\n\n /** Cause error for error chaining */\n readonly cause?: Error | undefined;\n\n /** Additional metadata */\n readonly metadata?: Readonly<Record<string, unknown>> | undefined;\n}\n\n/**\n * Retry information for error context\n */\nexport interface RetryInfo {\n /** Current attempt number */\n readonly attempt: number;\n\n /** Maximum attempts allowed */\n readonly maxAttempts: number;\n\n /** Next retry time */\n readonly nextRetryTime?: Date;\n\n /** Retry strategy used */\n readonly strategy: string;\n\n /** Backoff delay in milliseconds */\n readonly backoffDelay?: number;\n}\n\n/**\n * Server information for connection errors\n */\nexport interface ServerInfo {\n /** Server executable path */\n readonly path: string;\n\n /** Server version */\n readonly version?: string;\n\n /** Process ID */\n readonly pid?: number;\n\n /** Server status */\n readonly status: string;\n\n /** Server arguments */\n readonly args?: readonly string[];\n\n /** Working directory */\n readonly workingDirectory?: string;\n}\n\n/**\n * Tool information for tool errors\n */\nexport interface ToolInfo {\n /** Tool name */\n readonly name: string;\n\n /** Tool version */\n readonly version?: string;\n\n /** Subagent type */\n readonly subagent: string;\n\n /** Model used */\n readonly model?: string;\n\n /** Tool capabilities */\n readonly capabilities?: readonly string[];\n}\n\n/**\n * Tool execution details for error context\n */\nexport interface ToolExecutionDetails {\n /** Execution start time */\n readonly startTime: Date;\n\n /** Execution duration in milliseconds */\n readonly duration: number;\n\n /** Arguments used */\n readonly arguments: Readonly<Record<string, unknown>>;\n\n /** Progress events captured */\n readonly progressEvents?: readonly unknown[];\n\n /** Execution timeout */\n readonly timeout?: number;\n\n /** Session ID */\n readonly sessionId?: string;\n}\n\n// =============================================================================\n// Base Execution Error Class\n// =============================================================================\n\n/**\n * Base execution error class with enhanced context and recovery information\n */\nexport abstract class ExecutionError extends Error {\n /** Error type classification */\n public readonly type: ExecutionErrorType;\n\n /** Error code for programmatic handling */\n public readonly code: ExecutionErrorCode;\n\n /** Error timestamp */\n public readonly timestamp: Date;\n\n /** Operation context */\n public readonly context?: string | undefined;\n\n /** Retry information */\n public readonly retryInfo?: RetryInfo | undefined;\n\n /** Recovery suggestions */\n public readonly recoverySuggestions?: readonly string[] | undefined;\n\n /** Additional metadata */\n public readonly metadata?: Readonly<Record<string, unknown>> | undefined;\n\n /** Cause error for error chaining */\n public override readonly cause?: Error | undefined;\n\n constructor(\n message: string,\n type: ExecutionErrorType,\n code: ExecutionErrorCode,\n options?: ExecutionErrorOptions,\n ) {\n super(message);\n this.name = this.constructor.name;\n this.type = type;\n this.code = options?.code ?? code;\n this.timestamp = new Date();\n this.context = options?.context;\n this.retryInfo = options?.retryInfo;\n this.recoverySuggestions = options?.recoverySuggestions;\n this.metadata = options?.metadata;\n this.cause = options?.cause;\n\n // Maintain proper stack trace\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n\n /**\n * Get user-friendly error message\n */\n getUserMessage(): string {\n return this.message;\n }\n\n /**\n * Get technical error details\n */\n getTechnicalDetails(): string {\n const details = [\n `Error: ${this.name}`,\n `Type: ${this.type}`,\n `Code: ${this.code}`,\n `Message: ${this.message}`,\n `Timestamp: ${this.timestamp.toISOString()}`,\n ];\n\n if (this.context) {\n details.push(`Context: ${this.context}`);\n }\n\n if (this.retryInfo) {\n details.push(`Retry: ${this.retryInfo.attempt}/${this.retryInfo.maxAttempts}`);\n }\n\n if (this.cause) {\n details.push(`Cause: ${this.cause.message}`);\n }\n\n return details.join('\\n');\n }\n\n /**\n * Check if error is retryable\n */\n isRetryable(): boolean {\n if (!this.retryInfo) {\n return false;\n }\n return this.retryInfo.attempt < this.retryInfo.maxAttempts;\n }\n\n /**\n * Get time until next retry\n */\n getRetryDelay(): number {\n if (!this.retryInfo?.nextRetryTime) {\n return 0;\n }\n return Math.max(0, this.retryInfo.nextRetryTime.getTime() - Date.now());\n }\n\n /**\n * Serialize error to JSON\n */\n toJSON(): Record<string, unknown> {\n return {\n name: this.name,\n type: this.type,\n code: this.code,\n message: this.message,\n timestamp: this.timestamp.toISOString(),\n context: this.context,\n retryInfo: this.retryInfo,\n recoverySuggestions: this.recoverySuggestions,\n metadata: this.metadata,\n stack: this.stack,\n };\n }\n}\n\n// =============================================================================\n// Connection Error Classes\n// =============================================================================\n\n/**\n * Connection error for server connection failures\n */\nexport class ConnectionError extends ExecutionError {\n /** Server information */\n public readonly serverInfo?: ServerInfo | undefined;\n\n constructor(\n message: string,\n context?: string,\n serverInfo?: ServerInfo,\n options?: ExecutionErrorOptions,\n ) {\n const code = options?.code ?? ExecutionErrorCode.CONNECTION_FAILED;\n const suggestions = options?.recoverySuggestions ?? [\n 'Check if the server is running',\n 'Verify server path and permissions',\n 'Check network connectivity',\n 'Review server configuration',\n ];\n\n super(message, ExecutionErrorType.CONNECTION, code, {\n ...options,\n context,\n recoverySuggestions: suggestions,\n });\n\n this.serverInfo = serverInfo;\n }\n\n /**\n * Create connection timeout error\n */\n static timeout(timeoutMs: number, serverPath?: string): ConnectionError {\n return new ConnectionError(\n `Connection timeout after ${timeoutMs}ms`,\n 'connection_timeout',\n serverPath ? { path: serverPath, status: 'timeout' } : undefined,\n {\n code: ExecutionErrorCode.CONNECTION_TIMEOUT,\n recoverySuggestions: [\n 'Increase connection timeout value',\n 'Check server responsiveness',\n 'Verify network latency',\n ],\n },\n );\n }\n\n /**\n * Create connection refused error\n */\n static refused(serverPath: string, port?: number): ConnectionError {\n return new ConnectionError(\n `Connection refused to ${serverPath}${port ? `:${port}` : ''}`,\n 'connection_refused',\n { path: serverPath, status: 'refused' },\n {\n code: ExecutionErrorCode.CONNECTION_REFUSED,\n recoverySuggestions: [\n 'Verify server is running and listening',\n 'Check server address and port',\n 'Review firewall settings',\n ],\n },\n );\n }\n\n /**\n * Create server not found error\n */\n static serverNotFound(serverPath: string): ConnectionError {\n return new ConnectionError(\n `Server not found at path: ${serverPath}`,\n 'server_discovery',\n { path: serverPath, status: 'not_found' },\n {\n code: ExecutionErrorCode.SERVER_NOT_FOUND,\n recoverySuggestions: [\n 'Check server installation path',\n 'Verify executable permissions',\n 'Install the server package',\n 'Update PATH environment variable',\n ],\n },\n );\n }\n}\n\n// =============================================================================\n// Tool Error Classes\n// =============================================================================\n\n/**\n * Tool execution error\n */\nexport class ToolError extends ExecutionError {\n /** Tool information */\n public readonly toolInfo: ToolInfo;\n\n /** Execution details */\n public readonly executionDetails?: ToolExecutionDetails | undefined;\n\n constructor(\n message: string,\n toolInfo: ToolInfo,\n context?: string,\n options?: ExecutionErrorOptions & { executionDetails?: ToolExecutionDetails | undefined },\n ) {\n const code = options?.code ?? ExecutionErrorCode.TOOL_EXECUTION_FAILED;\n const suggestions = options?.recoverySuggestions ?? [\n 'Check tool arguments and parameters',\n 'Verify tool is available and accessible',\n 'Review tool documentation',\n 'Check server logs for details',\n ];\n\n super(message, ExecutionErrorType.TOOL_EXECUTION, code, {\n ...options,\n context,\n recoverySuggestions: suggestions,\n });\n\n this.toolInfo = toolInfo;\n this.executionDetails = options?.executionDetails;\n }\n\n /**\n * Create tool not found error\n */\n static notFound(toolName: string): ToolError {\n return new ToolError(\n `Tool not found: ${toolName}`,\n { name: toolName, subagent: 'unknown' },\n 'tool_discovery',\n {\n code: ExecutionErrorCode.TOOL_NOT_FOUND,\n recoverySuggestions: [\n 'Check available tools with listTools()',\n 'Verify tool name spelling',\n 'Ensure server supports this tool',\n ],\n },\n );\n }\n\n /**\n * Create tool timeout error\n */\n static timeout(\n toolName: string,\n timeoutMs: number,\n executionDetails?: ToolExecutionDetails,\n ): ToolError {\n return new ToolError(\n `Tool execution timeout: ${toolName} (${timeoutMs}ms)`,\n { name: toolName, subagent: 'unknown' },\n 'tool_timeout',\n {\n code: ExecutionErrorCode.TOOL_TIMEOUT,\n executionDetails,\n recoverySuggestions: [\n 'Increase tool execution timeout',\n 'Check tool complexity and resource usage',\n 'Consider breaking task into smaller parts',\n ],\n },\n );\n }\n\n /**\n * Create invalid arguments error\n */\n static invalidArguments(\n toolName: string,\n invalidArgs: Record<string, unknown>,\n expectedFormat?: string,\n ): ToolError {\n return new ToolError(\n `Invalid arguments for tool: ${toolName}`,\n { name: toolName, subagent: 'unknown' },\n 'argument_validation',\n {\n code: ExecutionErrorCode.TOOL_INVALID_ARGUMENTS,\n metadata: { invalidArgs, expectedFormat },\n recoverySuggestions: [\n 'Check tool documentation for required arguments',\n 'Verify argument types and formats',\n 'Review tool schema definition',\n ],\n },\n );\n }\n}\n\n// =============================================================================\n// Timeout Error Classes\n// =============================================================================\n\n/**\n * Timeout error for operation timeouts\n */\nexport class TimeoutError extends ExecutionError {\n /** Timeout duration in milliseconds */\n public readonly timeoutMs: number;\n\n /** Operation type that timed out */\n public readonly operationType: string;\n\n constructor(\n message: string,\n timeoutMs: number,\n operationType: string,\n context?: string,\n options?: ExecutionErrorOptions,\n ) {\n const code = options?.code ?? ExecutionErrorCode.CONNECTION_TIMEOUT;\n const suggestions = options?.recoverySuggestions ?? [\n 'Increase timeout value',\n 'Check operation complexity',\n 'Verify network connectivity',\n 'Consider breaking operation into smaller parts',\n ];\n\n super(message, ExecutionErrorType.TIMEOUT, code, {\n ...options,\n context,\n recoverySuggestions: suggestions,\n });\n\n this.timeoutMs = timeoutMs;\n this.operationType = operationType;\n }\n\n /**\n * Create connection timeout error\n */\n static connection(timeoutMs: number): TimeoutError {\n return new TimeoutError(\n `Connection timeout after ${timeoutMs}ms`,\n timeoutMs,\n 'connection',\n 'backend_connection',\n {\n code: ExecutionErrorCode.CONNECTION_TIMEOUT,\n recoverySuggestions: [\n 'Increase connection timeout',\n 'Check server startup time',\n 'Verify network latency',\n ],\n },\n );\n }\n\n /**\n * Create tool execution timeout error\n */\n static toolExecution(toolName: string, timeoutMs: number): TimeoutError {\n return new TimeoutError(\n `Tool execution timeout: ${toolName} (${timeoutMs}ms)`,\n timeoutMs,\n 'tool_execution',\n `tool_${toolName}`,\n {\n code: ExecutionErrorCode.TOOL_TIMEOUT,\n recoverySuggestions: [\n 'Increase tool execution timeout',\n 'Optimize tool parameters',\n 'Check tool resource usage',\n ],\n },\n );\n }\n}\n\n// =============================================================================\n// Rate Limit Error Classes\n// =============================================================================\n\n/**\n * Rate limit error with reset time parsing\n */\nexport class RateLimitError extends ExecutionError {\n /** Rate limit reset time */\n public readonly resetTime?: Date | undefined;\n\n /** Current rate limit tier */\n public readonly tier?: string | undefined;\n\n /** Requests remaining */\n public readonly remaining: number;\n\n /** Rate limit window */\n public readonly window?: string | undefined;\n\n constructor(\n message: string,\n remaining: number = 0,\n resetTime?: Date,\n tier?: string,\n context?: string,\n options?: ExecutionErrorOptions,\n ) {\n const code = options?.code ?? ExecutionErrorCode.RATE_LIMIT_EXCEEDED;\n const waitTime = resetTime ? Math.ceil((resetTime.getTime() - Date.now()) / 1000) : 0;\n const suggestions = options?.recoverySuggestions ?? [\n `Wait ${waitTime > 0 ? waitTime + ' seconds' : 'for rate limit reset'}`,\n 'Reduce request frequency',\n 'Implement request queuing',\n 'Consider upgrading service tier',\n ];\n\n super(message, ExecutionErrorType.RATE_LIMIT, code, {\n ...options,\n context,\n recoverySuggestions: suggestions,\n retryInfo: resetTime\n ? {\n attempt: 1,\n maxAttempts: 1,\n nextRetryTime: resetTime,\n strategy: 'rate_limit_wait',\n }\n : options?.retryInfo,\n });\n\n this.resetTime = resetTime;\n this.tier = tier;\n this.remaining = remaining;\n }\n\n /**\n * Parse rate limit error from message text\n */\n static fromMessage(message: string, context?: string): RateLimitError {\n const resetTime = parseRateLimitResetTime(message);\n\n // Extract remaining requests if available\n const remainingMatch = message.match(/(\\d+)\\s*(?:requests?|calls?)\\s*remaining/i);\n const remaining = remainingMatch ? parseInt(remainingMatch[1]!, 10) : 0;\n\n // Extract tier information if available\n const tierMatch = message.match(/tier[:\\s]*([a-zA-Z0-9_-]+)/i);\n const tier = tierMatch ? tierMatch[1] : undefined;\n\n return new RateLimitError(message, remaining, resetTime, tier, context, {\n code: ExecutionErrorCode.RATE_LIMIT_EXCEEDED,\n metadata: { originalMessage: message },\n });\n }\n\n /**\n * Create hourly rate limit error\n */\n static hourly(resetTime: Date, remaining: number = 0): RateLimitError {\n return new RateLimitError(\n `Hourly rate limit exceeded. Resets at ${resetTime.toLocaleTimeString()}`,\n remaining,\n resetTime,\n 'hourly',\n 'hourly_limit',\n {\n code: ExecutionErrorCode.RATE_LIMIT_HOURLY,\n },\n );\n }\n\n /**\n * Create daily rate limit error\n */\n static daily(resetTime: Date, remaining: number = 0): RateLimitError {\n return new RateLimitError(\n `Daily rate limit exceeded. Resets at ${resetTime.toLocaleDateString()} ${resetTime.toLocaleTimeString()}`,\n remaining,\n resetTime,\n 'daily',\n 'daily_limit',\n {\n code: ExecutionErrorCode.RATE_LIMIT_DAILY,\n },\n );\n }\n\n /**\n * Get wait time in milliseconds\n */\n getWaitTimeMs(): number {\n if (!this.resetTime) {\n return 0;\n }\n return Math.max(0, this.resetTime.getTime() - Date.now());\n }\n\n /**\n * Get wait time in seconds\n */\n getWaitTimeSeconds(): number {\n return Math.ceil(this.getWaitTimeMs() / 1000);\n }\n}\n\n// =============================================================================\n// Validation Error Classes\n// =============================================================================\n\n/**\n * Validation error for input validation failures\n */\nexport class ValidationError extends ExecutionError {\n /** Validation rule that failed */\n public readonly rule: string;\n\n /** Invalid value */\n public readonly value: unknown;\n\n /** Expected format/value */\n public readonly expected?: string | undefined;\n\n /** Field path for nested validation */\n public readonly field?: string | undefined;\n\n constructor(\n message: string,\n rule: string,\n value: unknown,\n expected?: string,\n field?: string,\n context?: string,\n options?: ExecutionErrorOptions,\n ) {\n const code = options?.code ?? ExecutionErrorCode.VALIDATION_FAILED;\n const suggestions = options?.recoverySuggestions ?? [\n 'Check parameter types and formats',\n 'Refer to API documentation',\n 'Validate input before sending',\n ];\n\n super(message, ExecutionErrorType.VALIDATION, code, {\n ...options,\n context,\n recoverySuggestions: suggestions,\n });\n\n this.rule = rule;\n this.value = value;\n this.expected = expected;\n this.field = field;\n }\n\n /**\n * Create required field error\n */\n static required(field: string): ValidationError {\n return new ValidationError(\n `Required field missing: ${field}`,\n 'required',\n undefined,\n 'non-empty value',\n field,\n 'parameter_validation',\n {\n code: ExecutionErrorCode.MISSING_PARAMETERS,\n },\n );\n }\n\n /**\n * Create type mismatch error\n */\n static typeMismatch(field: string, value: unknown, expectedType: string): ValidationError {\n return new ValidationError(\n `Invalid type for field '${field}': expected ${expectedType}, got ${typeof value}`,\n 'type_mismatch',\n value,\n expectedType,\n field,\n 'type_validation',\n {\n code: ExecutionErrorCode.INVALID_PARAMETERS,\n },\n );\n }\n\n /**\n * Create format error\n */\n static format(field: string, value: unknown, expectedFormat: string): ValidationError {\n return new ValidationError(\n `Invalid format for field '${field}': expected ${expectedFormat}`,\n 'format',\n value,\n expectedFormat,\n field,\n 'format_validation',\n {\n code: ExecutionErrorCode.INVALID_PARAMETERS,\n },\n );\n }\n\n /**\n * Create range error\n */\n static range(field: string, value: unknown, min?: number, max?: number): ValidationError {\n const range =\n min !== undefined && max !== undefined\n ? `${min}-${max}`\n : min !== undefined\n ? `>= ${min}`\n : `<= ${max}`;\n\n return new ValidationError(\n `Value out of range for field '${field}': expected ${range}`,\n 'range',\n value,\n range,\n field,\n 'range_validation',\n {\n code: ExecutionErrorCode.INVALID_PARAMETERS,\n },\n );\n }\n}\n\n// =============================================================================\n// Utility Functions\n// =============================================================================\n\n/**\n * Parse rate limit reset time from various message formats\n */\nexport function parseRateLimitResetTime(message: string): Date | undefined {\n for (const pattern of RATE_LIMIT_PATTERNS) {\n const match = message.match(pattern);\n if (match) {\n try {\n return parseTimeFromMatch(match);\n } catch {\n // Continue to next pattern\n }\n }\n }\n return undefined;\n}\n\n/**\n * Parse time information from regex match\n */\nfunction parseTimeFromMatch(match: RegExpMatchArray): Date | undefined {\n const [, time1, time2, period] = match;\n\n // Handle ISO date string (check before Unix timestamp to avoid conflicts)\n if (time1 && time1.includes('T')) {\n return new Date(time1);\n }\n\n // Handle Unix timestamp\n if (time1 && time1.length >= 10) {\n const timestamp = parseInt(time1, 10);\n return new Date(timestamp > 9999999999 ? timestamp : timestamp * 1000);\n }\n\n // Handle duration-based patterns\n if (time2 && (time2.includes('minute') || time2.includes('hour') || time2.includes('second'))) {\n const duration = parseInt(time1!, 10);\n const unit = time2.toLowerCase();\n const now = new Date();\n\n if (unit.includes('minute')) {\n return new Date(now.getTime() + duration * 60 * 1000);\n } else if (unit.includes('hour')) {\n return new Date(now.getTime() + duration * 60 * 60 * 1000);\n } else if (unit.includes('second')) {\n return new Date(now.getTime() + duration * 1000);\n }\n }\n\n // Handle time-based patterns (e.g., \"3:30 PM\", \"15:30\")\n if (time1) {\n const hour = parseInt(time1, 10);\n const minute = time2 ? parseInt(time2, 10) : 0;\n let adjustedHour = hour;\n\n if (period) {\n const isPM = period.toLowerCase().includes('pm');\n if (isPM && hour < 12) {\n adjustedHour += 12;\n } else if (!isPM && hour === 12) {\n adjustedHour = 0;\n }\n }\n\n const resetTime = new Date();\n resetTime.setHours(adjustedHour, minute, 0, 0);\n\n // If the time has passed today, set it for tomorrow\n if (resetTime <= new Date()) {\n resetTime.setDate(resetTime.getDate() + 1);\n }\n\n return resetTime;\n }\n\n return undefined;\n}\n\n/**\n * Type guards for error checking\n */\n\n/**\n * Check if error is an execution error\n */\nexport function isExecutionError(error: unknown): error is ExecutionError {\n return error instanceof ExecutionError;\n}\n\n/**\n * Check if error is a connection error\n */\nexport function isConnectionError(error: unknown): error is ConnectionError {\n return error instanceof ConnectionError;\n}\n\n/**\n * Check if error is a tool error\n */\nexport function isToolError(error: unknown): error is ToolError {\n return error instanceof ToolError;\n}\n\n/**\n * Check if error is a timeout error\n */\nexport function isTimeoutError(error: unknown): error is TimeoutError {\n return error instanceof TimeoutError;\n}\n\n/**\n * Check if error is a rate limit error\n */\nexport function isRateLimitError(error: unknown): error is RateLimitError {\n return error instanceof RateLimitError;\n}\n\n/**\n * Check if error is a validation error\n */\nexport function isValidationError(error: unknown): error is ValidationError {\n return error instanceof ValidationError;\n}\n\n/**\n * Check if error is retryable\n */\nexport function isRetryableError(error: unknown): boolean {\n if (!isExecutionError(error)) {\n return false;\n }\n\n // Rate limits are retryable after the reset time\n if (isRateLimitError(error)) {\n return true;\n }\n\n // Connection errors are usually retryable\n if (isConnectionError(error)) {\n return true;\n }\n\n // Some timeout errors are retryable\n if (isTimeoutError(error)) {\n return true;\n }\n\n // Validation errors are not retryable\n if (isValidationError(error)) {\n return false;\n }\n\n return error.isRetryable();\n}\n\n/**\n * Get error category for recovery strategy\n */\nexport function getErrorCategory(error: unknown): ExecutionErrorType | 'unknown' {\n if (isExecutionError(error)) {\n return error.type;\n }\n return 'unknown';\n}\n\n/**\n * Format error for user display\n */\nexport function formatErrorForUser(error: unknown): string {\n if (isExecutionError(error)) {\n return error.getUserMessage();\n }\n\n if (error instanceof Error) {\n return error.message;\n }\n\n return String(error);\n}\n\n/**\n * Format error for logging\n */\nexport function formatErrorForLogging(error: unknown): string {\n if (isExecutionError(error)) {\n return error.getTechnicalDetails();\n }\n\n if (error instanceof Error) {\n return `${error.name}: ${error.message}\\n${error.stack || 'No stack trace'}`;\n }\n\n return `Unknown error: ${JSON.stringify(error)}`;\n}\n\n/**\n * Extract recovery suggestions from error\n */\nexport function getRecoverySuggestions(error: unknown): string[] {\n if (isExecutionError(error) && error.recoverySuggestions) {\n return Array.from(error.recoverySuggestions);\n }\n\n // Default suggestions based on error type\n if (isConnectionError(error)) {\n return ['Check network connectivity', 'Verify server is running', 'Check server configuration'];\n }\n\n if (isRateLimitError(error)) {\n return ['Wait for rate limit reset', 'Reduce request frequency', 'Implement request queuing'];\n }\n\n if (isValidationError(error)) {\n return ['Check input parameters', 'Refer to API documentation', 'Validate data before sending'];\n }\n\n return [\n 'Check error message for details',\n 'Review configuration',\n 'Contact support if problem persists',\n ];\n}\n\n/**\n * Create error chain from multiple errors\n */\nexport function createErrorChain(errors: Error[]): ExecutionError {\n if (errors.length === 0) {\n return new ConnectionError('Unknown error occurred', 'error_chain');\n }\n\n if (errors.length === 1) {\n const error = errors[0]!;\n if (isExecutionError(error)) {\n return error;\n }\n return new ConnectionError(error.message, 'wrapped_error', undefined, {\n cause: error,\n });\n }\n\n const primaryError = errors[0]!;\n const additionalErrors = errors.slice(1);\n\n return new ConnectionError(\n `Multiple errors occurred: ${primaryError.message}`,\n 'error_chain',\n undefined,\n {\n cause: primaryError,\n metadata: {\n additionalErrors: additionalErrors.map((e) => ({\n name: e.name,\n message: e.message,\n })),\n },\n recoverySuggestions: [\n 'Address the primary error first',\n 'Check for cascading failures',\n 'Review system configuration',\n ],\n },\n );\n}\n\n// =============================================================================\n// Error Recovery Utilities\n// =============================================================================\n\n/**\n * Error recovery strategy type\n */\nexport type ErrorRecoveryStrategy =\n | 'retry'\n | 'wait'\n | 'reconnect'\n | 'fallback'\n | 'abort'\n | 'manual';\n\n/**\n * Get recommended recovery strategy for error\n */\nexport function getRecoveryStrategy(error: unknown): ErrorRecoveryStrategy {\n if (isRateLimitError(error)) {\n return 'wait';\n }\n\n if (isConnectionError(error)) {\n return 'reconnect';\n }\n\n if (isTimeoutError(error)) {\n return 'retry';\n }\n\n if (isValidationError(error)) {\n return 'manual';\n }\n\n if (isToolError(error)) {\n return 'fallback';\n }\n\n return 'abort';\n}\n\n/**\n * Calculate retry delay based on error and attempt\n */\nexport function calculateRetryDelay(\n error: unknown,\n attempt: number,\n baseDelay: number = 1000,\n maxDelay: number = 30000,\n): number {\n if (isRateLimitError(error)) {\n return error.getWaitTimeMs();\n }\n\n // Exponential backoff with jitter\n const exponentialDelay = Math.min(baseDelay * Math.pow(2, attempt - 1), maxDelay);\n const jitter = exponentialDelay * 0.1 * (Math.random() - 0.5);\n\n return Math.max(0, exponentialDelay + jitter);\n}\n\n// =============================================================================\n// Deprecated Aliases (backward compatibility)\n// The MCP system has been removed. These aliases are kept temporarily so that\n// any external consumers referencing the old MCP-prefixed names continue to\n// compile. They will be removed in a future major version.\n// =============================================================================\n\n/** @deprecated Use ExecutionErrorType instead */\nexport const MCPErrorType = ExecutionErrorType;\n/** @deprecated Use ExecutionErrorType instead */\nexport type MCPErrorType = ExecutionErrorType;\n\n/** @deprecated Use ExecutionErrorCode instead */\nexport const MCPErrorCode = ExecutionErrorCode;\n/** @deprecated Use ExecutionErrorCode instead */\nexport type MCPErrorCode = ExecutionErrorCode;\n\n/** @deprecated Use ExecutionErrorOptions instead */\nexport type MCPErrorOptions = ExecutionErrorOptions;\n\n/** @deprecated Use ExecutionError instead */\nexport type MCPError = ExecutionError;\n/** @deprecated Use ExecutionError instead */\nexport const MCPError = ExecutionError;\n\n/** @deprecated Use ConnectionError instead */\nexport type MCPConnectionError = ConnectionError;\n/** @deprecated Use ConnectionError instead */\nexport const MCPConnectionError = ConnectionError;\n\n/** @deprecated Use ToolError instead */\nexport type MCPToolError = ToolError;\n/** @deprecated Use ToolError instead */\nexport const MCPToolError = ToolError;\n\n/** @deprecated Use TimeoutError instead */\nexport type MCPTimeoutError = TimeoutError;\n/** @deprecated Use TimeoutError instead */\nexport const MCPTimeoutError = TimeoutError;\n\n/** @deprecated Use RateLimitError instead */\nexport type MCPRateLimitError = RateLimitError;\n/** @deprecated Use RateLimitError instead */\nexport const MCPRateLimitError = RateLimitError;\n\n/** @deprecated Use ValidationError instead */\nexport type MCPValidationError = ValidationError;\n/** @deprecated Use ValidationError instead */\nexport const MCPValidationError = ValidationError;\n\n/** @deprecated Use isExecutionError instead */\nexport const isMCPError = isExecutionError;\n","/**\n * Advanced Log Formatting System for juno-code\n *\n * Provides structured, colorized logging with multiple log levels and contexts.\n * All output goes to stderr to keep stdout clean for structured results.\n */\n\nimport chalk from 'chalk';\n\n// ============================================================================\n// Log Level and Context Types\n// ============================================================================\n\nexport enum LogLevel {\n TRACE = 0,\n DEBUG = 1,\n INFO = 2,\n WARN = 3,\n ERROR = 4,\n FATAL = 5,\n}\n\nexport enum LogContext {\n CLI = 'CLI',\n MCP = 'MCP',\n ENGINE = 'ENGINE',\n SESSION = 'SESSION',\n TEMPLATE = 'TEMPLATE',\n CONFIG = 'CONFIG',\n PERFORMANCE = 'PERFORMANCE',\n SYSTEM = 'SYSTEM',\n}\n\nexport interface LogEntry {\n timestamp: Date;\n level: LogLevel;\n context: LogContext;\n message: string;\n data?: any;\n duration?: number;\n}\n\nexport interface LoggerOptions {\n level: LogLevel;\n showTimestamp: boolean;\n showContext: boolean;\n showLevel: boolean;\n colorize: boolean;\n output: 'console';\n}\n\n// ============================================================================\n// Advanced Logger Class\n// ============================================================================\n\nexport class AdvancedLogger {\n private options: LoggerOptions;\n\n constructor(options: Partial<LoggerOptions> = {}) {\n this.options = {\n level: LogLevel.INFO,\n showTimestamp: true,\n showContext: true,\n showLevel: true,\n colorize: true,\n output: 'console',\n ...options,\n };\n }\n\n trace(message: string, context: LogContext = LogContext.SYSTEM, data?: any): void {\n this.log(LogLevel.TRACE, message, context, data);\n }\n\n debug(message: string, context: LogContext = LogContext.SYSTEM, data?: any): void {\n this.log(LogLevel.DEBUG, message, context, data);\n }\n\n info(message: string, context: LogContext = LogContext.SYSTEM, data?: any): void {\n this.log(LogLevel.INFO, message, context, data);\n }\n\n warn(message: string, context: LogContext = LogContext.SYSTEM, data?: any): void {\n this.log(LogLevel.WARN, message, context, data);\n }\n\n error(message: string, context: LogContext = LogContext.SYSTEM, data?: any): void {\n this.log(LogLevel.ERROR, message, context, data);\n }\n\n fatal(message: string, context: LogContext = LogContext.SYSTEM, data?: any): void {\n this.log(LogLevel.FATAL, message, context, data);\n }\n\n /**\n * Change log level\n */\n setLevel(level: LogLevel): void {\n this.options.level = level;\n }\n\n /**\n * Create a child logger with specific context\n */\n child(context: LogContext): ContextLogger {\n return new ContextLogger(this, context);\n }\n\n /**\n * Core logging method\n */\n private log(level: LogLevel, message: string, context: LogContext, data?: any): void {\n if (level < this.options.level) return;\n\n const entry: LogEntry = {\n timestamp: new Date(),\n level,\n context,\n message,\n data,\n };\n\n const formatted = this.formatSimple(entry);\n this.output(formatted);\n }\n\n /**\n * Simple format: [LEVEL] [CONTEXT] Message (duration)\n */\n private formatSimple(entry: LogEntry): string {\n const parts: string[] = [];\n\n if (this.options.showLevel) {\n const levelStr = this.formatLevel(entry.level);\n parts.push(`[${levelStr}]`);\n }\n\n if (this.options.showContext) {\n const contextStr = this.options.colorize\n ? chalk.gray(`[${entry.context}]`)\n : `[${entry.context}]`;\n parts.push(contextStr);\n }\n\n parts.push(entry.message);\n\n if (entry.duration !== undefined) {\n const durationStr = this.options.colorize\n ? chalk.cyan(`(${entry.duration}ms)`)\n : `(${entry.duration}ms)`;\n parts.push(durationStr);\n }\n\n return parts.join(' ');\n }\n\n /**\n * Format log level with appropriate color\n */\n private formatLevel(level: LogLevel): string {\n const levelName = LogLevel[level].padEnd(5);\n\n if (!this.options.colorize) return levelName;\n\n switch (level) {\n case LogLevel.TRACE:\n return chalk.gray(levelName);\n case LogLevel.DEBUG:\n return chalk.blue(levelName);\n case LogLevel.INFO:\n return chalk.green(levelName);\n case LogLevel.WARN:\n return chalk.yellow(levelName);\n case LogLevel.ERROR:\n return chalk.red(levelName);\n case LogLevel.FATAL:\n return chalk.redBright.bold(levelName);\n default:\n return levelName;\n }\n }\n\n /**\n * Output formatted log to stderr\n */\n private output(formatted: string): void {\n console.error(formatted);\n }\n}\n\n// ============================================================================\n// Context Logger Class\n// ============================================================================\n\nexport class ContextLogger {\n constructor(\n private parent: AdvancedLogger,\n private context: LogContext,\n ) {}\n\n trace(message: string, data?: any): void {\n this.parent.trace(message, this.context, data);\n }\n\n debug(message: string, data?: any): void {\n this.parent.debug(message, this.context, data);\n }\n\n info(message: string, data?: any): void {\n this.parent.info(message, this.context, data);\n }\n\n warn(message: string, data?: any): void {\n this.parent.warn(message, this.context, data);\n }\n\n error(message: string, data?: any): void {\n this.parent.error(message, this.context, data);\n }\n\n fatal(message: string, data?: any): void {\n this.parent.fatal(message, this.context, data);\n }\n}\n\n// ============================================================================\n// Global Logger Instance\n// ============================================================================\n\nexport const logger = new AdvancedLogger({\n level: LogLevel.INFO,\n colorize: true,\n output: 'console',\n});\n\n// Export context-specific loggers\nexport const cliLogger = logger.child(LogContext.CLI);\nexport const mcpLogger = logger.child(LogContext.MCP);\nexport const engineLogger = logger.child(LogContext.ENGINE);\nexport const sessionLogger = logger.child(LogContext.SESSION);\nexport const templateLogger = logger.child(LogContext.TEMPLATE);\nexport const configLogger = logger.child(LogContext.CONFIG);\nexport const performanceLogger = logger.child(LogContext.PERFORMANCE);\n\nexport default AdvancedLogger;\n","/**\n * Execution type definitions for juno-code\n *\n * This module provides comprehensive TypeScript types for task execution,\n * including progress tracking, tool calls, subagent integration,\n * session management, and connection lifecycle.\n *\n * @module execution\n * @since 1.0.0\n */\n\n// =============================================================================\n// Core Types & Enums\n// =============================================================================\n\n/**\n * Supported subagent types for tool mapping\n */\nexport type SubagentType = 'claude' | 'cursor' | 'codex' | 'gemini' | 'pi';\n\n/**\n * Extended subagent aliases for flexible naming\n */\nexport type SubagentAlias = 'claude-code' | 'claude_code' | 'gemini-cli' | 'cursor-agent';\n\n/**\n * Connection state lifecycle\n */\nexport enum MCPConnectionState {\n DISCONNECTED = 'disconnected',\n CONNECTING = 'connecting',\n CONNECTED = 'connected',\n RECONNECTING = 'reconnecting',\n FAILED = 'failed',\n CLOSING = 'closing',\n}\n\n/**\n * Progress event types from Roundtable server format\n */\nexport enum ProgressEventType {\n TOOL_START = 'tool_start',\n TOOL_RESULT = 'tool_result',\n THINKING = 'thinking',\n ERROR = 'error',\n INFO = 'info',\n DEBUG = 'debug',\n}\n\n/**\n * Error categories for targeted error handling\n */\nexport enum MCPErrorType {\n CONNECTION = 'connection',\n TIMEOUT = 'timeout',\n RATE_LIMIT = 'rate_limit',\n TOOL_EXECUTION = 'tool_execution',\n VALIDATION = 'validation',\n SERVER_NOT_FOUND = 'server_not_found',\n PROTOCOL = 'protocol',\n AUTHENTICATION = 'authentication',\n}\n\n/**\n * Tool execution status for tracking\n */\nexport enum ToolExecutionStatus {\n PENDING = 'pending',\n RUNNING = 'running',\n COMPLETED = 'completed',\n FAILED = 'failed',\n CANCELLED = 'cancelled',\n TIMEOUT = 'timeout',\n}\n\n// =============================================================================\n// Configuration Types\n// =============================================================================\n\n/**\n * Core server configuration interface\n *\n * @example\n * ```typescript\n * const config: MCPServerConfig = {\n * serverPath: './roundtable_mcp_server',\n * timeout: 3600,\n * retries: 3,\n * retryDelay: 1000,\n * workingDirectory: process.cwd(),\n * environment: {\n * 'ROUNDTABLE_API_KEY': 'your-key'\n * }\n * };\n * ```\n */\nexport interface MCPServerConfig {\n /** Optional path to server executable - will auto-discover if not provided */\n readonly serverPath?: string;\n\n /** Tool execution timeout in milliseconds (default: 3600000ms = 1 hour) */\n readonly timeout: number;\n\n /** Maximum retry attempts for failed operations (default: 3) */\n readonly retries: number;\n\n /** Delay between retry attempts in milliseconds (default: 1000ms) */\n readonly retryDelay: number;\n\n /** Working directory for server process execution */\n readonly workingDirectory: string;\n\n /** Additional environment variables for server process */\n readonly environment?: Readonly<Record<string, string>>;\n\n /** Custom server arguments (advanced usage) */\n readonly serverArgs?: readonly string[];\n\n /** Enable debug logging for communications */\n readonly debug?: boolean;\n\n /** Maximum memory usage for server process in MB */\n readonly maxMemoryMB?: number;\n\n /** Process priority for server subprocess */\n readonly processPriority?: 'low' | 'normal' | 'high';\n}\n\n/**\n * Connection retry configuration with exponential backoff\n */\nexport interface RetryConfig {\n /** Maximum number of retry attempts */\n readonly maxRetries: number;\n\n /** Initial delay between retries in milliseconds */\n readonly initialDelay: number;\n\n /** Maximum delay between retries in milliseconds */\n readonly maxDelay: number;\n\n /** Exponential backoff multiplier */\n readonly backoffMultiplier: number;\n\n /** Jitter factor to randomize retry timing (0-1) */\n readonly jitterFactor: number;\n\n /** Custom retry condition predicate */\n readonly shouldRetry?: (error: Error, attempt: number) => boolean;\n}\n\n/**\n * Rate limiting configuration and state\n */\nexport interface RateLimitConfig {\n /** Maximum requests per time window */\n readonly maxRequests: number;\n\n /** Time window in milliseconds */\n readonly windowMs: number;\n\n /** Burst allowance for short-term spikes */\n readonly burstAllowance: number;\n\n /** Enable adaptive rate limiting based on server responses */\n readonly adaptive: boolean;\n}\n\n// =============================================================================\n// Progress Tracking Types\n// =============================================================================\n\n/**\n * Progress event interface matching Roundtable server format\n * Format: \"Backend #count: event_type => content\"\n *\n * @example\n * ```typescript\n * const progressEvent: ProgressEvent = {\n * sessionId: 'session-123',\n * timestamp: new Date(),\n * backend: 'claude',\n * count: 1,\n * type: ProgressEventType.TOOL_START,\n * content: 'Starting code analysis...',\n * toolId: 'claude_1',\n * metadata: {\n * duration: 150,\n * tokens: 1024\n * }\n * };\n * ```\n */\nexport interface ProgressEvent {\n /** Unique session identifier for correlation */\n readonly sessionId: string;\n\n /** Event timestamp */\n readonly timestamp: Date;\n\n /** Subagent backend name (claude, cursor, codex, gemini) */\n readonly backend: string;\n\n /** Sequential event number within session */\n readonly count: number;\n\n /** Progress event classification */\n readonly type: ProgressEventType;\n\n /** Event content/message from subagent */\n readonly content: string;\n\n /** Generated tool correlation ID for tracking */\n readonly toolId: string;\n\n /** Additional event metadata */\n readonly metadata?: Readonly<Record<string, unknown>>;\n\n /** Parent event ID for nested operations */\n readonly parentId?: string;\n\n /** Event priority level */\n readonly priority?: 'low' | 'normal' | 'high';\n}\n\n/**\n * Progress callback function signature\n * Callbacks must never throw errors to avoid breaking execution flow\n *\n * @param event - The progress event to handle\n * @returns Promise<void> - Should handle errors internally\n */\nexport type ProgressCallback = (event: ProgressEvent) => Promise<void> | void;\n\n/**\n * Progress metadata for context tracking\n */\nexport interface ProgressMetadata {\n /** Operation start time */\n readonly startTime: Date;\n\n /** Total events processed */\n readonly eventCount: number;\n\n /** Last event timestamp */\n readonly lastEventTime?: Date;\n\n /** Operation context */\n readonly context: string;\n\n /** User-defined tags for categorization */\n readonly tags?: readonly string[];\n\n /** Performance metrics */\n readonly metrics?: ProgressMetrics;\n}\n\n/**\n * Performance metrics for progress tracking\n */\nexport interface ProgressMetrics {\n /** Average event processing time in milliseconds */\n readonly avgProcessingTime: number;\n\n /** Events processed per second */\n readonly eventsPerSecond: number;\n\n /** Memory usage in bytes */\n readonly memoryUsage: number;\n\n /** CPU usage percentage */\n readonly cpuUsage: number;\n}\n\n// =============================================================================\n// Tool Execution Types\n// =============================================================================\n\n/**\n * Tool call request structure\n *\n * @example\n * ```typescript\n * const request: ToolCallRequest = {\n * toolName: 'claude_subagent',\n * arguments: {\n * instruction: 'Analyze this code',\n * project_path: '/path/to/project',\n * model: 'sonnet-4'\n * },\n * timeout: 30000,\n * priority: 'high',\n * metadata: {\n * userId: 'user-123',\n * sessionId: 'session-456'\n * }\n * };\n * ```\n */\nexport interface ToolCallRequest {\n /** Tool name (mapped from subagent name) */\n readonly toolName: string;\n\n /** Tool arguments object */\n readonly arguments: Readonly<Record<string, unknown>>;\n\n /** Request timeout in milliseconds */\n readonly timeout?: number;\n\n /** Request priority level */\n readonly priority?: 'low' | 'normal' | 'high';\n\n /** Additional request metadata */\n readonly metadata?: Readonly<Record<string, unknown>>;\n\n /** Callback for progress events */\n readonly progressCallback?: ProgressCallback;\n\n /** Unique request identifier */\n readonly requestId?: string;\n}\n\n/**\n * Tool call result structure\n */\nexport interface ToolCallResult {\n /** Tool execution result content */\n readonly content: string;\n\n /** Execution status */\n readonly status: ToolExecutionStatus;\n\n /** Execution start time */\n readonly startTime: Date;\n\n /** Execution end time */\n readonly endTime: Date;\n\n /** Total execution duration in milliseconds */\n readonly duration: number;\n\n /** Any error that occurred during execution */\n readonly error?: Error;\n\n /** Progress events generated during execution */\n readonly progressEvents: readonly ProgressEvent[];\n\n /** Tool execution metadata */\n readonly metadata?: ToolExecutionMetadata;\n\n /** Request that generated this result */\n readonly request: ToolCallRequest;\n}\n\n/**\n * Tool execution metadata\n */\nexport interface ToolExecutionMetadata {\n /** Number of tokens used */\n readonly tokensUsed?: number;\n\n /** Estimated cost */\n readonly estimatedCost?: number;\n\n /** Model used for execution */\n readonly model?: string;\n\n /** Server version */\n readonly serverVersion?: string;\n\n /** Performance metrics */\n readonly performanceMetrics?: ToolPerformanceMetrics;\n\n /** Raw subagent response payload (for programmatic capture / session resume) */\n readonly subAgentResponse?: any;\n\n /** Indicates the content string is structured (e.g., JSON) and safe to parse */\n readonly structuredOutput?: boolean;\n\n /** Content type for the tool output (e.g., application/json) */\n readonly contentType?: string;\n\n /** Original raw output emitted by the tool (pre-structuring) */\n readonly rawOutput?: string;\n\n /** Quota limit information detected during execution */\n readonly quotaLimitInfo?: any;\n}\n\n/**\n * Tool performance metrics\n */\nexport interface ToolPerformanceMetrics {\n /** CPU usage during execution */\n readonly cpuUsage: number;\n\n /** Memory usage during execution */\n readonly memoryUsage: number;\n\n /** Network usage in bytes */\n readonly networkUsage: number;\n\n /** Processing time breakdown */\n readonly timingBreakdown: Record<string, number>;\n}\n\n// =============================================================================\n// Subagent Integration Types\n// =============================================================================\n\n/**\n * Subagent information and capabilities\n */\nexport interface SubagentInfo {\n /** Subagent identifier */\n readonly id: SubagentType;\n\n /** Display name */\n readonly name: string;\n\n /** Supported capabilities */\n readonly capabilities: readonly SubagentCapability[];\n\n /** Available models */\n readonly models: readonly string[];\n\n /** Default model */\n readonly defaultModel: string;\n\n /** Current availability status */\n readonly status: SubagentStatus;\n\n /** Rate limiting information */\n readonly rateLimits?: RateLimitInfo;\n\n /** Performance characteristics */\n readonly performance?: SubagentPerformance;\n}\n\n/**\n * Subagent capability types\n */\nexport enum SubagentCapability {\n CODE_GENERATION = 'code_generation',\n CODE_ANALYSIS = 'code_analysis',\n DEBUGGING = 'debugging',\n REFACTORING = 'refactoring',\n DOCUMENTATION = 'documentation',\n TESTING = 'testing',\n ARCHITECTURE = 'architecture',\n REVIEW = 'review',\n}\n\n/**\n * Subagent status\n */\nexport enum SubagentStatus {\n AVAILABLE = 'available',\n BUSY = 'busy',\n RATE_LIMITED = 'rate_limited',\n UNAVAILABLE = 'unavailable',\n ERROR = 'error',\n MAINTENANCE = 'maintenance',\n}\n\n/**\n * Rate limit information\n */\nexport interface RateLimitInfo {\n /** Requests remaining in current window */\n readonly remaining: number;\n\n /** Total requests allowed per window */\n readonly limit: number;\n\n /** Window reset time */\n readonly resetTime: Date;\n\n /** Current rate limit tier */\n readonly tier: string;\n}\n\n/**\n * Subagent performance characteristics\n */\nexport interface SubagentPerformance {\n /** Average response time in milliseconds */\n readonly avgResponseTime: number;\n\n /** Success rate percentage */\n readonly successRate: number;\n\n /** Current load level */\n readonly loadLevel: 'low' | 'medium' | 'high';\n\n /** Quality score (0-100) */\n readonly qualityScore: number;\n}\n\n/**\n * Subagent tool mapping configuration\n */\nexport interface SubagentMapper {\n /** Core subagent to tool name mapping */\n readonly mapping: Readonly<Record<SubagentType, string>>;\n\n /** Alias to subagent mapping */\n readonly aliases: Readonly<Record<SubagentAlias, SubagentType>>;\n\n /** Model validation rules */\n readonly modelValidation: Readonly<Record<SubagentType, ModelValidationRule>>;\n\n /** Default configurations per subagent */\n readonly defaults: Readonly<Record<SubagentType, SubagentDefaults>>;\n}\n\n/**\n * Model validation rule\n */\nexport interface ModelValidationRule {\n /** Allowed models for this subagent */\n readonly allowedModels: readonly string[];\n\n /** Default model if none specified */\n readonly defaultModel: string;\n\n /** Custom validation function */\n readonly customValidator?: (model: string) => boolean;\n}\n\n/**\n * Default subagent configuration\n */\nexport interface SubagentDefaults {\n /** Default timeout in milliseconds */\n readonly timeout: number;\n\n /** Default model */\n readonly model: string;\n\n /** Default arguments */\n readonly arguments: Readonly<Record<string, unknown>>;\n\n /** Default priority */\n readonly priority: 'low' | 'normal' | 'high';\n}\n\n// =============================================================================\n// Connection Management Types\n// =============================================================================\n\n/**\n * Connection lifecycle event\n */\nexport interface ConnectionEvent {\n /** Event type */\n readonly type: ConnectionEventType;\n\n /** Event timestamp */\n readonly timestamp: Date;\n\n /** Connection state after event */\n readonly state: MCPConnectionState;\n\n /** Event details */\n readonly details?: string;\n\n /** Error information if applicable */\n readonly error?: Error;\n}\n\n/**\n * Connection event types\n */\nexport enum ConnectionEventType {\n CONNECTING = 'connecting',\n CONNECTED = 'connected',\n DISCONNECTED = 'disconnected',\n RECONNECTING = 'reconnecting',\n ERROR = 'error',\n TIMEOUT = 'timeout',\n RATE_LIMITED = 'rate_limited',\n}\n\n/**\n * Connection health monitoring\n */\nexport interface ConnectionHealth {\n /** Current connection state */\n readonly state: MCPConnectionState;\n\n /** Connection uptime in milliseconds */\n readonly uptime: number;\n\n /** Number of successful operations */\n readonly successfulOperations: number;\n\n /** Number of failed operations */\n readonly failedOperations: number;\n\n /** Average response time */\n readonly avgResponseTime: number;\n\n /** Last successful operation time */\n readonly lastSuccessTime?: Date;\n\n /** Last error time */\n readonly lastErrorTime?: Date;\n\n /** Current error streak */\n readonly errorStreak: number;\n}\n\n/**\n * Connection recovery strategy\n */\nexport interface RecoveryStrategy {\n /** Strategy type */\n readonly type: RecoveryStrategyType;\n\n /** Strategy configuration */\n readonly config: RecoveryConfig;\n\n /** Custom recovery function */\n readonly customRecovery?: () => Promise<boolean>;\n}\n\n/**\n * Recovery strategy types\n */\nexport enum RecoveryStrategyType {\n IMMEDIATE_RETRY = 'immediate_retry',\n EXPONENTIAL_BACKOFF = 'exponential_backoff',\n CIRCUIT_BREAKER = 'circuit_breaker',\n GRACEFUL_DEGRADATION = 'graceful_degradation',\n CUSTOM = 'custom',\n}\n\n/**\n * Recovery configuration\n */\nexport interface RecoveryConfig {\n /** Maximum recovery attempts */\n readonly maxAttempts: number;\n\n /** Recovery timeout */\n readonly timeout: number;\n\n /** Strategy-specific parameters */\n readonly parameters: Readonly<Record<string, unknown>>;\n}\n\n// =============================================================================\n// Session Integration Types\n// =============================================================================\n\n/**\n * Session context (renamed from MCPSessionContext)\n */\nexport interface SessionContext {\n /** Unique session identifier */\n readonly sessionId: string;\n\n /** Session start time */\n readonly startTime: Date;\n\n /** User identifier */\n readonly userId?: string;\n\n /** Session metadata */\n readonly metadata: Readonly<Record<string, unknown>>;\n\n /** Active tool calls */\n readonly activeToolCalls: readonly string[];\n\n /** Session state */\n readonly state: SessionState;\n\n /** Last activity time */\n readonly lastActivity: Date;\n}\n\n/** @deprecated Use SessionContext instead */\nexport type MCPSessionContext = SessionContext;\n\n/**\n * Session state\n */\nexport enum SessionState {\n INITIALIZING = 'initializing',\n ACTIVE = 'active',\n IDLE = 'idle',\n SUSPENDED = 'suspended',\n COMPLETED = 'completed',\n FAILED = 'failed',\n}\n\n/**\n * Session persistence configuration\n */\nexport interface SessionPersistence {\n /** Enable session persistence */\n readonly enabled: boolean;\n\n /** Storage backend type */\n readonly storageType: SessionStorageType;\n\n /** Storage configuration */\n readonly storageConfig: SessionStorageConfig;\n\n /** Session TTL in milliseconds */\n readonly ttlMs: number;\n\n /** Auto-cleanup interval */\n readonly cleanupIntervalMs: number;\n}\n\n/**\n * Session storage types\n */\nexport enum SessionStorageType {\n MEMORY = 'memory',\n FILE = 'file',\n DATABASE = 'database',\n REDIS = 'redis',\n}\n\n/**\n * Session storage configuration\n */\nexport interface SessionStorageConfig {\n /** Storage-specific parameters */\n readonly parameters: Readonly<Record<string, unknown>>;\n\n /** Encryption configuration */\n readonly encryption?: EncryptionConfig;\n\n /** Compression configuration */\n readonly compression?: CompressionConfig;\n}\n\n/**\n * Encryption configuration\n */\nexport interface EncryptionConfig {\n /** Encryption algorithm */\n readonly algorithm: string;\n\n /** Key derivation parameters */\n readonly keyDerivation: KeyDerivationConfig;\n}\n\n/**\n * Key derivation configuration\n */\nexport interface KeyDerivationConfig {\n /** KDF algorithm */\n readonly algorithm: string;\n\n /** Salt length */\n readonly saltLength: number;\n\n /** Iteration count */\n readonly iterations: number;\n}\n\n/**\n * Compression configuration\n */\nexport interface CompressionConfig {\n /** Compression algorithm */\n readonly algorithm: 'gzip' | 'deflate' | 'brotli';\n\n /** Compression level */\n readonly level: number;\n}\n\n// =============================================================================\n// Error Types - Imported from core/errors.ts\n// =============================================================================\n\n// Import error types from dedicated errors module\nexport type {\n ExecutionError,\n ConnectionError,\n ToolError,\n TimeoutError,\n RateLimitError,\n ValidationError,\n ExecutionErrorOptions,\n RetryInfo,\n ServerInfo,\n ToolInfo,\n ToolExecutionDetails,\n} from '../core/errors.js';\n\n// =============================================================================\n// Utility Types\n// =============================================================================\n\n/**\n * Type-safe event emitter interface for events\n */\nexport interface MCPEventEmitter {\n on<T extends keyof MCPEventMap>(event: T, listener: MCPEventMap[T]): void;\n off<T extends keyof MCPEventMap>(event: T, listener: MCPEventMap[T]): void;\n emit<T extends keyof MCPEventMap>(event: T, ...args: Parameters<MCPEventMap[T]>): boolean;\n}\n\n/**\n * Event map for type-safe event handling\n */\nexport interface MCPEventMap {\n 'connection:state': (state: MCPConnectionState) => void;\n 'connection:error': (error: Error) => void;\n 'progress:event': (event: ProgressEvent) => void;\n 'tool:start': (request: ToolCallRequest) => void;\n 'tool:complete': (result: ToolCallResult) => void;\n 'tool:error': (error: Error) => void;\n 'session:create': (context: SessionContext) => void;\n 'session:end': (sessionId: string) => void;\n 'rate-limit:reached': (error: Error) => void;\n}\n\n/**\n * Utility type for making properties optional\n */\nexport type PartialBy<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;\n\n/**\n * Utility type for making properties required\n */\nexport type RequiredBy<T, K extends keyof T> = T & Required<Pick<T, K>>;\n\n/**\n * Utility type for deep readonly\n */\nexport type DeepReadonly<T> = {\n readonly [P in keyof T]: T[P] extends object ? DeepReadonly<T[P]> : T[P];\n};\n\n/**\n * Utility type for extracting promise return type\n */\nexport type Awaited<T> = T extends Promise<infer U> ? U : T;\n\n/**\n * Type guard for progress events\n */\nexport function isProgressEvent(obj: unknown): obj is ProgressEvent {\n return (\n typeof obj === 'object' &&\n obj !== null &&\n 'sessionId' in obj &&\n 'timestamp' in obj &&\n 'backend' in obj &&\n 'count' in obj &&\n 'type' in obj &&\n 'content' in obj &&\n 'toolId' in obj\n );\n}\n\n// Import type guards from errors module\nexport { isExecutionError } from '../core/errors.js';\n\n/**\n * Type guard for subagent types\n */\nexport function isSubagentType(value: string): value is SubagentType {\n return ['claude', 'cursor', 'codex', 'gemini', 'pi'].includes(value);\n}\n\n/**\n * Type guard for connection states\n */\nexport function isConnectionState(value: string): value is MCPConnectionState {\n return Object.values(MCPConnectionState).includes(value as MCPConnectionState);\n}\n\n// =============================================================================\n// Factory Types\n// =============================================================================\n\n/**\n * Client factory configuration\n */\nexport interface MCPClientFactory {\n /** Create client with configuration */\n create(config: MCPServerConfig): Promise<MCPClient>;\n\n /** Create mock client for testing */\n createMock(mockConfig?: MockClientConfig): MockMCPClient;\n\n /** Validate configuration */\n validateConfig(config: MCPServerConfig): ValidationResult;\n}\n\n/**\n * Mock client configuration for testing\n */\nexport interface MockClientConfig {\n /** Predefined tool responses */\n readonly toolResponses: Readonly<Record<string, string>>;\n\n /** Simulated progress events */\n readonly progressEvents: readonly ProgressEvent[];\n\n /** Simulated errors */\n readonly errors: readonly Error[];\n\n /** Response delays */\n readonly responseDelays: Readonly<Record<string, number>>;\n}\n\n/**\n * Validation result\n */\nexport interface ValidationResult {\n /** Validation success */\n readonly valid: boolean;\n\n /** Validation errors */\n readonly errors: readonly string[];\n\n /** Validation warnings */\n readonly warnings: readonly string[];\n}\n\n/**\n * Abstract client interface\n */\nexport interface MCPClient {\n /** Connect to server */\n connect(): Promise<void>;\n\n /** Disconnect from server */\n disconnect(): Promise<void>;\n\n /** Check connection status */\n isConnected(): boolean;\n\n /** Call tool with progress tracking */\n callTool(request: ToolCallRequest): Promise<ToolCallResult>;\n\n /** List available tools */\n listTools(): Promise<readonly string[]>;\n\n /** Get subagent information */\n getSubagentInfo(subagent: SubagentType): Promise<SubagentInfo>;\n\n /** Add progress callback */\n onProgress(callback: ProgressCallback): () => void;\n\n /** Get connection health */\n getHealth(): ConnectionHealth;\n\n /** Event emitter interface */\n on<T extends keyof MCPEventMap>(event: T, listener: MCPEventMap[T]): void;\n off<T extends keyof MCPEventMap>(event: T, listener: MCPEventMap[T]): void;\n}\n\n/**\n * Mock client interface for testing\n */\nexport interface MockMCPClient extends MCPClient {\n /** Add mock tool response */\n addToolResponse(toolName: string, response: string): void;\n\n /** Simulate progress event */\n simulateProgressEvent(event: ProgressEvent): void;\n\n /** Simulate error */\n simulateError(error: Error): void;\n\n /** Reset mock state */\n reset(): void;\n}\n\n// =============================================================================\n// Constants\n// =============================================================================\n\n/**\n * Default configuration values\n */\nexport const MCP_DEFAULTS = {\n TIMEOUT: 3600000, // 1 hour\n RETRIES: 3,\n RETRY_DELAY: 1000, // 1 second\n MAX_MEMORY_MB: 512,\n PROCESS_PRIORITY: 'normal' as const,\n CONNECTION_TIMEOUT: 30000, // 30 seconds\n HEALTH_CHECK_INTERVAL: 60000, // 1 minute\n SESSION_TTL: 86400000, // 24 hours\n CLEANUP_INTERVAL: 3600000, // 1 hour\n} as const;\n\n/**\n * Subagent to tool mapping\n */\nexport const SUBAGENT_TOOL_MAPPING: Record<SubagentType, string> = {\n claude: 'claude_subagent',\n cursor: 'cursor_subagent',\n codex: 'codex_subagent',\n gemini: 'gemini_subagent',\n pi: 'pi_subagent',\n} as const;\n\n/**\n * Subagent alias mapping\n */\nexport const SUBAGENT_ALIASES: Record<SubagentAlias, SubagentType> = {\n 'claude-code': 'claude',\n claude_code: 'claude',\n 'gemini-cli': 'gemini',\n 'cursor-agent': 'cursor',\n} as const;\n\n/**\n * Progress event parsing patterns\n */\nexport const PROGRESS_PATTERNS = {\n /** Main progress message pattern: \"Backend #count: event_type => content\" */\n MAIN: /^(.+?)\\s+#(\\d+):\\s+(\\w+)\\s*=>\\s*(.+)$/,\n\n /** Tool call patterns for detection */\n TOOL_CALLS: [\n /calling\\s+tool[:\\s]*([a-zA-Z_][a-zA-Z0-9_]*)/i,\n /<function_calls>\\s*<invoke name=\"([^\"]+)\"/i,\n /tool[:\\s]*([a-zA-Z_][a-zA-Z0-9_]*)/i,\n ],\n\n /** Rate limit patterns */\n RATE_LIMITS: [\n /resets\\s+(at\\s+)?(\\d{1,2}):(\\d{2})\\s*(am|pm)?/i,\n /resets\\s+(at\\s+)?(\\d{1,2})\\s*(am|pm)/i,\n /try again in (\\d+)\\s*(minutes?|hours?)/i,\n /5-hour limit reached.*resets\\s+(at\\s+)?(\\d{1,2})\\s*(am|pm)/i,\n ],\n} as const;\n","/**\n * Shell Backend Implementation for juno-code\n *\n * Executes shell scripts from ~/.juno_code/services/ directory\n * Supports JSON streaming output and converts to progress events\n */\n\nimport { spawn, ChildProcess } from 'node:child_process';\nimport { promises as fs } from 'node:fs';\nimport * as path from 'node:path';\nimport os from 'node:os';\nimport fsExtra from 'fs-extra';\nimport type { Backend } from '../backend-manager.js';\nimport {\n ProgressEventType,\n ToolExecutionStatus,\n} from '../../types/execution.js';\nimport type {\n ToolCallRequest,\n ToolCallResult,\n ProgressEvent,\n ProgressCallback,\n ToolExecutionMetadata,\n} from '../../types/execution.js';\nimport { engineLogger } from '../../cli/utils/advanced-logger.js';\n\n// =============================================================================\n// Type Definitions\n// =============================================================================\n\n/**\n * Shell backend configuration\n */\nexport interface ShellBackendConfig {\n /** Working directory for execution */\n workingDirectory: string;\n\n /** Path to services directory (default: ~/.juno_code/services) */\n servicesPath: string;\n\n /** Enable debug logging */\n debug?: boolean;\n\n /** Timeout for script execution in milliseconds */\n timeout?: number;\n\n /** Environment variables to pass to shell scripts */\n environment?: Record<string, string>;\n\n /** Enable JSON streaming parsing */\n enableJsonStreaming?: boolean;\n\n /** Output full JSON format instead of simplified messages (for verbose mode) */\n outputRawJson?: boolean;\n}\n\n/**\n * Script execution result\n */\ninterface ScriptExecutionResult {\n success: boolean;\n output: string;\n error?: string;\n exitCode: number;\n duration: number;\n subAgentResponse?: any;\n metadata?: Record<string, any>;\n}\n\n/**\n * Quota limit information extracted from Claude or Codex response\n */\nexport interface QuotaLimitInfo {\n /** Whether a quota limit was detected */\n detected: boolean;\n /** The parsed reset time as a Date object */\n resetTime?: Date;\n /** Sleep duration in milliseconds until the reset time */\n sleepDurationMs?: number;\n /** The timezone extracted from the message */\n timezone?: string;\n /** Original error message */\n originalMessage?: string;\n /** Which subagent triggered the quota limit */\n source?: 'claude' | 'codex';\n}\n\n// =============================================================================\n// Quota Limit Detection Utilities\n// =============================================================================\n\n/**\n * Common timezone aliases and their UTC offsets\n */\nconst TIMEZONE_OFFSETS: Record<string, number> = {\n // North American timezones\n 'America/Toronto': -5,\n 'America/New_York': -5,\n 'US/Eastern': -5,\n 'America/Chicago': -6,\n 'US/Central': -6,\n 'America/Denver': -7,\n 'US/Mountain': -7,\n 'America/Los_Angeles': -8,\n 'US/Pacific': -8,\n // European timezones\n 'Europe/London': 0,\n UTC: 0,\n GMT: 0,\n 'Europe/Paris': 1,\n 'Europe/Berlin': 1,\n CET: 1,\n // Other common timezones\n 'Asia/Tokyo': 9,\n 'Asia/Shanghai': 8,\n 'Australia/Sydney': 11,\n};\n\n/**\n * Parse reset time from Claude quota limit message\n * Handles formats like:\n * - \"resets 8pm (America/Toronto)\"\n * - \"resets 10am (UTC)\"\n * - \"resets 11:30pm (US/Eastern)\"\n * - \"resets 2:00 PM (America/New_York)\"\n */\nfunction parseResetTime(message: string): { resetTime: Date; timezone: string } | null {\n // Pattern to match: \"resets HH[:MM] [AM/PM] (TIMEZONE)\"\n const resetPattern = /resets\\s+(\\d{1,2})(?::(\\d{2}))?\\s*(am|pm)?\\s*\\(([^)]+)\\)/i;\n const match = message.match(resetPattern);\n\n if (!match) {\n return null;\n }\n\n let hours = parseInt(match[1]!, 10);\n const minutes = match[2] ? parseInt(match[2]!, 10) : 0;\n const ampm = match[3]?.toLowerCase();\n const timezone = match[4]!.trim();\n\n // Convert to 24-hour format\n if (ampm === 'pm' && hours !== 12) {\n hours += 12;\n } else if (ampm === 'am' && hours === 12) {\n hours = 0;\n }\n\n // Get timezone offset (default to local if unknown)\n const timezoneOffset = TIMEZONE_OFFSETS[timezone];\n\n // Create reset time in the specified timezone\n const now = new Date();\n const resetTime = new Date();\n\n if (timezoneOffset !== undefined) {\n // Set the reset time in the target timezone\n resetTime.setUTCHours(hours - timezoneOffset, minutes, 0, 0);\n\n // If the reset time is in the past, add a day\n if (resetTime.getTime() <= now.getTime()) {\n resetTime.setTime(resetTime.getTime() + 24 * 60 * 60 * 1000);\n }\n } else {\n // Fallback: assume it's in the local timezone\n resetTime.setHours(hours, minutes, 0, 0);\n\n // If the reset time is in the past, add a day\n if (resetTime.getTime() <= now.getTime()) {\n resetTime.setTime(resetTime.getTime() + 24 * 60 * 60 * 1000);\n }\n }\n\n return { resetTime, timezone };\n}\n\n/**\n * Parse reset time from Codex quota limit message\n * Handles formats like:\n * - \"try again at Feb 4th, 2026 1:50 AM\"\n * - \"try again at February 4, 2026 1:50 AM\"\n * - \"try again at Jan 15th, 2026 11:30 PM\"\n */\nfunction parseCodexResetTime(message: string): { resetTime: Date } | null {\n // Pattern to match: \"try again at Month Day[st/nd/rd/th], Year HH:MM AM/PM\"\n const resetPattern =\n /try again at\\s+(\\w+)\\s+(\\d{1,2})(?:st|nd|rd|th)?,?\\s*(\\d{4})\\s+(\\d{1,2}):(\\d{2})\\s*(AM|PM)/i;\n const match = message.match(resetPattern);\n\n if (!match) {\n return null;\n }\n\n const monthStr = match[1]!;\n const day = parseInt(match[2]!, 10);\n const year = parseInt(match[3]!, 10);\n let hours = parseInt(match[4]!, 10);\n const minutes = parseInt(match[5]!, 10);\n const ampm = match[6]!.toUpperCase();\n\n // Convert month name to number\n const MONTH_MAP: Record<string, number> = {\n jan: 0,\n january: 0,\n feb: 1,\n february: 1,\n mar: 2,\n march: 2,\n apr: 3,\n april: 3,\n may: 4,\n jun: 5,\n june: 5,\n jul: 6,\n july: 6,\n aug: 7,\n august: 7,\n sep: 8,\n september: 8,\n oct: 9,\n october: 9,\n nov: 10,\n november: 10,\n dec: 11,\n december: 11,\n };\n\n const month = MONTH_MAP[monthStr.toLowerCase()];\n if (month === undefined) {\n return null;\n }\n\n // Convert 12-hour format to 24-hour format\n if (ampm === 'PM' && hours !== 12) {\n hours += 12;\n } else if (ampm === 'AM' && hours === 12) {\n hours = 0;\n }\n\n // Codex provides an absolute date/time, construct it directly\n // The time is assumed to be in the user's local timezone (Codex doesn't specify timezone)\n const resetTime = new Date(year, month, day, hours, minutes, 0, 0);\n\n // If the reset time is in the past, it's likely already passed; add 24h as fallback\n const now = new Date();\n if (resetTime.getTime() <= now.getTime()) {\n resetTime.setTime(resetTime.getTime() + 24 * 60 * 60 * 1000);\n }\n\n return { resetTime };\n}\n\n/**\n * Detect and parse quota limit error from Claude or Codex response\n */\nexport function detectQuotaLimit(message: string | undefined | null): QuotaLimitInfo {\n if (!message || typeof message !== 'string') {\n return { detected: false };\n }\n\n // Check for quota limit patterns:\n // Claude: \"You've hit your limit · resets 8pm (America/Toronto)\"\n // Codex: \"You've hit your usage limit. ... try again at Feb 4th, 2026 1:50 AM.\"\n const claudePattern = /you'?ve hit your limit/i;\n const codexPattern = /you'?ve hit your usage limit/i;\n\n const isClaudeQuota = claudePattern.test(message) && !codexPattern.test(message);\n const isCodexQuota = codexPattern.test(message);\n\n if (!isClaudeQuota && !isCodexQuota) {\n return { detected: false };\n }\n\n const source = isCodexQuota ? 'codex' : 'claude';\n\n // Try to parse the reset time - Claude format first, then Codex format\n const parsedClaude = parseResetTime(message);\n if (parsedClaude) {\n const now = new Date();\n const sleepDurationMs = Math.max(0, parsedClaude.resetTime.getTime() - now.getTime());\n\n return {\n detected: true,\n resetTime: parsedClaude.resetTime,\n sleepDurationMs,\n timezone: parsedClaude.timezone,\n originalMessage: message,\n source,\n };\n }\n\n // Try Codex reset time format (\"try again at Feb 4th, 2026 1:50 AM\")\n const parsedCodex = parseCodexResetTime(message);\n if (parsedCodex) {\n const now = new Date();\n const sleepDurationMs = Math.max(0, parsedCodex.resetTime.getTime() - now.getTime());\n\n return {\n detected: true,\n resetTime: parsedCodex.resetTime,\n sleepDurationMs,\n timezone: 'local',\n originalMessage: message,\n source,\n };\n }\n\n // Quota limit detected but couldn't parse reset time\n // Default to 5 minutes wait\n return {\n detected: true,\n sleepDurationMs: 5 * 60 * 1000, // 5 minutes default\n originalMessage: message,\n source,\n };\n}\n\n/**\n * Format duration in human-readable form\n */\nexport function formatDuration(ms: number): string {\n const totalSeconds = Math.ceil(ms / 1000);\n const hours = Math.floor(totalSeconds / 3600);\n const minutes = Math.floor((totalSeconds % 3600) / 60);\n const seconds = totalSeconds % 60;\n\n const parts: string[] = [];\n if (hours > 0) parts.push(`${hours}h`);\n if (minutes > 0) parts.push(`${minutes}m`);\n if (seconds > 0 || parts.length === 0) parts.push(`${seconds}s`);\n\n return parts.join(' ');\n}\n\n// =============================================================================\n// Shell Backend Implementation\n// =============================================================================\n\n/**\n * Shell backend that executes scripts from ~/.juno_code/services/\n */\nexport class ShellBackend implements Backend {\n readonly type = 'shell' as const;\n readonly name = 'Shell Scripts Backend';\n\n private config: ShellBackendConfig | null = null;\n private progressCallbacks: ProgressCallback[] = [];\n private eventCounter = 0;\n private jsonBuffer = ''; // Buffer for handling partial JSON objects\n private logFilePath: string | null = null; // Path to current log file\n\n /**\n * Configure the shell backend\n */\n configure(config: ShellBackendConfig): void {\n this.config = config;\n }\n\n /**\n * Initialize the backend\n */\n async initialize(): Promise<void> {\n if (!this.config) {\n throw new Error('Shell backend not configured. Call configure() first.');\n }\n\n // Ensure services directory exists\n try {\n await fs.access(this.config.servicesPath);\n } catch (error) {\n throw new Error(\n `Services directory not found: ${this.config.servicesPath}. Please create the directory and add subagent scripts.`,\n );\n }\n\n if (this.config.debug) {\n engineLogger.info(\n `Shell backend initialized with services path: ${this.config.servicesPath}`,\n );\n }\n }\n\n /**\n * Execute a tool call request using shell scripts\n */\n async execute(request: ToolCallRequest): Promise<ToolCallResult> {\n if (!this.config) {\n throw new Error('Shell backend not configured');\n }\n\n const startTime = Date.now();\n const toolId = `shell_${request.toolName}_${startTime}`;\n\n // Extract subagent name and create log file\n const subagentType = this.extractSubagentFromToolName(request.toolName);\n try {\n this.logFilePath = await this.createLogFile(subagentType);\n } catch (error) {\n // Log creation failed - continue without file logging\n if (this.config.debug) {\n engineLogger.warn(\n `Failed to create log file, continuing without file logging: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n this.logFilePath = null;\n }\n\n // Emit tool start event\n await this.emitProgressEvent({\n sessionId: (request.metadata?.sessionId as string) || 'unknown',\n timestamp: new Date(),\n backend: 'shell',\n count: ++this.eventCounter,\n type: ProgressEventType.TOOL_START,\n content: `Starting ${request.toolName} via shell script`,\n toolId,\n metadata: {\n toolName: request.toolName,\n arguments: request.arguments,\n phase: 'initialization',\n },\n });\n\n try {\n // Find appropriate script for the subagent (already extracted above)\n const scriptPath = await this.findScriptForSubagent(subagentType);\n\n // Execute the script\n const result = await this.executeScript(scriptPath, request, toolId, subagentType);\n\n const duration = Date.now() - startTime;\n\n // Emit completion event\n await this.emitProgressEvent({\n sessionId: (request.metadata?.sessionId as string) || 'unknown',\n timestamp: new Date(),\n backend: 'shell',\n count: ++this.eventCounter,\n type: ProgressEventType.TOOL_RESULT,\n content: `${request.toolName} completed successfully (${duration}ms)`,\n toolId,\n metadata: {\n toolName: request.toolName,\n duration,\n success: result.success,\n phase: 'completion',\n },\n });\n\n const structuredResult = this.buildStructuredOutput(subagentType, result);\n\n const toolResult: Record<string, unknown> = {\n content: structuredResult.content,\n status: result.success ? ToolExecutionStatus.COMPLETED : ToolExecutionStatus.FAILED,\n startTime: new Date(startTime),\n endTime: new Date(),\n duration,\n progressEvents: [] as ProgressEvent[],\n request,\n };\n if (result.error) {\n toolResult.error = new Error(result.error);\n }\n if (structuredResult.metadata) {\n toolResult.metadata = structuredResult.metadata;\n }\n return toolResult as unknown as ToolCallResult;\n } catch (error) {\n const duration = Date.now() - startTime;\n\n // Emit error event\n await this.emitProgressEvent({\n sessionId: (request.metadata?.sessionId as string) || 'unknown',\n timestamp: new Date(),\n backend: 'shell',\n count: ++this.eventCounter,\n type: ProgressEventType.ERROR,\n content: `${request.toolName} failed: ${error instanceof Error ? error.message : String(error)}`,\n toolId,\n metadata: {\n toolName: request.toolName,\n duration,\n success: false,\n error: error instanceof Error ? error.message : String(error),\n phase: 'error',\n },\n });\n\n throw error;\n }\n }\n\n /**\n * Check if shell backend is available\n */\n async isAvailable(): Promise<boolean> {\n if (!this.config) {\n return false;\n }\n\n try {\n // Check if services directory exists\n const stats = await fs.stat(this.config.servicesPath);\n if (!stats.isDirectory()) {\n return false;\n }\n\n // Check if at least one subagent script exists\n const scripts = await this.findAvailableScripts();\n return scripts.length > 0;\n } catch (error) {\n return false;\n }\n }\n\n /**\n * Set progress callback\n */\n onProgress(callback: ProgressCallback): () => void {\n this.progressCallbacks.push(callback);\n return () => {\n const index = this.progressCallbacks.indexOf(callback);\n if (index !== -1) {\n this.progressCallbacks.splice(index, 1);\n }\n };\n }\n\n /**\n * Clean up resources\n */\n async cleanup(): Promise<void> {\n // Nothing to clean up for shell backend\n this.progressCallbacks = [];\n }\n\n // =============================================================================\n // Private Implementation Methods\n // =============================================================================\n\n /**\n * Create log file path and ensure log directory exists\n */\n private async createLogFile(subagentName: string): Promise<string> {\n // Format timestamp as YYYYMMDD_HHMMSS\n const now = new Date();\n const timestamp =\n now.getFullYear().toString() +\n (now.getMonth() + 1).toString().padStart(2, '0') +\n now.getDate().toString().padStart(2, '0') +\n '_' +\n now.getHours().toString().padStart(2, '0') +\n now.getMinutes().toString().padStart(2, '0') +\n now.getSeconds().toString().padStart(2, '0');\n\n // Create log directory path\n const logDir = path.join(this.config!.workingDirectory, '.juno_task', 'logs');\n\n // Ensure log directory exists\n try {\n await fsExtra.ensureDir(logDir);\n } catch (error) {\n if (this.config?.debug) {\n engineLogger.warn(\n `Failed to create log directory: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n throw new Error(`Failed to create log directory: ${logDir}`);\n }\n\n // Create log file path\n const logFileName = `${subagentName}_shell_${timestamp}.log`;\n const logFilePath = path.join(logDir, logFileName);\n\n if (this.config?.debug) {\n engineLogger.debug(`Created log file path: ${logFilePath}`);\n }\n\n return logFilePath;\n }\n\n /**\n * Write log entry to file\n */\n private async writeToLogFile(message: string): Promise<void> {\n if (!this.logFilePath) {\n return; // No log file configured\n }\n\n try {\n // Append to log file with timestamp\n const timestamp = new Date().toISOString();\n const logEntry = `[${timestamp}] ${message}\\n`;\n await fsExtra.appendFile(this.logFilePath, logEntry, 'utf-8');\n } catch (error) {\n // Don't throw - just log the error if debug is enabled\n if (this.config?.debug) {\n engineLogger.warn(\n `Failed to write to log file: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n }\n\n /**\n * Extract subagent type from tool name\n */\n private extractSubagentFromToolName(toolName: string): string {\n // Map tool names to subagent types\n const toolMapping: Record<string, string> = {\n claude_subagent: 'claude',\n cursor_subagent: 'cursor',\n codex_subagent: 'codex',\n gemini_subagent: 'gemini',\n pi_subagent: 'pi',\n };\n\n return toolMapping[toolName] || toolName.replace('_subagent', '');\n }\n\n /**\n * Find script for a specific subagent\n */\n private async findScriptForSubagent(subagent: string): Promise<string> {\n const possibleNames = [\n `${subagent}.py`, // Subagent-specific Python script (e.g. claude.py, codex.py)\n `${subagent}.sh`, // Subagent-specific shell script\n `subagent.py`, // Generic Python script (fallback)\n `subagent.sh`, // Generic shell script (fallback)\n ];\n\n const checkedPaths: string[] = [];\n\n for (const name of possibleNames) {\n const scriptPath = path.join(this.config!.servicesPath, name);\n checkedPaths.push(scriptPath);\n\n try {\n const stats = await fs.stat(scriptPath);\n if (stats.isFile()) {\n if (this.config!.debug) {\n engineLogger.debug(`Found script for ${subagent}: ${scriptPath}`);\n }\n return scriptPath;\n }\n } catch (error) {\n // Continue to next possibility\n if (this.config!.debug) {\n engineLogger.debug(`Script not found: ${scriptPath}`);\n }\n }\n }\n\n throw new Error(\n `No script found for subagent: ${subagent}. Checked paths: ${checkedPaths.join(', ')}`,\n );\n }\n\n /**\n * Find all available scripts in services directory\n */\n private async findAvailableScripts(): Promise<string[]> {\n try {\n const files = await fs.readdir(this.config!.servicesPath);\n const scriptFiles = files.filter((file) => file.endsWith('.py') || file.endsWith('.sh'));\n return scriptFiles;\n } catch (error) {\n return [];\n }\n }\n\n /**\n * Execute a shell script\n */\n private async executeScript(\n scriptPath: string,\n request: ToolCallRequest,\n toolId: string,\n subagentType: string,\n ): Promise<ScriptExecutionResult> {\n return new Promise(async (resolve, reject) => {\n const startTime = Date.now();\n const isPython = scriptPath.endsWith('.py');\n const isGemini = subagentType === 'gemini';\n\n // Prepare environment variables\n const env: Record<string, string | undefined> = {\n ...process.env,\n ...this.config!.environment,\n // Pass request data as environment variables\n JUNO_INSTRUCTION: String(request.arguments?.instruction ?? ''),\n JUNO_PROJECT_PATH: String(request.arguments?.project_path ?? this.config!.workingDirectory),\n JUNO_MODEL: String(request.arguments?.model ?? ''),\n JUNO_ITERATION: String(request.arguments?.iteration ?? 1),\n JUNO_TOOL_ID: toolId,\n };\n\n if (isGemini) {\n env.GEMINI_OUTPUT_FORMAT = env.GEMINI_OUTPUT_FORMAT || 'stream-json';\n }\n\n // Capture file for structured subagent responses (claude.py, pi.py, codex.py support)\n let captureDir: string | null = null;\n let capturePath: string | null = null;\n if (subagentType === 'claude' || subagentType === 'pi' || subagentType === 'codex') {\n try {\n captureDir = await fs.mkdtemp(path.join(os.tmpdir(), 'juno-shell-'));\n capturePath = path.join(captureDir, `subagent_${toolId}.json`);\n env.JUNO_SUBAGENT_CAPTURE_PATH = capturePath;\n } catch (error) {\n if (this.config?.debug) {\n engineLogger.warn(\n `Failed to prepare subagent capture path: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n }\n\n // Build command arguments for the script\n const command = isPython ? 'python3' : 'bash';\n const args = [scriptPath];\n\n // For Python scripts, add the prompt as -p argument\n if (isPython && request.arguments?.instruction) {\n args.push('-p', String(request.arguments.instruction));\n }\n\n // For Python scripts, add the model as -m argument if provided\n if (isPython && request.arguments?.model) {\n args.push('-m', String(request.arguments.model));\n }\n\n // For Gemini, force stream-json output format by default to preserve headless parity\n if (isPython && isGemini) {\n args.push('--output-format', env.GEMINI_OUTPUT_FORMAT || 'stream-json');\n }\n\n // For Python scripts, add the agents configuration if provided\n if (isPython && request.arguments?.agents) {\n args.push('--agents', String(request.arguments.agents));\n }\n\n // For Python scripts, add available tools from built-in set if provided (--tools)\n if (isPython && request.arguments?.tools && Array.isArray(request.arguments.tools)) {\n args.push('--tools');\n args.push(...(request.arguments.tools as string[]));\n }\n\n // For Python scripts, add permission-based allowed tools if provided (--allowedTools)\n if (\n isPython &&\n request.arguments?.allowedTools &&\n Array.isArray(request.arguments.allowedTools)\n ) {\n args.push('--allowedTools');\n args.push(...(request.arguments.allowedTools as string[]));\n }\n\n // For Python scripts, add append allowed tools if provided (--appendAllowedTools)\n if (\n isPython &&\n request.arguments?.appendAllowedTools &&\n Array.isArray(request.arguments.appendAllowedTools)\n ) {\n args.push('--appendAllowedTools');\n args.push(...(request.arguments.appendAllowedTools as string[]));\n }\n\n // For Python scripts, add disallowed tools if provided (--disallowedTools)\n if (\n isPython &&\n request.arguments?.disallowedTools &&\n Array.isArray(request.arguments.disallowedTools)\n ) {\n args.push('--disallowedTools');\n args.push(...(request.arguments.disallowedTools as string[]));\n }\n\n // For Python scripts, add resume flag if provided (--resume SESSION_ID)\n if (isPython && request.arguments?.resume) {\n args.push('--resume', String(request.arguments.resume));\n }\n\n // For Python scripts, add continue flag if provided (--continue)\n if (isPython && request.arguments?.continueConversation) {\n args.push('--continue');\n }\n\n // For Pi subagent, explicitly pass --cd for working directory\n if (isPython && subagentType === 'pi' && request.arguments?.project_path) {\n args.push('--cd', String(request.arguments.project_path));\n }\n\n // For Python scripts, pass verbose flag if verbose mode is enabled\n if (isPython && this.config!.debug) {\n args.push('--verbose');\n }\n\n if (this.config!.debug) {\n // Show command with truncated prompt for readability\n const displayArgs = args.map((a, i) => {\n if (i > 0 && args[i - 1] === '-p' && a.length > 200) {\n return `\"${a.substring(0, 200)}...\" (${a.length} chars)`;\n }\n return a;\n });\n engineLogger.debug(`Executing script: ${command} ${displayArgs.join(' ')}`);\n engineLogger.debug(`Working directory: ${this.config!.workingDirectory}`);\n engineLogger.debug(`Subagent type: ${subagentType}`);\n engineLogger.debug(\n `Environment variables: ${Object.keys(env)\n .filter((k) => k.startsWith('JUNO_') || k.startsWith('PI_'))\n .join(', ')}`,\n );\n }\n\n // Spawn the process\n const child: ChildProcess = spawn(command, args, {\n env,\n cwd: this.config!.workingDirectory,\n stdio: ['pipe', 'pipe', 'pipe'],\n });\n\n // Close stdin immediately - we don't need it and it prevents the subprocess from waiting\n if (child.stdin) {\n child.stdin.end();\n }\n\n let stdout = '';\n let stderr = '';\n let isProcessKilled = false;\n\n // Handle stdout (JSON streaming or TEXT streaming)\n child.stdout?.on('data', (chunk: Buffer) => {\n const data = chunk.toString();\n stdout += data;\n\n if (this.config!.debug) {\n engineLogger.debug(`Script stdout chunk: ${data.length} bytes`);\n }\n\n // Try to parse and emit streaming events (handles both JSON and TEXT formats)\n if (this.config!.enableJsonStreaming !== false) {\n try {\n this.parseAndEmitStreamingEvents(\n data,\n (request.metadata?.sessionId as string) || 'unknown',\n toolId,\n );\n } catch (error) {\n if (this.config!.debug) {\n engineLogger.warn(\n `Streaming parse error: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n }\n });\n\n // Handle stderr - stream as progress events for user visibility\n child.stderr?.on('data', (chunk: Buffer) => {\n const errorData = chunk.toString();\n stderr += errorData;\n\n if (this.config!.debug) {\n engineLogger.debug(`Script stderr: ${errorData}`);\n }\n\n // Emit stderr lines as progress events so errors are visible during execution\n const lines = errorData.split('\\n');\n for (const line of lines) {\n if (!line.trim()) continue;\n this.emitProgressEvent({\n sessionId: (request.metadata?.sessionId as string) || 'unknown',\n timestamp: new Date(),\n backend: 'shell',\n count: ++this.eventCounter,\n type: ProgressEventType.THINKING,\n content: line,\n toolId,\n metadata: {\n format: 'text',\n source: 'stderr',\n raw: true,\n },\n }).catch((error) => {\n if (this.config?.debug) {\n engineLogger.warn(\n `Failed to emit stderr progress event: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n });\n }\n });\n\n // Handle process completion\n child.on('close', (exitCode) => {\n void (async () => {\n if (isProcessKilled) return; // Prevent double resolution\n\n const duration = Date.now() - startTime;\n const success = exitCode === 0;\n\n let subAgentResponse: any;\n if (capturePath) {\n try {\n const captured = await fs.readFile(capturePath, 'utf-8');\n if (captured.trim()) {\n subAgentResponse = JSON.parse(captured);\n }\n } catch (error) {\n if (this.config?.debug) {\n engineLogger.warn(\n `Failed to read subagent capture: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n } finally {\n if (captureDir) {\n try {\n await fs.rm(captureDir, { recursive: true, force: true });\n } catch (cleanupError) {\n if (this.config?.debug) {\n engineLogger.warn(\n `Failed to clean capture directory: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`,\n );\n }\n }\n }\n }\n }\n\n if (this.config!.debug) {\n engineLogger.debug(\n `Script execution completed with exit code: ${exitCode}, duration: ${duration}ms`,\n );\n engineLogger.debug(`Stdout length: ${stdout.length}, Stderr length: ${stderr.length}`);\n }\n\n const execResult: ScriptExecutionResult = {\n success,\n output: stdout,\n exitCode: exitCode || 0,\n duration,\n };\n if (stderr) {\n execResult.error = stderr;\n }\n if (subAgentResponse) {\n execResult.subAgentResponse = subAgentResponse;\n }\n resolve(execResult);\n })();\n });\n\n // Handle process errors\n child.on('error', (error) => {\n if (isProcessKilled) return; // Prevent double resolution\n\n if (this.config!.debug) {\n engineLogger.error(`Script execution error: ${error.message}`);\n }\n reject(new Error(`Failed to execute script: ${error.message}`));\n });\n\n // Apply timeout if configured\n const timeout = this.config!.timeout || 43200000; // 12 hours default for long-running operations\n const timer = setTimeout(() => {\n if (isProcessKilled) return;\n\n isProcessKilled = true;\n if (this.config!.debug) {\n engineLogger.warn(`Script execution timed out after ${timeout}ms, killing process`);\n }\n\n child.kill('SIGTERM');\n\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\n reject(new Error(`Script execution timed out after ${timeout}ms`));\n }, timeout);\n\n // Clear timeout when process completes\n child.on('close', () => {\n clearTimeout(timer);\n });\n\n child.on('error', () => {\n clearTimeout(timer);\n });\n });\n }\n\n /**\n * Build a structured, JSON-parsable result payload for programmatic capture while\n * preserving the shell backend's existing on-screen streaming behavior.\n */\n private buildStructuredOutput(\n subagentType: string,\n result: ScriptExecutionResult,\n ): { content: string; metadata?: ToolExecutionMetadata } {\n if (subagentType === 'claude') {\n const claudeEvent = result.subAgentResponse ?? this.extractLastJsonEvent(result.output);\n const isError = claudeEvent?.is_error ?? claudeEvent?.subtype === 'error' ?? !result.success;\n\n // Check for quota limit error\n const resultText = claudeEvent?.result ?? claudeEvent?.error ?? '';\n const quotaLimitInfo = detectQuotaLimit(resultText);\n\n const structuredPayload = {\n type: 'result',\n subtype: claudeEvent?.subtype || (isError ? 'error' : 'success'),\n is_error: isError,\n result: claudeEvent?.result ?? claudeEvent?.error ?? claudeEvent?.content ?? result.output,\n error: claudeEvent?.error,\n stderr: result.error,\n datetime: claudeEvent?.datetime,\n counter: claudeEvent?.counter,\n session_id: claudeEvent?.session_id,\n num_turns: claudeEvent?.num_turns,\n duration_ms: claudeEvent?.duration_ms ?? result.duration,\n exit_code: result.exitCode,\n total_cost_usd: claudeEvent?.total_cost_usd,\n usage: claudeEvent?.usage,\n modelUsage: claudeEvent?.modelUsage || claudeEvent?.model_usage || {},\n permission_denials: claudeEvent?.permission_denials || [],\n uuid: claudeEvent?.uuid,\n sub_agent_response: claudeEvent,\n // Add quota limit info if detected\n ...(quotaLimitInfo.detected && { quota_limit: quotaLimitInfo }),\n };\n\n const metadataObj: Record<string, unknown> = {\n structuredOutput: true,\n contentType: 'application/json',\n rawOutput: result.output,\n };\n if (claudeEvent) {\n metadataObj.subAgentResponse = claudeEvent;\n }\n if (quotaLimitInfo.detected) {\n metadataObj.quotaLimitInfo = quotaLimitInfo;\n }\n const metadata = metadataObj as ToolExecutionMetadata;\n\n return {\n content: JSON.stringify(structuredPayload),\n metadata,\n };\n }\n\n // Check for Codex quota limit errors in output\n if (subagentType === 'codex') {\n // Codex streams JSON events; look for error/turn.failed events with quota messages\n const codexQuotaMessage = this.extractCodexQuotaMessage(result.output, result.error);\n if (codexQuotaMessage) {\n const quotaLimitInfo = detectQuotaLimit(codexQuotaMessage);\n if (quotaLimitInfo.detected) {\n const metadata: ToolExecutionMetadata = {\n structuredOutput: true,\n contentType: 'application/json',\n rawOutput: result.output,\n quotaLimitInfo,\n };\n const structuredPayload = {\n type: 'result',\n subtype: 'error',\n is_error: true,\n result: codexQuotaMessage,\n error: codexQuotaMessage,\n exit_code: result.exitCode,\n duration_ms: result.duration,\n quota_limit: quotaLimitInfo,\n };\n return {\n content: JSON.stringify(structuredPayload),\n metadata,\n };\n }\n }\n }\n\n // For Codex subagent: extract structured result from capture file or last JSON event\n if (subagentType === 'codex') {\n const codexEvent = result.subAgentResponse ?? this.extractLastJsonEvent(result.output);\n if (codexEvent) {\n const isError = codexEvent.is_error ?? !result.success;\n // Extract message text from agent_message event format\n // Codex events can be: {msg: {message: \"...\"}} (legacy) or {item: {text: \"...\"}} (item.completed)\n const msgPayload = codexEvent.msg ?? codexEvent;\n const itemPayload =\n typeof codexEvent.item === 'object' && codexEvent.item ? codexEvent.item : undefined;\n const messageText =\n msgPayload.message ??\n msgPayload.text ??\n itemPayload?.text ??\n itemPayload?.message ??\n msgPayload.content ??\n result.output;\n const structuredPayload = {\n type: 'result',\n subtype: codexEvent.subtype || (isError ? 'error' : 'success'),\n is_error: isError,\n result: messageText,\n error: isError ? messageText : undefined,\n stderr: result.error,\n exit_code: result.exitCode,\n duration_ms: result.duration,\n sub_agent_response: codexEvent,\n };\n const metadata: ToolExecutionMetadata = {\n ...(codexEvent ? { subAgentResponse: codexEvent } : undefined),\n structuredOutput: true,\n contentType: 'application/json',\n rawOutput: result.output,\n };\n return {\n content: JSON.stringify(structuredPayload),\n metadata,\n };\n }\n }\n\n // For Pi subagent: extract structured result from capture file or last JSON event\n if (subagentType === 'pi') {\n const piEvent = result.subAgentResponse ?? this.extractLastJsonEvent(result.output);\n if (piEvent) {\n // Extract result text: prefer .result, fall back to .messages array (agent_end events)\n let resultText: string | undefined = piEvent.result;\n if (!resultText && Array.isArray(piEvent.messages)) {\n // agent_end event: extract last assistant message text\n for (let i = piEvent.messages.length - 1; i >= 0; i--) {\n const msg = piEvent.messages[i];\n if (msg?.role === 'assistant') {\n // Extract text from content array\n const content = msg.content;\n if (typeof content === 'string') {\n resultText = content;\n } else if (Array.isArray(content)) {\n const texts: string[] = [];\n for (const item of content) {\n if (typeof item === 'string') texts.push(item);\n else if (item?.type === 'text' && typeof item.text === 'string')\n texts.push(item.text);\n }\n resultText = texts.join('\\n');\n }\n if (resultText) break;\n }\n }\n }\n if (resultText) {\n const isError = piEvent.is_error ?? !result.success;\n // Sanitize piEvent: strip bulky messages array and redundant type from sub_agent_response\n // to reduce token usage in the structured output\n const sanitizedPiEvent = { ...piEvent };\n delete sanitizedPiEvent.messages;\n // Also sanitize nested sub_agent_response if present (from pi.py capture)\n if (\n sanitizedPiEvent.sub_agent_response &&\n typeof sanitizedPiEvent.sub_agent_response === 'object'\n ) {\n const inner = { ...sanitizedPiEvent.sub_agent_response };\n delete inner.messages;\n delete inner.type;\n sanitizedPiEvent.sub_agent_response = inner;\n }\n const structuredPayload = {\n type: 'result',\n subtype: piEvent.subtype || (isError ? 'error' : 'success'),\n is_error: isError,\n result: resultText,\n error: piEvent.error,\n stderr: result.error,\n session_id: piEvent.session_id,\n exit_code: result.exitCode,\n duration_ms: piEvent.duration_ms ?? result.duration,\n usage: piEvent.usage,\n sub_agent_response: sanitizedPiEvent,\n };\n const metadata: ToolExecutionMetadata = {\n ...(piEvent ? { subAgentResponse: piEvent } : undefined),\n structuredOutput: true,\n contentType: 'application/json',\n rawOutput: result.output,\n };\n return {\n content: JSON.stringify(structuredPayload),\n metadata,\n };\n }\n }\n }\n\n // For generic subagents: build structured error output on failure\n if (!result.success) {\n const errorMessage = result.error?.trim() || result.output?.trim() || 'Unknown error';\n const structuredPayload = {\n type: 'result',\n subtype: 'error',\n is_error: true,\n result: errorMessage,\n error: errorMessage,\n stderr: result.error,\n exit_code: result.exitCode,\n duration_ms: result.duration,\n };\n const metadata: ToolExecutionMetadata = {\n structuredOutput: true,\n contentType: 'application/json',\n rawOutput: result.output,\n };\n return {\n content: JSON.stringify(structuredPayload),\n metadata,\n };\n }\n\n const returnValue: { content: string; metadata?: ToolExecutionMetadata } = {\n content: result.output,\n };\n if (result.metadata) {\n returnValue.metadata = result.metadata as ToolExecutionMetadata;\n }\n return returnValue;\n }\n\n /**\n * Extract quota limit message from Codex stream output\n * Codex outputs JSON events like:\n * {\"type\": \"error\", \"message\": \"You've hit your usage limit...\"}\n * {\"type\": \"turn.failed\", \"error\": {\"message\": \"You've hit your usage limit...\"}}\n */\n private extractCodexQuotaMessage(output: string, stderr?: string): string | null {\n const sources = [output, stderr].filter(Boolean);\n\n for (const source of sources) {\n const lines = source!\n .split('\\n')\n .map((l) => l.trim())\n .filter(Boolean);\n for (const line of lines) {\n try {\n const parsed = JSON.parse(line);\n // Check type=error events\n if (parsed?.type === 'error' && parsed?.message) {\n if (/you'?ve hit your usage limit/i.test(parsed.message)) {\n return parsed.message;\n }\n }\n // Check type=turn.failed events\n if (parsed?.type === 'turn.failed' && parsed?.error?.message) {\n if (/you'?ve hit your usage limit/i.test(parsed.error.message)) {\n return parsed.error.message;\n }\n }\n } catch {\n // Not JSON, check as plain text\n if (/you'?ve hit your usage limit/i.test(line)) {\n return line;\n }\n }\n }\n }\n\n return null;\n }\n\n /**\n * Extract the last valid JSON object from a script's stdout to use as a structured payload fallback.\n */\n private extractLastJsonEvent(output: string): any | null {\n if (!output) {\n return null;\n }\n\n const lines = output\n .split('\\n')\n .map((line) => line.trim())\n .filter(Boolean);\n\n for (let i = lines.length - 1; i >= 0; i--) {\n try {\n const parsed = JSON.parse(lines[i]!);\n if (parsed && typeof parsed === 'object') {\n return parsed;\n }\n } catch {\n // Ignore parse failures and continue scanning earlier lines\n }\n }\n\n return null;\n }\n\n /**\n * Parse streaming events from script output\n * Handles both JSON format (Claude) and TEXT format (Codex)\n *\n * Strategy:\n * 1. Try to parse each line as JSON first (for Claude)\n * 2. If JSON parsing fails, treat as TEXT streaming (for Codex and other text-based subagents)\n * 3. Emit all text lines (including whitespace-only) as progress events for real-time display\n */\n private parseAndEmitStreamingEvents(data: string, sessionId: string, toolId?: string): void {\n // Handle partial lines by maintaining a buffer\n if (!this.jsonBuffer) {\n this.jsonBuffer = '';\n }\n\n this.jsonBuffer += data;\n\n const streamToolId = toolId || `stream_${Date.now()}`;\n\n // Split by lines, but keep the last potentially incomplete line in buffer\n const lines = this.jsonBuffer.split('\\n');\n this.jsonBuffer = lines.pop() || ''; // Keep last incomplete line\n\n // Process complete lines\n for (const line of lines) {\n const rawLine = line.endsWith('\\r') ? line.slice(0, -1) : line;\n if (!rawLine) continue;\n\n const hasNonWhitespace = rawLine.trim().length > 0;\n\n // Preserve whitespace-only lines (tabs/spaces) as-is for accurate pretty output rendering\n if (!hasNonWhitespace) {\n this.emitProgressEvent({\n sessionId,\n timestamp: new Date(),\n backend: 'shell',\n count: ++this.eventCounter,\n type: ProgressEventType.THINKING,\n content: rawLine,\n toolId: streamToolId,\n metadata: {\n format: 'text',\n raw: true,\n },\n }).catch((error) => {\n if (this.config?.debug) {\n engineLogger.warn(\n `Failed to emit whitespace-only streaming event: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n });\n continue;\n }\n\n const trimmedLine = rawLine.trim();\n\n // Try JSON parsing first (for Claude and other JSON-outputting subagents)\n let isJsonParsed = false;\n try {\n const jsonEvent = JSON.parse(trimmedLine);\n\n // Detect format: Claude CLI or generic StreamingEvent\n let progressEvent: ProgressEvent;\n\n if (this.isClaudeCliEvent(jsonEvent)) {\n // Handle Claude CLI specific format\n // Pass the original trimmedLine for raw JSON output mode\n progressEvent = this.convertClaudeEventToProgress(jsonEvent, sessionId, rawLine, streamToolId);\n isJsonParsed = true;\n } else if (this.isGenericStreamingEvent(jsonEvent)) {\n // Handle generic StreamingEvent format\n progressEvent = {\n sessionId,\n timestamp: jsonEvent.timestamp ? new Date(jsonEvent.timestamp) : new Date(),\n backend: 'shell',\n count: ++this.eventCounter,\n type: jsonEvent.type as ProgressEventType,\n content: jsonEvent.content,\n toolId: streamToolId,\n metadata: jsonEvent.metadata,\n };\n isJsonParsed = true;\n } else {\n // Unknown JSON format, treat as text below\n if (this.config?.debug) {\n engineLogger.debug(`Unknown JSON format, treating as text: ${trimmedLine}`);\n }\n }\n\n // Emit the progress event if JSON was successfully parsed\n if (isJsonParsed) {\n this.emitProgressEvent(progressEvent!).catch((error) => {\n if (this.config?.debug) {\n engineLogger.warn(\n `Failed to emit progress event: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n });\n }\n } catch (error) {\n // Not JSON - this is expected for text-based subagents like Codex\n // Treat as TEXT streaming and emit as thinking event\n isJsonParsed = false;\n }\n\n // If not JSON, handle as TEXT streaming (for Codex and other text-based outputs)\n if (!isJsonParsed && trimmedLine.length > 0) {\n this.emitProgressEvent({\n sessionId,\n timestamp: new Date(),\n backend: 'shell',\n count: ++this.eventCounter,\n type: ProgressEventType.THINKING,\n content: rawLine,\n toolId: streamToolId,\n metadata: {\n format: 'text',\n raw: true,\n },\n }).catch((error) => {\n if (this.config?.debug) {\n engineLogger.warn(\n `Failed to emit text streaming event: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n });\n }\n }\n }\n\n /**\n * Check if JSON event is Claude CLI format\n */\n private isClaudeCliEvent(event: any): boolean {\n return (\n event &&\n typeof event === 'object' &&\n event.type &&\n ['system', 'assistant', 'result'].includes(event.type)\n );\n }\n\n /**\n * Check if JSON event is generic StreamingEvent format\n */\n private isGenericStreamingEvent(event: any): boolean {\n return event && typeof event === 'object' && event.type && event.content !== undefined;\n }\n\n /**\n * Convert Claude CLI event to ProgressEvent format\n */\n private convertClaudeEventToProgress(\n event: any,\n sessionId: string,\n originalLine?: string,\n toolId?: string,\n ): ProgressEvent {\n let type: ProgressEventType;\n let content: string;\n const metadata: Record<string, any> = {};\n const eventToolId = toolId || `claude_${Date.now()}`;\n\n // If outputRawJson is enabled, pass the original JSON line for jq-style formatting\n // This allows the progress display to format it with colors and indentation\n if (this.config?.outputRawJson && originalLine) {\n // Determine event type based on Claude CLI format\n switch (event.type) {\n case 'system':\n type = ProgressEventType.TOOL_START;\n break;\n case 'assistant':\n type = ProgressEventType.THINKING;\n break;\n case 'result':\n type = event.is_error || event.subtype === 'error' ? ProgressEventType.ERROR : ProgressEventType.TOOL_RESULT;\n break;\n default:\n type = ProgressEventType.THINKING;\n }\n\n // Pass the raw JSON for jq-style formatting in the display layer\n content = originalLine;\n metadata.rawJsonOutput = true;\n metadata.originalType = event.type;\n metadata.parsedEvent = event; // Keep parsed version for metadata access\n\n return {\n sessionId,\n timestamp: new Date(),\n backend: 'shell',\n count: ++this.eventCounter,\n type,\n content,\n toolId: eventToolId,\n metadata,\n };\n }\n\n // Original simplified format (when outputRawJson is false/undefined)\n switch (event.type) {\n case 'system':\n // System/init event\n type = ProgressEventType.TOOL_START;\n content = `Initializing Claude session`;\n metadata.subtype = event.subtype;\n metadata.sessionId = event.session_id;\n metadata.model = event.model;\n metadata.tools = event.tools;\n metadata.cwd = event.cwd;\n break;\n\n case 'assistant':\n // Assistant message event\n type = ProgressEventType.THINKING;\n // Check if this is pretty-formatted JSON from claude.py\n if (!event.message && (event.content !== undefined || event.tool_use !== undefined)) {\n // Pretty-formatted: { \"type\": \"assistant\", \"datetime\": \"...\", \"content\": \"...\", \"counter\": \"...\" }\n // or with tool_use: { \"type\": \"assistant\", \"datetime\": \"...\", \"tool_use\": {...}, \"counter\": \"...\" }\n if (event.content && typeof event.content === 'string') {\n content = event.content;\n } else if (event.tool_use) {\n // For tool_use, show the tool name and input\n content = `Tool: ${event.tool_use.name}`;\n metadata.tool_use = event.tool_use; // Preserve tool_use data in metadata\n } else {\n content = ''; // Empty content (content was explicitly set to undefined/empty)\n }\n } else if (event.message?.content && Array.isArray(event.message.content)) {\n // Original format: Extract content from message.content array\n const textContent = event.message.content.find((c: any) => c.type === 'text');\n content = textContent?.text || 'Processing...';\n } else {\n content = 'Processing...';\n }\n metadata.messageId = event.message?.id;\n metadata.model = event.message?.model;\n metadata.usage = event.message?.usage;\n metadata.sessionId = event.session_id;\n metadata.datetime = event.datetime; // Preserve datetime from pretty format\n metadata.counter = event.counter; // Preserve counter from pretty format\n break;\n\n case 'result':\n // Result event\n if (event.is_error || event.subtype === 'error') {\n type = ProgressEventType.ERROR;\n content = event.result || event.error || 'Execution failed';\n } else {\n type = ProgressEventType.TOOL_RESULT;\n content = event.result || 'Execution completed';\n }\n metadata.subtype = event.subtype;\n metadata.duration = event.duration_ms;\n metadata.cost = event.total_cost_usd;\n metadata.usage = event.usage;\n metadata.sessionId = event.session_id;\n break;\n\n default:\n // Fallback to thinking\n type = ProgressEventType.THINKING;\n content = JSON.stringify(event);\n metadata.unknownType = event.type;\n }\n\n return {\n sessionId,\n timestamp: new Date(),\n backend: 'shell',\n count: ++this.eventCounter,\n type,\n content,\n toolId: eventToolId,\n metadata,\n };\n }\n\n\n /**\n * Emit progress event to all callbacks\n */\n private async emitProgressEvent(event: ProgressEvent): Promise<void> {\n // Write to log file first\n if (this.logFilePath) {\n const logMessage = `[${event.type}] ${event.content}${event.metadata ? ' | metadata: ' + JSON.stringify(event.metadata) : ''}`;\n await this.writeToLogFile(logMessage);\n }\n\n // Then emit to callbacks for screen display\n for (const callback of this.progressCallbacks) {\n try {\n await callback(event);\n } catch (error) {\n // Don't break on callback errors\n if (this.config?.debug) {\n engineLogger.warn(\n `Progress callback error: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n }\n }\n}\n","/**\n * juno-code - TypeScript implementation of juno-code CLI tool\n *\n * Main entry point for the library exports\n */\n\n// Core exports\nexport * from './core/config';\nexport * from './templates/default-hooks';\nexport * from './core/engine';\nexport * from './core/session';\n// Utility exports (excluding validateConfig to avoid conflicts)\nexport * from './utils/environment';\nexport {\n executeHook,\n executeHooks,\n validateHooksConfig,\n type HooksConfig,\n type HookExecutionContext,\n type HookExecutionOptions,\n type HookExecutionResult,\n type CommandExecutionResult,\n} from './utils/hooks';\nexport {\n SubagentSchema,\n LogLevelSchema,\n SessionStatusSchema,\n IterationsSchema,\n ModelSchema,\n ConfigValidationSchema,\n validateSubagent,\n validateModel,\n validateIterations,\n validateLogLevel,\n validateEnvironmentVars,\n} from './utils/validation';\n\n// Type exports (consolidated to avoid conflicts)\nexport * from './types';\n\n// Version information\nexport { version } from './version';\n","/**\n * Core configuration module for juno-code\n *\n * Provides comprehensive configuration management with multi-source loading,\n * validation, and environment variable support.\n *\n * @module core/config\n */\n\nimport { z } from 'zod';\nimport * as path from 'node:path';\nimport * as nodeFs from 'node:fs';\nimport { promises as fsPromises } from 'node:fs';\nimport * as yaml from 'js-yaml';\nimport fs from 'fs-extra';\nimport type { JunoTaskConfig } from '../types/index';\nimport { getDefaultHooks } from '../templates/default-hooks.js';\n\n/**\n * Environment variable mapping for configuration options\n * All config options can be set via JUNO_CODE_* environment variables\n * Uses JUNO_CODE_* environment variables\n */\nexport const ENV_VAR_MAPPING = {\n // Core settings\n JUNO_CODE_DEFAULT_SUBAGENT: 'defaultSubagent',\n JUNO_CODE_DEFAULT_BACKEND: 'defaultBackend',\n JUNO_CODE_DEFAULT_MAX_ITERATIONS: 'defaultMaxIterations',\n JUNO_CODE_DEFAULT_MODEL: 'defaultModel',\n\n // Logging settings\n JUNO_CODE_LOG_LEVEL: 'logLevel',\n JUNO_CODE_LOG_FILE: 'logFile',\n JUNO_CODE_VERBOSE: 'verbose',\n JUNO_CODE_QUIET: 'quiet',\n\n // MCP settings\n JUNO_CODE_MCP_TIMEOUT: 'mcpTimeout',\n JUNO_CODE_MCP_RETRIES: 'mcpRetries',\n JUNO_CODE_MCP_SERVER_PATH: 'mcpServerPath',\n JUNO_CODE_MCP_SERVER_NAME: 'mcpServerName',\n\n // Hook settings\n JUNO_CODE_HOOK_COMMAND_TIMEOUT: 'hookCommandTimeout',\n\n // Quota/hourly limit settings\n JUNO_CODE_ON_HOURLY_LIMIT: 'onHourlyLimit',\n\n // TUI settings\n JUNO_CODE_INTERACTIVE: 'interactive',\n JUNO_CODE_HEADLESS_MODE: 'headlessMode',\n\n // Paths\n JUNO_CODE_WORKING_DIRECTORY: 'workingDirectory',\n JUNO_CODE_SESSION_DIRECTORY: 'sessionDirectory',\n} as const;\n\n/**\n * Zod schema for validating subagent types\n */\nconst SubagentTypeSchema = z.enum(['claude', 'cursor', 'codex', 'gemini', 'pi']);\n\n/**\n * Zod schema for validating backend types\n */\nconst BackendTypeSchema = z.enum(['shell']);\n\n/**\n * Zod schema for validating log levels\n */\nconst LogLevelSchema = z.enum(['error', 'warn', 'info', 'debug', 'trace']);\n\n/**\n * Zod schema for validating on-hourly-limit behavior\n */\nconst OnHourlyLimitSchema = z.enum(['wait', 'raise']);\n\n/**\n * Zod schema for validating hook types\n */\nconst HookTypeSchema = z.enum([\n 'START_RUN',\n 'START_ITERATION',\n 'END_ITERATION',\n 'END_RUN',\n 'ON_STALE',\n]);\n\n/**\n * Zod schema for validating individual hook configuration\n */\nconst HookSchema = z.object({\n commands: z.array(z.string()).describe('List of bash commands to execute for this hook'),\n});\n\n/**\n * Zod schema for validating hooks configuration\n * Maps hook types to their respective configurations\n */\nconst HooksSchema = z.record(HookTypeSchema, HookSchema).optional();\n\n/**\n * Zod schema for validating JunoTaskConfig\n * Provides runtime validation with detailed error messages\n */\nexport const JunoTaskConfigSchema = z\n .object({\n // Core settings\n defaultSubagent: SubagentTypeSchema.describe('Default subagent to use for task execution'),\n\n defaultBackend: BackendTypeSchema.describe('Default backend to use for task execution'),\n\n defaultMaxIterations: z\n .number()\n .int()\n .min(1)\n .max(1000)\n .describe('Default maximum number of iterations for task execution'),\n\n defaultModel: z.string().optional().describe('Default model to use for the subagent'),\n\n // Project metadata\n mainTask: z.string().optional().describe('Main task objective for the project'),\n\n // Logging settings\n logLevel: LogLevelSchema.describe('Logging level for the application'),\n\n logFile: z.string().optional().describe('Path to log file (optional)'),\n\n verbose: z.boolean().describe('Enable verbose output'),\n\n quiet: z.boolean().describe('Enable quiet mode (minimal output)'),\n\n // MCP settings\n mcpTimeout: z\n .number()\n .int()\n .min(1000)\n // Allow very large timeouts to satisfy real-world workflows and user tests\n // User feedback requires accepting values like 6,000,000 ms (100 minutes)\n .max(86400000) // up to 24 hours\n .describe('MCP server timeout in milliseconds'),\n\n mcpRetries: z.number().int().min(0).max(10).describe('Number of retries for MCP operations'),\n\n mcpServerPath: z\n .string()\n .optional()\n .describe('Path to MCP server executable (auto-discovered if not specified)'),\n\n mcpServerName: z\n .string()\n .optional()\n .describe('Named MCP server to connect to (e.g., \"roundtable-ai\")'),\n\n // Hook settings\n hookCommandTimeout: z\n .number()\n .int()\n .min(1000)\n .max(3600000) // up to 1 hour\n .optional()\n .describe(\n 'Timeout for individual hook commands in milliseconds (default: 300000 = 5 minutes)',\n ),\n\n // Quota/hourly limit settings\n onHourlyLimit: OnHourlyLimitSchema.describe(\n 'Behavior when Claude hourly quota limit is reached: \"wait\" to sleep until reset, \"raise\" to exit immediately',\n ),\n\n // TUI settings\n interactive: z.boolean().describe('Enable interactive mode'),\n\n headlessMode: z.boolean().describe('Enable headless mode (no TUI)'),\n\n // Paths\n workingDirectory: z.string().describe('Working directory for task execution'),\n\n sessionDirectory: z.string().describe('Directory for storing session data'),\n\n // Hooks configuration\n hooks: HooksSchema.describe(\n 'Hook system configuration for executing commands at specific lifecycle events',\n ),\n\n // Skip hooks execution\n skipHooks: z.boolean().optional().describe('Skip execution of all lifecycle hooks when true'),\n })\n .strict();\n\n/**\n * Default configuration values\n * These are used as fallbacks when no other configuration is provided\n */\nexport const DEFAULT_CONFIG: JunoTaskConfig = {\n // Core settings\n defaultSubagent: 'claude',\n defaultBackend: 'shell',\n defaultMaxIterations: 1,\n\n // Logging settings\n logLevel: 'info',\n verbose: false,\n quiet: false,\n\n // MCP settings (also used by shell backend)\n mcpTimeout: 43200000, // 43200 seconds (12 hours) - default for long-running shell backend operations\n mcpRetries: 3,\n mcpServerName: 'roundtable-ai', // Default to roundtable-ai server\n\n // Quota/hourly limit settings\n onHourlyLimit: 'raise', // Default to exit immediately when hourly limit is reached\n\n // TUI settings\n interactive: true,\n headlessMode: false,\n\n // Paths\n workingDirectory: process.cwd(),\n sessionDirectory: path.join(process.cwd(), '.juno_task'),\n\n // Hooks configuration - populated with default hooks template\n hooks: getDefaultHooks(),\n};\n\n/**\n * Global configuration file names to search for\n * Searched in order of preference (after project-specific config)\n */\nconst GLOBAL_CONFIG_FILE_NAMES = [\n 'juno-code.config.json',\n 'juno-code.config.js',\n '.juno-coderc.json',\n '.juno-coderc.js',\n 'package.json', // Will look for 'junoCode' field\n] as const;\n\n/**\n * Project-specific configuration file (highest precedence for project settings)\n */\nconst PROJECT_CONFIG_FILE = '.juno_task/config.json';\n\n/**\n * Supported configuration file formats\n */\ntype ConfigFileFormat = 'json' | 'yaml' | 'toml' | 'js';\n\n/**\n * Configuration source types for precedence handling\n * Precedence order: cli > env > projectFile > file > defaults\n */\ntype ConfigSource = 'defaults' | 'file' | 'projectFile' | 'env' | 'cli';\n\n/**\n * Utility function to resolve paths (relative to absolute)\n *\n * @param inputPath - The path to resolve\n * @param basePath - Base path for relative resolution (defaults to cwd)\n * @returns Absolute path\n */\nfunction resolvePath(inputPath: string, basePath: string = process.cwd()): string {\n if (path.isAbsolute(inputPath)) {\n return inputPath;\n }\n return path.resolve(basePath, inputPath);\n}\n\n/**\n * Utility function to parse environment variables\n * Handles type conversion for boolean and number values\n *\n * @param value - Environment variable value\n * @returns Parsed value with appropriate type\n */\nfunction parseEnvValue(value: string): string | number | boolean {\n // Handle empty string\n if (value === '') return value;\n\n // Handle boolean values\n if (value.toLowerCase() === 'true') return true;\n if (value.toLowerCase() === 'false') return false;\n\n // Handle numeric values\n const numValue = Number(value);\n if (!isNaN(numValue) && isFinite(numValue)) {\n return numValue;\n }\n\n // Return as string\n return value;\n}\n\n/**\n * Load configuration from environment variables\n * Maps JUNO_CODE_* environment variables to config properties\n *\n * @returns Partial configuration from environment variables\n */\nfunction loadConfigFromEnv(): Partial<JunoTaskConfig> {\n const config: Partial<JunoTaskConfig> = {};\n\n for (const [envVar, configKey] of Object.entries(ENV_VAR_MAPPING)) {\n const value = process.env[envVar];\n if (value !== undefined) {\n (config as any)[configKey] = parseEnvValue(value);\n }\n }\n\n return config;\n}\n\n/**\n * Load configuration from a JSON file\n *\n * @param filePath - Path to the JSON configuration file\n * @returns Parsed configuration object\n */\nasync function loadJsonConfig(filePath: string): Promise<Partial<JunoTaskConfig>> {\n try {\n const content = await fsPromises.readFile(filePath, 'utf-8');\n return JSON.parse(content);\n } catch (error) {\n throw new Error(`Failed to load JSON config from ${filePath}: ${error}`);\n }\n}\n\n/**\n * Load configuration from a YAML file\n *\n * @param filePath - Path to the YAML configuration file\n * @returns Parsed configuration object\n */\nasync function loadYamlConfig(filePath: string): Promise<Partial<JunoTaskConfig>> {\n try {\n const content = await fsPromises.readFile(filePath, 'utf-8');\n const parsed = yaml.load(content);\n return parsed as Partial<JunoTaskConfig>;\n } catch (error) {\n throw new Error(`Failed to load YAML config from ${filePath}: ${error}`);\n }\n}\n\n/**\n * Load configuration from package.json\n * Looks for configuration in the 'junoCode' field\n *\n * @param filePath - Path to package.json\n * @returns Parsed configuration object\n */\nasync function loadPackageJsonConfig(filePath: string): Promise<Partial<JunoTaskConfig>> {\n try {\n const content = await fsPromises.readFile(filePath, 'utf-8');\n const packageJson = JSON.parse(content);\n return packageJson.junoCode || {};\n } catch (error) {\n throw new Error(`Failed to load package.json config from ${filePath}: ${error}`);\n }\n}\n\n/**\n * Determine configuration file format based on file extension\n *\n * @param filePath - Path to the configuration file\n * @returns Configuration file format\n */\nfunction getConfigFileFormat(filePath: string): ConfigFileFormat {\n const ext = path.extname(filePath).toLowerCase();\n\n switch (ext) {\n case '.json':\n return 'json';\n case '.yaml':\n case '.yml':\n return 'yaml';\n case '.toml':\n return 'toml';\n case '.js':\n case '.mjs':\n return 'js';\n default:\n // For files like .juno-coderc (no extension), assume JSON\n return 'json';\n }\n}\n\n/**\n * Load configuration from a file\n * Automatically detects file format and uses appropriate parser\n *\n * @param filePath - Path to the configuration file\n * @returns Parsed configuration object\n */\nasync function loadConfigFromFile(filePath: string): Promise<Partial<JunoTaskConfig>> {\n const format = getConfigFileFormat(filePath);\n const resolvedPath = resolvePath(filePath);\n\n // Check if file exists\n try {\n await fsPromises.access(resolvedPath, nodeFs.constants.R_OK);\n } catch {\n throw new Error(`Configuration file not readable: ${resolvedPath}`);\n }\n\n switch (format) {\n case 'json':\n if (path.basename(filePath) === 'package.json') {\n return loadPackageJsonConfig(resolvedPath);\n }\n return loadJsonConfig(resolvedPath);\n\n case 'yaml':\n return loadYamlConfig(resolvedPath);\n\n case 'toml':\n // TOML support would require additional dependency\n throw new Error('TOML configuration files are not yet supported');\n\n case 'js':\n // JavaScript config files would require dynamic import\n throw new Error('JavaScript configuration files are not yet supported');\n\n default:\n throw new Error(`Unsupported configuration file format: ${format}`);\n }\n}\n\n/**\n * Find project-specific configuration file\n * Looks for .juno_task/config.json in the specified directory\n *\n * @param searchDir - Directory to search for project configuration file\n * @returns Path to found project config file, or null if none found\n */\nasync function findProjectConfigFile(searchDir: string = process.cwd()): Promise<string | null> {\n const filePath = path.join(searchDir, PROJECT_CONFIG_FILE);\n\n try {\n await fsPromises.access(filePath, nodeFs.constants.R_OK);\n return filePath;\n } catch {\n // File doesn't exist or isn't readable\n return null;\n }\n}\n\n/**\n * Find global configuration file in the specified directory\n * Searches for global config files in order of preference\n *\n * @param searchDir - Directory to search for global configuration files\n * @returns Path to found global config file, or null if none found\n */\nasync function findGlobalConfigFile(searchDir: string = process.cwd()): Promise<string | null> {\n for (const fileName of GLOBAL_CONFIG_FILE_NAMES) {\n const filePath = path.join(searchDir, fileName);\n\n try {\n await fsPromises.access(filePath, nodeFs.constants.R_OK);\n return filePath;\n } catch {\n // File doesn't exist or isn't readable, continue searching\n continue;\n }\n }\n\n return null;\n}\n\n/**\n * ConfigLoader class for multi-source configuration loading\n *\n * Implements configuration precedence: CLI args > Environment Variables > Project Config > Global Config Files > Profile > Defaults\n */\nexport class ConfigLoader {\n private configSources: Map<ConfigSource, Partial<JunoTaskConfig>> = new Map();\n\n /**\n * Create a new ConfigLoader instance\n *\n * @param baseDir - Base directory for relative path resolution\n */\n constructor(private baseDir: string = process.cwd()) {\n // Initialize with defaults\n this.configSources.set('defaults', DEFAULT_CONFIG);\n }\n\n /**\n * Load configuration from environment variables\n *\n * @returns This ConfigLoader instance for method chaining\n */\n fromEnvironment(): this {\n const envConfig = loadConfigFromEnv();\n this.configSources.set('env', envConfig);\n return this;\n }\n\n /**\n * Load configuration from a specific file\n *\n * @param filePath - Path to configuration file\n * @returns This ConfigLoader instance for method chaining\n */\n async fromFile(filePath: string): Promise<this> {\n try {\n const fileConfig = await loadConfigFromFile(filePath);\n this.configSources.set('file', fileConfig);\n } catch (error) {\n throw new Error(`Failed to load configuration file: ${error}`);\n }\n return this;\n }\n\n /**\n * Load configuration from project-specific config file\n * Loads from .juno_task/config.json with highest precedence for project settings\n *\n * @returns This ConfigLoader instance for method chaining\n */\n async fromProjectConfig(): Promise<this> {\n try {\n const projectConfigFile = await findProjectConfigFile(this.baseDir);\n if (projectConfigFile) {\n const fileConfig = await loadConfigFromFile(projectConfigFile);\n this.configSources.set('projectFile', fileConfig);\n }\n } catch (error) {\n throw new Error(`Failed to load project configuration file: ${error}`);\n }\n return this;\n }\n\n /**\n * Automatically discover and load configuration files\n * Searches for both project-specific and global config files in the base directory\n * Project-specific config (.juno_task/config.json) takes precedence over global configs\n *\n * @returns This ConfigLoader instance for method chaining\n */\n async autoDiscoverFile(): Promise<this> {\n // First, try to load project-specific config\n const projectConfigFile = await findProjectConfigFile(this.baseDir);\n if (projectConfigFile) {\n const fileConfig = await loadConfigFromFile(projectConfigFile);\n this.configSources.set('projectFile', fileConfig);\n }\n\n // Then, try to load global config file\n const globalConfigFile = await findGlobalConfigFile(this.baseDir);\n if (globalConfigFile) {\n const fileConfig = await loadConfigFromFile(globalConfigFile);\n this.configSources.set('file', fileConfig);\n }\n\n return this;\n }\n\n /**\n * Load configuration from CLI arguments\n *\n * @param cliConfig - Configuration object from CLI argument parsing\n * @returns This ConfigLoader instance for method chaining\n */\n fromCli(cliConfig: Partial<JunoTaskConfig>): this {\n this.configSources.set('cli', cliConfig);\n return this;\n }\n\n /**\n * Merge all configuration sources according to precedence\n * CLI args > Environment Variables > Project Config > Global Config Files > Defaults\n *\n * @returns Merged configuration object\n */\n merge(): JunoTaskConfig {\n // Start with defaults to ensure all required properties are present\n const mergedConfig = { ...DEFAULT_CONFIG };\n\n // Apply sources in order of precedence (lowest to highest)\n const sourcePrecedence: ConfigSource[] = ['file', 'projectFile', 'env', 'cli'];\n\n for (const source of sourcePrecedence) {\n const sourceConfig = this.configSources.get(source);\n if (sourceConfig) {\n Object.assign(mergedConfig, sourceConfig);\n }\n }\n\n // Resolve paths to absolute paths\n if (mergedConfig.workingDirectory) {\n mergedConfig.workingDirectory = resolvePath(mergedConfig.workingDirectory, this.baseDir);\n }\n\n if (mergedConfig.sessionDirectory) {\n mergedConfig.sessionDirectory = resolvePath(mergedConfig.sessionDirectory, this.baseDir);\n }\n\n if (mergedConfig.logFile) {\n mergedConfig.logFile = resolvePath(mergedConfig.logFile, this.baseDir);\n }\n\n if (mergedConfig.mcpServerPath) {\n mergedConfig.mcpServerPath = resolvePath(mergedConfig.mcpServerPath, this.baseDir);\n }\n\n return mergedConfig;\n }\n\n /**\n * Load and merge configuration from all sources\n * Convenience method that performs auto-discovery and returns validated config\n *\n * @param cliConfig - Optional CLI configuration\n * @returns Promise resolving to validated configuration\n */\n async loadAll(cliConfig?: Partial<JunoTaskConfig>): Promise<JunoTaskConfig> {\n // Load from environment\n this.fromEnvironment();\n\n // Auto-discover configuration file\n await this.autoDiscoverFile();\n\n // Add CLI config if provided\n if (cliConfig) {\n this.fromCli(cliConfig);\n }\n\n // Merge and return\n return this.merge();\n }\n}\n\n/**\n * Validate configuration object against schema\n *\n * @param config - Configuration object to validate\n * @returns Validated configuration object\n * @throws Error if validation fails\n */\nexport function validateConfig(config: unknown): JunoTaskConfig {\n try {\n const parsed = JunoTaskConfigSchema.parse(config);\n return parsed as JunoTaskConfig;\n } catch (error) {\n if (error instanceof z.ZodError) {\n const errorMessages = error.errors\n .map((err) => `${err.path.join('.')}: ${err.message}`)\n .join('; ');\n throw new Error(`Configuration validation failed: ${errorMessages}`);\n }\n throw error;\n }\n}\n\n/**\n * Ensure hooks configuration exists in project config file\n *\n * This function handles auto-migration for the hooks configuration:\n * - If .juno_task/config.json doesn't exist: create it with default config including empty hooks section\n * - If it exists but has no \"hooks\" field: add hooks: {} to the file\n * - Preserve all existing configuration\n *\n * @param baseDir - Base directory where .juno_task directory should be located\n * @returns Promise that resolves when migration is complete\n */\nasync function ensureHooksConfig(baseDir: string): Promise<void> {\n try {\n const configDir = path.join(baseDir, '.juno_task');\n const configPath = path.join(configDir, 'config.json');\n\n // Ensure the .juno_task directory exists\n await fs.ensureDir(configDir);\n\n // Check if config file exists\n const configExists = await fs.pathExists(configPath);\n\n // Use default hooks template with file size monitoring commands\n const allHookTypes = getDefaultHooks();\n\n if (!configExists) {\n // Create new config file with default config including all hook types\n const defaultConfig = {\n ...DEFAULT_CONFIG,\n hooks: allHookTypes,\n };\n await fs.writeJson(configPath, defaultConfig, { spaces: 2 });\n } else {\n // Read existing config and ensure hooks field exists with all hook types\n const existingConfig = await fs.readJson(configPath);\n let needsUpdate = false;\n\n // If hooks field doesn't exist, add it with all hook types\n if (!existingConfig.hooks) {\n existingConfig.hooks = allHookTypes;\n needsUpdate = true;\n }\n\n // Migration: Add defaultModel if missing (for configs created before this feature)\n if (!existingConfig.defaultModel) {\n // Determine default model based on defaultSubagent\n const subagent = existingConfig.defaultSubagent || 'claude';\n const modelDefaults: Record<string, string> = {\n claude: ':sonnet',\n codex: ':codex',\n gemini: ':pro',\n cursor: 'auto',\n };\n existingConfig.defaultModel = modelDefaults[subagent] || ':sonnet';\n needsUpdate = true;\n }\n\n // Migration: Update defaultMaxIterations from old default (50) to new default (1)\n // Old configs created before v1.44.109 had defaultMaxIterations: 50\n if (existingConfig.defaultMaxIterations === 50) {\n existingConfig.defaultMaxIterations = DEFAULT_CONFIG.defaultMaxIterations;\n needsUpdate = true;\n }\n\n if (needsUpdate) {\n await fs.writeJson(configPath, existingConfig, { spaces: 2 });\n }\n }\n } catch (error) {\n // Log warning but don't block app startup\n console.warn(`Warning: Failed to ensure hooks configuration: ${error}`);\n }\n}\n\n/**\n * Load and validate configuration from all sources\n *\n * This is the main entry point for configuration loading.\n * It performs auto-discovery, merging, and validation.\n *\n * @param options - Configuration loading options\n * @param options.baseDir - Base directory for relative path resolution\n * @param options.configFile - Specific configuration file to load\n * @param options.cliConfig - CLI configuration override\n * @returns Promise resolving to validated configuration\n *\n * @example\n * ```typescript\n * // Load with auto-discovery\n * const config = await loadConfig();\n *\n * // Load with specific file\n * const config = await loadConfig({\n * configFile: './my-config.json'\n * });\n *\n * // Load with CLI overrides\n * const config = await loadConfig({\n * cliConfig: { verbose: true, logLevel: 'debug' }\n * });\n * ```\n */\nexport async function loadConfig(\n options: {\n baseDir?: string;\n configFile?: string;\n cliConfig?: Partial<JunoTaskConfig>;\n } = {},\n): Promise<JunoTaskConfig> {\n const { baseDir = process.cwd(), configFile, cliConfig } = options;\n\n // Ensure hooks configuration exists in project config (auto-migration)\n await ensureHooksConfig(baseDir);\n\n const loader = new ConfigLoader(baseDir);\n\n // Load from environment\n loader.fromEnvironment();\n\n // Load from specific file or auto-discover\n if (configFile) {\n await loader.fromFile(configFile);\n } else {\n await loader.autoDiscoverFile();\n }\n\n // Add CLI config if provided\n if (cliConfig) {\n loader.fromCli(cliConfig);\n }\n\n // Merge and validate\n const mergedConfig = loader.merge();\n return validateConfig(mergedConfig);\n}\n\n/**\n * Type export for configuration loading options\n */\nexport type ConfigLoadOptions = Parameters<typeof loadConfig>[0];\n\n/**\n * Type export for environment variable mapping\n */\nexport type EnvVarMapping = typeof ENV_VAR_MAPPING;\n","/**\n * Default hooks template configuration\n *\n * This module provides default hook commands that are shipped with juno-code.\n * These hooks are automatically configured during project initialization (init command).\n *\n * Hook Types:\n * - START_RUN: Executes at the beginning of a run (before all iterations)\n * - START_ITERATION: Executes at the start of each iteration\n * - END_ITERATION: Executes at the end of each iteration\n * - END_RUN: Executes at the end of a run (after all iterations)\n *\n * To modify default hooks:\n * 1. Update the commands in this file\n * 2. Rebuild the project (npm run build)\n * 3. New installations will use the updated defaults\n *\n * @module templates/default-hooks\n */\n\nimport type { Hooks } from '../types/index';\n\n/**\n * Default hooks configuration template\n *\n * All hook types are included so users can see available hooks without reading documentation.\n * Empty command arrays indicate hooks that are available but not configured by default.\n *\n * These hooks provide useful default behaviors:\n * - File size monitoring for CLAUDE.md, AGENTS.md, .juno_task/plan.md, .juno_task/tasks.md\n * - Alerts via juno-kanban when documentation/task files become too large\n *\n * Users can customize these hooks by editing .juno_task/config.json after initialization\n */\nexport const DEFAULT_HOOKS: Hooks = {\n // Executes once at the beginning of a run (before all iterations)\n // Use for: setup, environment checks, notifications, pre-run cleanup\n START_RUN: {\n commands: [],\n },\n\n // Executes at the start of each iteration\n // Use for: file monitoring, state checks, per-iteration setup\n START_ITERATION: {\n commands: [\n // Monitor CLAUDE.md file size\n 'file=\"CLAUDE.md\"; lines=$(wc -l < \"$file\" 2>/dev/null || echo 0); chars=$(wc -m < \"$file\" 2>/dev/null || echo 0); if [ \"$lines\" -gt 450 ] || [ \"$chars\" -gt 40000 ]; then juno-kanban \"[Critical] file $file is too large, keep it lean and useful for every run of the agent.\"; fi',\n\n // Monitor AGENTS.md file size\n 'file=\"AGENTS.md\"; lines=$(wc -l < \"$file\" 2>/dev/null || echo 0); chars=$(wc -m < \"$file\" 2>/dev/null || echo 0); if [ \"$lines\" -gt 450 ] || [ \"$chars\" -gt 40000 ]; then juno-kanban \"[Critical] file $file is too large, keep it lean and useful for every run of the agent.\"; fi',\n\n // Monitor .juno_task/plan.md file size\n 'file=\".juno_task/plan.md\"; lines=$(wc -l < \"$file\" 2>/dev/null || echo 0); chars=$(wc -m < \"$file\" 2>/dev/null || echo 0); if [ \"$lines\" -gt 450 ] || [ \"$chars\" -gt 40000 ]; then juno-kanban \"[Critical] file $file is too large, keep it lean and useful for every run of the agent.\"; fi',\n\n // Monitor .juno_task/tasks.md file size\n 'file=\".juno_task/tasks.md\"; lines=$(wc -l < \"$file\" 2>/dev/null || echo 0); chars=$(wc -m < \"$file\" 2>/dev/null || echo 0); if [ \"$lines\" -gt 450 ] || [ \"$chars\" -gt 40000 ]; then juno-kanban \"[Critical] file $file is too large, keep it lean and useful for every run of the agent.\"; fi',\n './.juno_task/scripts/cleanup_feedback.sh',\n ],\n },\n\n // Executes at the end of each iteration\n // Use for: validation, logging, per-iteration cleanup, progress tracking\n END_ITERATION: {\n commands: [],\n },\n\n // Executes once at the end of a run (after all iterations complete)\n // Use for: final cleanup, notifications, reports, post-run actions\n END_RUN: {\n commands: [],\n },\n\n // Executes when stale iteration is detected in run_until_completion.sh\n // Use for: alerts, notifications, logging when agent is not making progress\n ON_STALE: {\n commands: [\n './.juno_task/scripts/kanban.sh create \"Warning: You haven\\'t done anything on the kanban in the past run. You need to process a task, or if you find it unsuitable or unresolvable, you need to archive the task\" --status todo',\n ],\n },\n};\n\n/**\n * Get default hooks configuration\n *\n * Returns a copy of the default hooks to prevent mutation of the template.\n * This function can be used during initialization to populate the config.json file.\n *\n * @returns A copy of the default hooks configuration\n */\nexport function getDefaultHooks(): Hooks {\n return JSON.parse(JSON.stringify(DEFAULT_HOOKS));\n}\n\n/**\n * Get default hooks as formatted JSON string for config.json\n *\n * @param indent - Number of spaces for indentation (default: 2)\n * @returns Formatted JSON string of default hooks\n */\nexport function getDefaultHooksJson(indent: number = 2): string {\n return JSON.stringify(DEFAULT_HOOKS, null, indent);\n}\n","/**\n * Core execution engine module for juno-task-ts\n *\n * This module provides the main execution orchestration engine that manages\n * the entire workflow for AI task execution, including session management,\n * backend integration, progress tracking, error handling, and cancellation.\n *\n * The implementation closely matches the Python budi-cli execution patterns,\n * including rate limit handling, iteration logic, and progress tracking.\n *\n * @module core/engine\n * @since 1.0.0\n */\n\nimport { EventEmitter } from 'node:events';\nimport type { JunoTaskConfig, SubagentType, ProgressEventType, BackendType } from '../types/index';\nimport type {\n ProgressEvent,\n ProgressCallback,\n ToolCallRequest,\n ToolCallResult,\n SessionContext,\n} from '../types/execution.js';\nimport { ExecutionError, RateLimitError } from './errors';\nimport { executeHook } from '../utils/hooks.js';\nimport { engineLogger } from '../cli/utils/advanced-logger.js';\nimport type { Backend } from './backend-manager.js';\nimport { type QuotaLimitInfo, formatDuration } from './backends/shell-backend.js';\n\n// =============================================================================\n// Type Definitions\n// =============================================================================\n\n/**\n * Execution request interface for starting task execution\n */\nexport interface ExecutionRequest {\n /** Unique request identifier */\n readonly requestId: string;\n\n /** Task instruction or prompt text */\n readonly instruction: string;\n\n /** Subagent to use for execution */\n readonly subagent: SubagentType;\n\n /** Backend to use for execution */\n readonly backend: BackendType;\n\n /** Working directory for execution */\n readonly workingDirectory: string;\n\n /** Maximum number of iterations (-1 for unlimited) */\n readonly maxIterations: number;\n\n /** Optional specific model to use */\n readonly model?: string;\n\n /** Optional timeout in milliseconds (overrides config) */\n readonly timeoutMs?: number;\n\n /** Session metadata */\n readonly sessionMetadata?: Record<string, unknown>;\n\n /** Custom progress callbacks */\n readonly progressCallbacks?: ProgressCallback[];\n\n /** Request priority level */\n readonly priority?: 'low' | 'normal' | 'high';\n\n /** MCP server name (for MCP backend) */\n readonly mcpServerName?: string;\n\n /** Available tools from built-in set (only works with --print mode, forwarded to shell backend) */\n readonly tools?: string[];\n\n /** Permission-based filtering of specific tool instances (forwarded to shell backend) */\n readonly allowedTools?: string[];\n\n /** Disallowed tools (forwarded to shell backend) */\n readonly disallowedTools?: string[];\n\n /** Append tools to default allowed-tools list (forwarded to shell backend) */\n readonly appendAllowedTools?: string[];\n\n /** Agents configuration (forwarded to shell backend) */\n readonly agents?: string;\n\n /** Resume a conversation by session ID (forwarded to shell backend) */\n readonly resume?: string;\n\n /** Continue the most recent conversation (forwarded to shell backend) */\n readonly continueConversation?: boolean;\n}\n\n/**\n * Execution result interface for completed executions\n */\nexport interface ExecutionResult {\n /** Request that generated this result */\n readonly request: ExecutionRequest;\n\n /** Execution status */\n readonly status: ExecutionStatus;\n\n /** Execution start time */\n readonly startTime: Date;\n\n /** Execution end time */\n readonly endTime: Date;\n\n /** Total execution duration in milliseconds */\n readonly duration: number;\n\n /** All iteration results */\n readonly iterations: readonly IterationResult[];\n\n /** Final execution statistics */\n readonly statistics: ExecutionStatistics;\n\n /** Any error that terminated execution */\n readonly error?: ExecutionError;\n\n /** Session context information */\n readonly sessionContext: SessionContext;\n\n /** All progress events captured during execution */\n readonly progressEvents: readonly ProgressEvent[];\n}\n\n/**\n * Individual iteration result\n */\nexport interface IterationResult {\n /** Iteration number (1-based) */\n readonly iterationNumber: number;\n\n /** Iteration success status */\n readonly success: boolean;\n\n /** Iteration start time */\n readonly startTime: Date;\n\n /** Iteration end time */\n readonly endTime: Date;\n\n /** Iteration duration in milliseconds */\n readonly duration: number;\n\n /** Tool call result */\n readonly toolResult: ToolCallResult;\n\n /** Iteration-specific progress events */\n readonly progressEvents: readonly ProgressEvent[];\n\n /** Any error that occurred during iteration */\n readonly error?: Error;\n}\n\n/**\n * Execution status enumeration\n */\nexport enum ExecutionStatus {\n PENDING = 'pending',\n RUNNING = 'running',\n COMPLETED = 'completed',\n FAILED = 'failed',\n CANCELLED = 'cancelled',\n TIMEOUT = 'timeout',\n RATE_LIMITED = 'rate_limited',\n}\n\n/**\n * Execution statistics for performance tracking\n */\nexport interface ExecutionStatistics {\n /** Total iterations attempted */\n totalIterations: number;\n\n /** Number of successful iterations */\n successfulIterations: number;\n\n /** Number of failed iterations */\n failedIterations: number;\n\n /** Average iteration duration in milliseconds */\n averageIterationDuration: number;\n\n /** Total tool calls made */\n totalToolCalls: number;\n\n /** Total progress events processed */\n totalProgressEvents: number;\n\n /** Rate limit encounters */\n rateLimitEncounters: number;\n\n /** Total rate limit wait time in milliseconds */\n rateLimitWaitTime: number;\n\n /** Quota limit encounters (Claude-specific) */\n quotaLimitEncounters: number;\n\n /** Total quota limit wait time in milliseconds */\n quotaLimitWaitTime: number;\n\n /** Error breakdown by type */\n errorBreakdown: Record<string, number>;\n\n /** Performance metrics */\n performanceMetrics: PerformanceMetrics;\n}\n\n/**\n * Performance metrics for detailed analysis\n */\nexport interface PerformanceMetrics {\n /** CPU usage percentage during execution */\n cpuUsage: number;\n\n /** Memory usage in bytes */\n memoryUsage: number;\n\n /** Network requests made */\n networkRequests: number;\n\n /** File system operations */\n fileSystemOperations: number;\n\n /** Throughput metrics */\n throughput: ThroughputMetrics;\n}\n\n/**\n * Throughput metrics\n */\nexport interface ThroughputMetrics {\n /** Iterations per minute */\n iterationsPerMinute: number;\n\n /** Progress events per second */\n progressEventsPerSecond: number;\n\n /** Tool calls per minute */\n toolCallsPerMinute: number;\n}\n\n/**\n * Rate limit information for handling\n */\nexport interface RateLimitInfo {\n /** Whether currently rate limited */\n readonly isRateLimited: boolean;\n\n /** Rate limit reset time */\n readonly resetTime?: Date;\n\n /** Remaining requests in current window */\n readonly remaining: number;\n\n /** Time to wait before next request in milliseconds */\n readonly waitTimeMs: number;\n\n /** Rate limit tier/category */\n readonly tier?: string;\n}\n\n/**\n * Error recovery strategy configuration\n */\nexport interface ErrorRecoveryConfig {\n /** Maximum recovery attempts per error type */\n readonly maxAttempts: Record<string, number>;\n\n /** Retry delays by error type in milliseconds */\n readonly retryDelays: Record<string, number>;\n\n /** Whether to continue on specific error types */\n readonly continueOnError: Record<string, boolean>;\n\n /** Custom recovery strategies */\n readonly customStrategies: Record<string, (error: ExecutionError) => Promise<boolean>>;\n}\n\n/**\n * Execution engine configuration\n */\nexport interface ExecutionEngineConfig {\n /** Base configuration */\n readonly config: JunoTaskConfig;\n\n /** No longer uses BackendManager; engine creates ShellBackend directly */\n\n /** Error recovery configuration */\n readonly errorRecovery: ErrorRecoveryConfig;\n\n /** Rate limit handling configuration */\n readonly rateLimitConfig: RateLimitHandlingConfig;\n\n /** Progress tracking configuration */\n readonly progressConfig: ProgressTrackingConfig;\n}\n\n/**\n * Rate limit handling configuration\n */\nexport interface RateLimitHandlingConfig {\n /** Enable automatic rate limit handling */\n readonly enabled: boolean;\n\n /** Maximum wait time for rate limits in milliseconds */\n readonly maxWaitTimeMs: number;\n\n /** Rate limit detection patterns */\n readonly detectionPatterns: readonly RegExp[];\n\n /** Custom rate limit parsers */\n readonly customParsers: readonly RateLimitParser[];\n}\n\n/**\n * Rate limit parser interface\n */\nexport interface RateLimitParser {\n /** Pattern to match rate limit messages */\n readonly pattern: RegExp;\n\n /** Parse function to extract reset time */\n readonly parse: (message: string) => Date | null;\n}\n\n/**\n * Progress tracking configuration\n */\nexport interface ProgressTrackingConfig {\n /** Enable progress tracking */\n readonly enabled: boolean;\n\n /** Buffer size for progress events */\n readonly bufferSize: number;\n\n /** Progress event filters */\n readonly filters: readonly ProgressEventFilter[];\n\n /** Custom progress processors */\n readonly processors: readonly ProgressEventProcessor[];\n}\n\n/**\n * Progress event filter\n */\nexport interface ProgressEventFilter {\n /** Filter type */\n readonly type: ProgressEventType | 'custom';\n\n /** Filter predicate */\n readonly predicate: (event: ProgressEvent) => boolean;\n}\n\n/**\n * Progress event processor\n */\nexport interface ProgressEventProcessor {\n /** Processor name */\n readonly name: string;\n\n /** Process function */\n readonly process: (event: ProgressEvent) => Promise<void>;\n}\n\n// =============================================================================\n// Default Configurations\n// =============================================================================\n\n/**\n * Default error recovery configuration\n */\nexport const DEFAULT_ERROR_RECOVERY_CONFIG: ErrorRecoveryConfig = {\n maxAttempts: {\n connection: 3,\n timeout: 2,\n rate_limit: 5,\n tool_execution: 2,\n validation: 1,\n server_not_found: 1,\n protocol: 2,\n authentication: 1,\n },\n retryDelays: {\n connection: 1000,\n timeout: 2000,\n rate_limit: 0, // Wait time determined by rate limit reset\n tool_execution: 1500,\n validation: 0, // No retry for validation errors\n server_not_found: 0, // No retry for server not found\n protocol: 1000,\n authentication: 0, // No retry for auth errors\n },\n continueOnError: {\n connection: true,\n timeout: true,\n rate_limit: true,\n tool_execution: false,\n validation: false,\n server_not_found: false,\n protocol: true,\n authentication: false,\n },\n customStrategies: {},\n};\n\n/**\n * Default rate limit handling configuration\n */\nexport const DEFAULT_RATE_LIMIT_CONFIG: RateLimitHandlingConfig = {\n enabled: true,\n maxWaitTimeMs: 3600000, // 1 hour\n detectionPatterns: [\n /resets\\s+(\\d{1,2}):?(\\d{2})?\\s*(am|pm)?/i,\n /resets\\s+(\\d{1,2})\\s*(am|pm)/i,\n /try again in (\\d+)\\s*(minutes?|hours?)/i,\n /5-hour limit reached.*resets\\s+(\\d{1,2})\\s*(am|pm)/i,\n ],\n customParsers: [],\n};\n\n/**\n * Default progress tracking configuration\n */\nexport const DEFAULT_PROGRESS_CONFIG: ProgressTrackingConfig = {\n enabled: true,\n bufferSize: 10000,\n filters: [],\n processors: [],\n};\n\n// =============================================================================\n// Main ExecutionEngine Class\n// =============================================================================\n\n/**\n * Main execution engine class for orchestrating AI task execution\n *\n * This class manages the complete execution lifecycle including:\n * - Session creation and management\n * - Iteration loop with rate limit handling\n * - Progress tracking and statistics collection\n * - Error handling with recovery strategies\n * - Cancellation and cleanup\n *\n * @example\n * ```typescript\n * const engine = createExecutionEngine(await loadConfig());\n *\n * const request: ExecutionRequest = {\n * requestId: 'req-123',\n * instruction: 'Implement a new feature',\n * subagent: 'claude',\n * workingDirectory: '/path/to/project',\n * maxIterations: 10,\n * };\n *\n * const result = await engine.execute(request);\n * ```\n */\nexport class ExecutionEngine extends EventEmitter {\n private readonly engineConfig: ExecutionEngineConfig;\n private readonly activeExecutions = new Map<string, ExecutionContext>();\n private readonly progressCallbacks: ProgressCallback[] = [];\n private readonly cleanupTasks: (() => Promise<void>)[] = [];\n private isShuttingDown = false;\n private currentBackend: Backend | null = null;\n\n /**\n * Create a new ExecutionEngine instance\n *\n * @param config - Engine configuration\n */\n constructor(config: ExecutionEngineConfig) {\n super();\n this.engineConfig = config;\n this.setupErrorHandling();\n this.setupProgressTracking();\n }\n\n // =============================================================================\n // Public API Methods\n // =============================================================================\n\n /**\n * Execute a task request with comprehensive orchestration\n *\n * @param request - Execution request parameters\n * @param abortSignal - Optional abort signal for cancellation\n * @returns Promise resolving to execution result\n */\n async execute(request: ExecutionRequest, abortSignal?: AbortSignal): Promise<ExecutionResult> {\n this.validateRequest(request);\n\n const context = this.createExecutionContext(request, abortSignal);\n this.activeExecutions.set(request.requestId, context);\n\n try {\n this.emit('execution:start', { request, context });\n\n const result = await this.executeInternal(context);\n\n this.emit('execution:complete', { request, result });\n return result;\n } catch (error) {\n const mcpError = this.wrapError(error);\n this.emit('execution:error', { request, error: mcpError });\n throw mcpError;\n } finally {\n this.activeExecutions.delete(request.requestId);\n await this.cleanupExecution(context);\n }\n }\n\n /**\n * Add a progress callback for all executions\n *\n * @param callback - Progress callback function\n * @returns Cleanup function to remove the callback\n */\n onProgress(callback: ProgressCallback): () => void {\n this.progressCallbacks.push(callback);\n return () => {\n const index = this.progressCallbacks.indexOf(callback);\n if (index !== -1) {\n this.progressCallbacks.splice(index, 1);\n }\n };\n }\n\n /**\n * Get current rate limit information\n *\n * @returns Current rate limit status\n */\n async getRateLimitInfo(): Promise<RateLimitInfo> {\n // Implementation would query backend for rate limit status\n return {\n isRateLimited: false,\n remaining: 100,\n resetTime: new Date(Date.now() + 60000), // 1 minute from now\n waitTimeMs: 0,\n };\n }\n\n /**\n * Cancel all active executions and shutdown gracefully\n *\n * @param timeoutMs - Maximum time to wait for cleanup\n */\n async shutdown(timeoutMs: number = 30000): Promise<void> {\n if (this.isShuttingDown) {\n return;\n }\n\n this.isShuttingDown = true;\n this.emit('engine:shutdown:start');\n\n try {\n // Cancel all active executions\n const cancellationPromises = Array.from(this.activeExecutions.values()).map((context) =>\n this.cancelExecution(context),\n );\n\n // Wait for cancellations with timeout\n await Promise.race([\n Promise.all(cancellationPromises),\n new Promise((_, reject) =>\n setTimeout(() => reject(new Error('Shutdown timeout')), timeoutMs),\n ),\n ]);\n\n // Clean up backend\n if (this.currentBackend) {\n await this.currentBackend.cleanup();\n this.currentBackend = null;\n }\n\n // Run cleanup tasks\n await Promise.all(this.cleanupTasks.map((task) => task()));\n\n this.emit('engine:shutdown:complete');\n } catch (error) {\n this.emit('engine:shutdown:error', error);\n throw error;\n } finally {\n this.removeAllListeners();\n }\n }\n\n /**\n * Get statistics for all executions\n *\n * @returns Aggregate execution statistics\n */\n getExecutionStatistics(): ExecutionStatistics {\n const contexts = Array.from(this.activeExecutions.values());\n\n return {\n totalIterations: contexts.reduce((sum, ctx) => sum + ctx.statistics.totalIterations, 0),\n successfulIterations: contexts.reduce(\n (sum, ctx) => sum + ctx.statistics.successfulIterations,\n 0,\n ),\n failedIterations: contexts.reduce((sum, ctx) => sum + ctx.statistics.failedIterations, 0),\n averageIterationDuration: this.calculateAverageIterationDuration(contexts),\n totalToolCalls: contexts.reduce((sum, ctx) => sum + ctx.statistics.totalToolCalls, 0),\n totalProgressEvents: contexts.reduce(\n (sum, ctx) => sum + ctx.statistics.totalProgressEvents,\n 0,\n ),\n rateLimitEncounters: contexts.reduce(\n (sum, ctx) => sum + ctx.statistics.rateLimitEncounters,\n 0,\n ),\n rateLimitWaitTime: contexts.reduce((sum, ctx) => sum + ctx.statistics.rateLimitWaitTime, 0),\n quotaLimitEncounters: contexts.reduce(\n (sum, ctx) => sum + (ctx.statistics.quotaLimitEncounters ?? 0),\n 0,\n ),\n quotaLimitWaitTime: contexts.reduce(\n (sum, ctx) => sum + (ctx.statistics.quotaLimitWaitTime ?? 0),\n 0,\n ),\n errorBreakdown: this.aggregateErrorBreakdown(contexts),\n performanceMetrics: this.calculatePerformanceMetrics(contexts),\n };\n }\n\n // =============================================================================\n // Private Implementation Methods\n // =============================================================================\n\n /**\n * Setup error handling for the engine\n */\n private setupErrorHandling(): void {\n // Backend-agnostic error handling\n process.on('uncaughtException', (error) => {\n this.emit('engine:uncaught-exception', error);\n });\n\n process.on('unhandledRejection', (reason) => {\n this.emit('engine:unhandled-rejection', reason);\n });\n }\n\n /**\n * Setup progress tracking for the engine\n */\n private setupProgressTracking(): void {\n // Progress tracking will be set up when backend is initialized\n // The backend manager will handle progress callbacks\n }\n\n /**\n * Initialize backend for execution request.\n * Directly creates and configures a ShellBackend (no factory indirection).\n */\n private async initializeBackend(request: ExecutionRequest): Promise<void> {\n // Clean up existing backend if present\n if (this.currentBackend) {\n await this.currentBackend.cleanup();\n this.currentBackend = null;\n }\n\n // Create ShellBackend directly\n const { ShellBackend } = await import('./backends/shell-backend.js');\n const backend = new ShellBackend();\n\n // Configure\n (backend as any).configure({\n workingDirectory: request.workingDirectory,\n servicesPath: `${process.env.HOME || process.env.USERPROFILE}/.juno_code/services`,\n debug: this.engineConfig.config.verbose,\n timeout: request.timeoutMs || this.engineConfig.config.mcpTimeout || 43200000,\n enableJsonStreaming: true,\n outputRawJson: this.engineConfig.config.verbose,\n environment: process.env,\n sessionId: request.requestId,\n });\n\n // Initialize and check availability\n await backend.initialize();\n\n const isAvailable = await backend.isAvailable();\n if (!isAvailable) {\n throw new Error(\n 'Shell backend is not available. Ensure ~/.juno_code/services/ exists and contains service scripts.',\n );\n }\n\n this.currentBackend = backend;\n\n // Set up progress tracking for the selected backend\n backend.onProgress(async (event: ProgressEvent) => {\n try {\n // Process through configured processors\n for (const processor of this.engineConfig.progressConfig.processors) {\n await processor.process(event);\n }\n\n // Notify all registered callbacks\n await Promise.all([...this.progressCallbacks.map((callback) => callback(event))]);\n\n this.emit('progress:event', event);\n } catch (error) {\n this.emit('progress:error', { event, error });\n }\n });\n\n engineLogger.info(`Initialized ${backend.name} backend for execution`);\n }\n\n /**\n * Validate execution request parameters\n */\n private validateRequest(request: ExecutionRequest): void {\n if (!request.requestId?.trim()) {\n throw new Error('Request ID is required');\n }\n\n if (!request.instruction?.trim()) {\n throw new Error('Instruction is required');\n }\n\n if (!request.subagent?.trim()) {\n throw new Error('Subagent is required');\n }\n\n if (!request.workingDirectory?.trim()) {\n throw new Error('Working directory is required');\n }\n\n if (\n Number.isNaN(request.maxIterations) ||\n request.maxIterations < -1 ||\n request.maxIterations === 0\n ) {\n throw new Error('Max iterations must be a positive number or -1 for unlimited');\n }\n }\n\n /**\n * Create execution context for a request\n */\n private createExecutionContext(\n request: ExecutionRequest,\n abortSignal?: AbortSignal,\n ): ExecutionContext {\n const abortController = new AbortController();\n\n // Chain external abort signal if provided\n if (abortSignal) {\n abortSignal.addEventListener('abort', () => {\n abortController.abort();\n });\n }\n\n return {\n request,\n status: ExecutionStatus.PENDING,\n startTime: new Date(),\n endTime: null,\n iterations: [],\n statistics: this.createInitialStatistics(),\n progressEvents: [],\n error: null,\n abortController,\n sessionContext: this.createSessionContext(request),\n rateLimitInfo: {\n isRateLimited: false,\n remaining: 100,\n waitTimeMs: 0,\n },\n };\n }\n\n /**\n * Create initial statistics object\n */\n private createInitialStatistics(): ExecutionStatistics {\n return {\n totalIterations: 0,\n successfulIterations: 0,\n failedIterations: 0,\n averageIterationDuration: 0,\n totalToolCalls: 0,\n totalProgressEvents: 0,\n rateLimitEncounters: 0,\n rateLimitWaitTime: 0,\n quotaLimitEncounters: 0,\n quotaLimitWaitTime: 0,\n errorBreakdown: {},\n performanceMetrics: {\n cpuUsage: 0,\n memoryUsage: 0,\n networkRequests: 0,\n fileSystemOperations: 0,\n throughput: {\n iterationsPerMinute: 0,\n progressEventsPerSecond: 0,\n toolCallsPerMinute: 0,\n },\n },\n };\n }\n\n /**\n * Create session context for execution\n */\n private createSessionContext(request: ExecutionRequest): SessionContext {\n return {\n sessionId: `session-${request.requestId}`,\n startTime: new Date(),\n userId: 'system',\n metadata: {\n ...request.sessionMetadata,\n subagent: request.subagent,\n workingDirectory: request.workingDirectory,\n },\n activeToolCalls: [],\n state: 'initializing' as any,\n lastActivity: new Date(),\n };\n }\n\n /**\n * Internal execution implementation\n */\n private async executeInternal(context: ExecutionContext): Promise<ExecutionResult> {\n context.status = ExecutionStatus.RUNNING;\n context.sessionContext = { ...context.sessionContext, state: 'active' as any };\n\n // Initialize backend for this execution request\n await this.initializeBackend(context.request);\n\n // Execute START_RUN hook\n try {\n if (this.engineConfig.config.hooks && !this.engineConfig.config.skipHooks) {\n await executeHook(\n 'START_RUN',\n this.engineConfig.config.hooks,\n {\n workingDirectory: context.request.workingDirectory,\n sessionId: context.sessionContext.sessionId,\n runId: context.request.requestId,\n metadata: {\n sessionId: context.sessionContext.sessionId,\n requestId: context.request.requestId,\n subagent: context.request.subagent,\n backend: context.request.backend,\n maxIterations: context.request.maxIterations,\n instruction: context.request.instruction,\n },\n },\n {\n commandTimeout: this.engineConfig.config.hookCommandTimeout,\n },\n );\n }\n } catch (error) {\n engineLogger.warn('Hook START_RUN failed', { error });\n // Continue execution despite hook failure\n }\n\n try {\n await this.runIterationLoop(context);\n\n // Determine final status: if all iterations failed, mark execution as failed\n const hasSuccessfulIteration = context.statistics.successfulIterations > 0;\n if (hasSuccessfulIteration || context.statistics.totalIterations === 0) {\n context.status = ExecutionStatus.COMPLETED;\n context.sessionContext = { ...context.sessionContext, state: 'completed' as any };\n } else {\n context.status = ExecutionStatus.FAILED;\n context.sessionContext = { ...context.sessionContext, state: 'failed' as any };\n }\n } catch (error) {\n context.error = this.wrapError(error);\n context.status = this.determineErrorStatus(context.error);\n context.sessionContext = { ...context.sessionContext, state: 'failed' as any };\n } finally {\n context.endTime = new Date();\n }\n\n // Execute END_RUN hook\n try {\n if (this.engineConfig.config.hooks && !this.engineConfig.config.skipHooks) {\n await executeHook(\n 'END_RUN',\n this.engineConfig.config.hooks,\n {\n workingDirectory: context.request.workingDirectory,\n sessionId: context.sessionContext.sessionId,\n runId: context.request.requestId,\n metadata: {\n sessionId: context.sessionContext.sessionId,\n requestId: context.request.requestId,\n status: context.status,\n totalIterations: context.statistics.totalIterations,\n successfulIterations: context.statistics.successfulIterations,\n failedIterations: context.statistics.failedIterations,\n duration: context.endTime\n ? context.endTime.getTime() - context.startTime.getTime()\n : 0,\n success: context.status === ExecutionStatus.COMPLETED,\n },\n },\n {\n commandTimeout: this.engineConfig.config.hookCommandTimeout,\n },\n );\n }\n } catch (error) {\n engineLogger.warn('Hook END_RUN failed', { error });\n // Continue execution despite hook failure\n }\n\n return this.createExecutionResult(context);\n }\n\n /**\n * Run the main iteration loop\n */\n private async runIterationLoop(context: ExecutionContext): Promise<void> {\n let iterationNumber = 1;\n\n while (!this.shouldStopIterating(context, iterationNumber)) {\n this.checkAbortSignal(context);\n\n try {\n const quotaLimitInfo = await this.executeIteration(context, iterationNumber);\n\n // Check if a quota limit was encountered\n if (quotaLimitInfo?.detected) {\n const shouldRetry = await this.handleQuotaLimit(context, quotaLimitInfo);\n if (shouldRetry) {\n // Don't increment iteration number, retry same iteration\n continue;\n }\n }\n\n iterationNumber++;\n } catch (error) {\n if (error instanceof RateLimitError) {\n await this.handleRateLimit(context, error);\n // Don't increment iteration number, retry same iteration\n continue;\n }\n\n const shouldContinue = await this.handleIterationError(context, error, iterationNumber);\n if (!shouldContinue) {\n throw error;\n }\n\n iterationNumber++;\n }\n\n // Brief delay between iterations\n await this.sleep(2000);\n }\n }\n\n /**\n * Execute a single iteration\n * @returns QuotaLimitInfo if a quota limit was detected, null otherwise\n */\n private async executeIteration(\n context: ExecutionContext,\n iterationNumber: number,\n ): Promise<QuotaLimitInfo | null> {\n const iterationStart = new Date();\n\n // Execute START_ITERATION hook\n try {\n if (this.engineConfig.config.hooks && !this.engineConfig.config.skipHooks) {\n await executeHook(\n 'START_ITERATION',\n this.engineConfig.config.hooks,\n {\n workingDirectory: context.request.workingDirectory,\n sessionId: context.sessionContext.sessionId,\n runId: context.request.requestId,\n iteration: iterationNumber,\n totalIterations: context.request.maxIterations,\n metadata: {\n sessionId: context.sessionContext.sessionId,\n requestId: context.request.requestId,\n iterationNumber,\n maxIterations: context.request.maxIterations,\n subagent: context.request.subagent,\n },\n },\n {\n commandTimeout: this.engineConfig.config.hookCommandTimeout,\n },\n );\n }\n } catch (error) {\n engineLogger.warn('Hook START_ITERATION failed', { error, iterationNumber });\n // Continue execution despite hook failure\n }\n\n this.emit('iteration:start', { context, iterationNumber });\n\n const toolRequest: ToolCallRequest = {\n toolName: this.getToolNameForSubagent(context.request.subagent),\n arguments: {\n instruction: context.request.instruction,\n project_path: context.request.workingDirectory,\n ...(context.request.model !== undefined && { model: context.request.model }),\n ...(context.request.agents !== undefined && { agents: context.request.agents }),\n ...(context.request.tools !== undefined && { tools: context.request.tools }),\n ...(context.request.allowedTools !== undefined && {\n allowedTools: context.request.allowedTools,\n }),\n ...(context.request.appendAllowedTools !== undefined && {\n appendAllowedTools: context.request.appendAllowedTools,\n }),\n ...(context.request.disallowedTools !== undefined && {\n disallowedTools: context.request.disallowedTools,\n }),\n ...(context.request.resume !== undefined && { resume: context.request.resume }),\n ...(context.request.continueConversation !== undefined && {\n continueConversation: context.request.continueConversation,\n }),\n iteration: iterationNumber,\n },\n timeout: context.request.timeoutMs || this.engineConfig.config.mcpTimeout,\n priority: context.request.priority || 'normal',\n metadata: {\n sessionId: context.sessionContext.sessionId,\n iterationNumber,\n },\n progressCallback: async (event: ProgressEvent) => {\n context.progressEvents.push(event);\n context.statistics.totalProgressEvents++;\n await this.processProgressEvent(context, event);\n },\n };\n\n try {\n if (!this.currentBackend) {\n throw new Error('No backend initialized. Call initializeBackend() first.');\n }\n const toolResult = await this.currentBackend.execute(toolRequest);\n\n const iterationEnd = new Date();\n const duration = iterationEnd.getTime() - iterationStart.getTime();\n\n const iterationResult: IterationResult = {\n iterationNumber,\n success: toolResult.status?.toLowerCase() === 'completed',\n startTime: iterationStart,\n endTime: iterationEnd,\n duration,\n toolResult,\n progressEvents: toolResult.progressEvents,\n ...(toolResult.error !== undefined &&\n toolResult.error !== null && { error: toolResult.error }),\n };\n\n context.iterations.push(iterationResult);\n this.updateStatistics(context, iterationResult);\n\n this.emit('iteration:complete', { context, iterationResult });\n\n // Execute END_ITERATION hook for successful iteration\n try {\n if (this.engineConfig.config.hooks && !this.engineConfig.config.skipHooks) {\n await executeHook(\n 'END_ITERATION',\n this.engineConfig.config.hooks,\n {\n workingDirectory: context.request.workingDirectory,\n sessionId: context.sessionContext.sessionId,\n runId: context.request.requestId,\n iteration: iterationNumber,\n totalIterations: context.request.maxIterations,\n metadata: {\n sessionId: context.sessionContext.sessionId,\n requestId: context.request.requestId,\n iterationNumber,\n success: iterationResult.success,\n duration: iterationResult.duration,\n toolCallStatus: iterationResult.toolResult.status,\n },\n },\n {\n commandTimeout: this.engineConfig.config.hookCommandTimeout,\n },\n );\n }\n } catch (error) {\n engineLogger.warn('Hook END_ITERATION failed', { error, iterationNumber });\n // Continue execution despite hook failure\n }\n\n // Check for quota limit in the result\n const quotaLimitInfo = this.extractQuotaLimitInfo(toolResult);\n return quotaLimitInfo;\n } catch (error) {\n const iterationEnd = new Date();\n const duration = iterationEnd.getTime() - iterationStart.getTime();\n const mcpError = this.wrapError(error);\n\n const iterationResult: IterationResult = {\n iterationNumber,\n success: false,\n startTime: iterationStart,\n endTime: iterationEnd,\n duration,\n toolResult: {\n content: '',\n status: 'failed' as any,\n startTime: iterationStart,\n endTime: iterationEnd,\n duration,\n error: mcpError,\n progressEvents: [],\n request: toolRequest,\n },\n progressEvents: [],\n error: mcpError,\n };\n\n context.iterations.push(iterationResult);\n this.updateStatistics(context, iterationResult);\n\n this.emit('iteration:error', { context, iterationResult });\n\n // Execute END_ITERATION hook for failed iteration\n try {\n if (this.engineConfig.config.hooks && !this.engineConfig.config.skipHooks) {\n await executeHook(\n 'END_ITERATION',\n this.engineConfig.config.hooks,\n {\n workingDirectory: context.request.workingDirectory,\n sessionId: context.sessionContext.sessionId,\n runId: context.request.requestId,\n iteration: iterationNumber,\n totalIterations: context.request.maxIterations,\n metadata: {\n sessionId: context.sessionContext.sessionId,\n requestId: context.request.requestId,\n iterationNumber,\n success: false,\n duration: iterationResult.duration,\n error: mcpError.message,\n errorType: mcpError.type,\n },\n },\n {\n commandTimeout: this.engineConfig.config.hookCommandTimeout,\n },\n );\n }\n } catch (hookError) {\n engineLogger.warn('Hook END_ITERATION failed', { error: hookError, iterationNumber });\n // Continue execution despite hook failure\n }\n\n throw error;\n }\n }\n\n /**\n * Handle rate limit errors with automatic retry\n */\n private async handleRateLimit(context: ExecutionContext, error: RateLimitError): Promise<void> {\n if (!this.engineConfig.rateLimitConfig.enabled) {\n throw error;\n }\n\n context.statistics.rateLimitEncounters++;\n\n const waitTimeMs = this.calculateRateLimitWaitTime(error);\n if (waitTimeMs > this.engineConfig.rateLimitConfig.maxWaitTimeMs) {\n throw new Error(\n `Rate limit wait time (${waitTimeMs}ms) exceeds maximum allowed (${this.engineConfig.rateLimitConfig.maxWaitTimeMs}ms)`,\n );\n }\n\n context.statistics.rateLimitWaitTime += waitTimeMs;\n context.rateLimitInfo = {\n isRateLimited: true,\n ...(error.resetTime !== undefined && { resetTime: error.resetTime }),\n remaining: error.remaining || 0,\n waitTimeMs,\n ...(error.tier !== undefined && { tier: error.tier }),\n };\n\n this.emit('rate-limit:start', { context, error, waitTimeMs });\n\n await this.sleep(waitTimeMs);\n\n context.rateLimitInfo = {\n isRateLimited: false,\n remaining: 100,\n waitTimeMs: 0,\n };\n\n this.emit('rate-limit:end', { context });\n }\n\n /**\n * Calculate wait time for rate limit reset\n */\n private calculateRateLimitWaitTime(error: RateLimitError): number {\n if (error.resetTime) {\n const now = new Date();\n const waitTime = error.resetTime.getTime() - now.getTime();\n return Math.max(0, waitTime);\n }\n\n // Default wait time if no reset time provided\n return 60000; // 1 minute\n }\n\n /**\n * Handle Claude quota limit with automatic sleep and retry\n * @returns true if we should retry the iteration, false otherwise\n */\n private async handleQuotaLimit(\n context: ExecutionContext,\n quotaInfo: QuotaLimitInfo,\n ): Promise<boolean> {\n if (!quotaInfo.detected || !quotaInfo.sleepDurationMs) {\n return false;\n }\n\n context.statistics.quotaLimitEncounters++;\n\n // Check the onHourlyLimit configuration setting\n // Priority: config.json < ENV < Flag (all handled by the config loader)\n const onHourlyLimit = this.engineConfig.config.onHourlyLimit || 'raise';\n\n // If set to 'raise', exit immediately instead of waiting\n if (onHourlyLimit === 'raise') {\n const resetTimeStr = quotaInfo.resetTime\n ? quotaInfo.resetTime.toLocaleTimeString('en-US', {\n hour: 'numeric',\n minute: '2-digit',\n hour12: true,\n timeZoneName: 'short',\n })\n : 'unknown';\n\n const sourceLabel = quotaInfo.source === 'codex' ? 'Codex' : 'Claude';\n\n engineLogger.info(`╔════════════════════════════════════════════════════════════════╗`);\n engineLogger.info(\n `║ ${sourceLabel} Quota Limit Reached${' '.repeat(44 - sourceLabel.length - ' Quota Limit Reached'.length)}║`,\n );\n engineLogger.info(`╠════════════════════════════════════════════════════════════════╣`);\n engineLogger.info(`║ Quota resets at: ${resetTimeStr.padEnd(44)}║`);\n engineLogger.info(`║ Behavior: raise (exit immediately) ║`);\n engineLogger.info(`╠════════════════════════════════════════════════════════════════╣`);\n engineLogger.info(`║ To auto-wait instead, use: --on-hourly-limit wait ║`);\n engineLogger.info(`║ Or set: JUNO_CODE_ON_HOURLY_LIMIT=wait ║`);\n engineLogger.info(`║ Or in config.json: { \"onHourlyLimit\": \"wait\" } ║`);\n engineLogger.info(`╚════════════════════════════════════════════════════════════════╝`);\n\n this.emit('quota-limit:raise', { context, quotaInfo });\n\n // Return false to NOT retry, which will cause the iteration loop to continue\n // but since this is an error condition, we need to throw to actually exit\n throw new Error(\n `${sourceLabel} quota limit reached. Quota resets at ${resetTimeStr}. Use --on-hourly-limit wait to auto-retry.`,\n );\n }\n\n // onHourlyLimit === 'wait' - proceed with waiting behavior\n const waitTimeMs = quotaInfo.sleepDurationMs;\n\n // Cap the wait time at 12 hours to prevent excessive waits\n const maxWaitTimeMs = 12 * 60 * 60 * 1000; // 12 hours\n if (waitTimeMs > maxWaitTimeMs) {\n engineLogger.warn(\n `Quota limit wait time (${formatDuration(waitTimeMs)}) exceeds maximum allowed (12 hours). Will not auto-retry.`,\n );\n return false;\n }\n\n context.statistics.quotaLimitWaitTime += waitTimeMs;\n\n // Format the reset time for user display\n const resetTimeStr = quotaInfo.resetTime\n ? quotaInfo.resetTime.toLocaleTimeString('en-US', {\n hour: 'numeric',\n minute: '2-digit',\n hour12: true,\n timeZoneName: 'short',\n })\n : 'unknown';\n\n const durationStr = formatDuration(waitTimeMs);\n\n // Log user-friendly message\n const waitSourceLabel = quotaInfo.source === 'codex' ? 'Codex' : 'Claude';\n\n engineLogger.info(`╔════════════════════════════════════════════════════════════════╗`);\n engineLogger.info(\n `║ ${waitSourceLabel} Quota Limit Reached${' '.repeat(44 - waitSourceLabel.length - ' Quota Limit Reached'.length)}║`,\n );\n engineLogger.info(`╠════════════════════════════════════════════════════════════════╣`);\n engineLogger.info(`║ Quota resets at: ${resetTimeStr.padEnd(44)}║`);\n engineLogger.info(`║ Sleeping for: ${durationStr.padEnd(44)}║`);\n if (quotaInfo.timezone) {\n engineLogger.info(`║ Timezone: ${quotaInfo.timezone.padEnd(44)}║`);\n }\n engineLogger.info(`╚════════════════════════════════════════════════════════════════╝`);\n\n this.emit('quota-limit:start', { context, quotaInfo, waitTimeMs });\n\n // Sleep with periodic progress updates\n await this.sleepWithProgress(waitTimeMs, (remaining) => {\n const remainingStr = formatDuration(remaining);\n engineLogger.info(`[Quota Wait] ${remainingStr} remaining until retry...`);\n });\n\n this.emit('quota-limit:end', { context });\n\n engineLogger.info(`Quota limit wait complete. Resuming execution...`);\n\n return true;\n }\n\n /**\n * Sleep with periodic progress updates\n */\n private async sleepWithProgress(\n totalMs: number,\n onProgress: (remainingMs: number) => void,\n ): Promise<void> {\n const updateIntervalMs = 60000; // Update every minute\n let remaining = totalMs;\n\n while (remaining > 0) {\n const sleepTime = Math.min(remaining, updateIntervalMs);\n await this.sleep(sleepTime);\n remaining -= sleepTime;\n\n if (remaining > 0) {\n onProgress(remaining);\n }\n }\n }\n\n /**\n * Check if tool result indicates a quota limit error\n */\n private extractQuotaLimitInfo(toolResult: ToolCallResult): QuotaLimitInfo | null {\n // Check metadata first (most reliable)\n const metadataQuotaInfo = (toolResult.metadata as any)?.quotaLimitInfo;\n if (metadataQuotaInfo?.detected) {\n return metadataQuotaInfo;\n }\n\n // Try to parse from content if metadata doesn't have it\n try {\n const content =\n typeof toolResult.content === 'string'\n ? JSON.parse(toolResult.content)\n : toolResult.content;\n\n if (content?.quota_limit?.detected) {\n return content.quota_limit;\n }\n } catch {\n // Ignore parse errors\n }\n\n return null;\n }\n\n /**\n * Handle iteration errors with recovery strategies\n */\n private async handleIterationError(\n context: ExecutionContext,\n error: unknown,\n iterationNumber: number,\n ): Promise<boolean> {\n const mcpError = this.wrapError(error);\n const errorType = mcpError.type;\n\n context.statistics.errorBreakdown[errorType] =\n (context.statistics.errorBreakdown[errorType] || 0) + 1;\n\n // Check if we should continue on this error type\n const shouldContinue = this.engineConfig.errorRecovery.continueOnError[errorType] ?? false;\n if (!shouldContinue) {\n return false;\n }\n\n // Attempt recovery if strategy exists\n const customStrategy = this.engineConfig.errorRecovery.customStrategies[errorType];\n if (customStrategy) {\n try {\n const recovered = await customStrategy(mcpError);\n if (recovered) {\n this.emit('error:recovered', { context, error: mcpError, iterationNumber });\n return true;\n }\n } catch (recoveryError) {\n this.emit('error:recovery-failed', {\n context,\n error: mcpError,\n recoveryError,\n iterationNumber,\n });\n }\n }\n\n // Apply retry delay if configured\n const retryDelay = this.engineConfig.errorRecovery.retryDelays[errorType] || 0;\n if (retryDelay > 0) {\n await this.sleep(retryDelay);\n }\n\n this.emit('error:continuing', { context, error: mcpError, iterationNumber });\n return true;\n }\n\n /**\n * Process individual progress events\n */\n private async processProgressEvent(\n context: ExecutionContext,\n event: ProgressEvent,\n ): Promise<void> {\n // Apply filters\n for (const filter of this.engineConfig.progressConfig.filters) {\n if (!filter.predicate(event)) {\n return;\n }\n }\n\n // Update session activity\n context.sessionContext = {\n ...context.sessionContext,\n lastActivity: new Date(),\n };\n\n this.emit('progress:processed', { context, event });\n }\n\n /**\n * Update execution statistics\n */\n private updateStatistics(context: ExecutionContext, iteration: IterationResult): void {\n const stats = context.statistics;\n\n stats.totalIterations++;\n stats.totalToolCalls++;\n\n if (iteration.success) {\n stats.successfulIterations++;\n } else {\n stats.failedIterations++;\n }\n\n // Update average iteration duration\n const totalDuration =\n stats.averageIterationDuration * (stats.totalIterations - 1) + iteration.duration;\n stats.averageIterationDuration = totalDuration / stats.totalIterations;\n\n // Update performance metrics\n this.updatePerformanceMetrics(context);\n }\n\n /**\n * Update performance metrics\n */\n private updatePerformanceMetrics(context: ExecutionContext): void {\n const metrics = context.statistics.performanceMetrics;\n\n // Get current resource usage\n const memUsage = process.memoryUsage();\n metrics.memoryUsage = memUsage.heapUsed;\n\n // Calculate throughput\n const duration = Date.now() - context.startTime.getTime();\n const durationMinutes = duration / (1000 * 60);\n\n if (durationMinutes > 0) {\n metrics.throughput.iterationsPerMinute = context.statistics.totalIterations / durationMinutes;\n metrics.throughput.toolCallsPerMinute = context.statistics.totalToolCalls / durationMinutes;\n metrics.throughput.progressEventsPerSecond =\n context.statistics.totalProgressEvents / (duration / 1000);\n }\n }\n\n /**\n * Check if iteration loop should stop\n */\n private shouldStopIterating(context: ExecutionContext, iterationNumber: number): boolean {\n // Check abort signal\n if (context.abortController.signal.aborted) {\n return true;\n }\n\n // Check max iterations\n if (context.request.maxIterations !== -1 && iterationNumber > context.request.maxIterations) {\n return true;\n }\n\n // Check for shutdown\n if (this.isShuttingDown) {\n return true;\n }\n\n return false;\n }\n\n /**\n * Check abort signal and throw if aborted\n */\n private checkAbortSignal(context: ExecutionContext): void {\n if (context.abortController.signal.aborted) {\n throw new Error('Execution aborted');\n }\n }\n\n /**\n * Get tool name for subagent\n */\n private getToolNameForSubagent(subagent: SubagentType): string {\n const mapping: Record<SubagentType, string> = {\n claude: 'claude_subagent',\n cursor: 'cursor_subagent',\n codex: 'codex_subagent',\n gemini: 'gemini_subagent',\n pi: 'pi_subagent',\n };\n\n return mapping[subagent] || 'claude_subagent';\n }\n\n /**\n * Wrap unknown errors as execution errors\n */\n private wrapError(error: unknown): ExecutionError {\n if (error instanceof ExecutionError) {\n return error;\n }\n\n // Classify common transport/socket failures as connection errors so the loop can continue\n const msg = error instanceof Error ? `${error.name}: ${error.message}` : String(error);\n const lower = msg.toLowerCase();\n const isConnectionLike = [\n 'epipe',\n 'broken pipe',\n 'econnreset',\n 'socket hang up',\n 'err_socket_closed',\n 'connection reset by peer',\n ].some((token) => lower.includes(token));\n\n if (isConnectionLike) {\n return {\n type: 'connection',\n message: msg,\n timestamp: new Date(),\n code: 'MCP_CONNECTION_LOST' as any,\n } as any;\n }\n\n // Fallback: treat as tool execution error\n return {\n type: 'tool_execution',\n message: msg,\n timestamp: new Date(),\n } as any;\n }\n\n /**\n * Determine execution status from error\n */\n private determineErrorStatus(error: ExecutionError): ExecutionStatus {\n switch (error.type) {\n case 'rate_limit':\n return ExecutionStatus.RATE_LIMITED;\n case 'timeout':\n return ExecutionStatus.TIMEOUT;\n default:\n return ExecutionStatus.FAILED;\n }\n }\n\n /**\n * Create final execution result\n */\n private createExecutionResult(context: ExecutionContext): ExecutionResult {\n const endTime = context.endTime || new Date();\n return {\n request: context.request,\n status: context.status,\n startTime: context.startTime,\n endTime,\n duration: endTime.getTime() - context.startTime.getTime(),\n iterations: context.iterations,\n statistics: context.statistics,\n ...(context.error !== undefined && context.error !== null && { error: context.error }),\n sessionContext: context.sessionContext,\n progressEvents: context.progressEvents,\n };\n }\n\n /**\n * Cancel an execution\n */\n private async cancelExecution(context: ExecutionContext): Promise<void> {\n context.abortController.abort();\n context.status = ExecutionStatus.CANCELLED;\n this.emit('execution:cancelled', { context });\n }\n\n /**\n * Cleanup execution resources\n */\n private async cleanupExecution(context: ExecutionContext): Promise<void> {\n // Cleanup would happen here\n this.emit('execution:cleanup', { context });\n }\n\n /**\n * Calculate average iteration duration across contexts\n */\n private calculateAverageIterationDuration(contexts: ExecutionContext[]): number {\n if (contexts.length === 0) return 0;\n\n const totalDuration = contexts.reduce(\n (sum, ctx) => sum + ctx.statistics.averageIterationDuration * ctx.statistics.totalIterations,\n 0,\n );\n const totalIterations = contexts.reduce((sum, ctx) => sum + ctx.statistics.totalIterations, 0);\n\n return totalIterations > 0 ? totalDuration / totalIterations : 0;\n }\n\n /**\n * Aggregate error breakdown across contexts\n */\n private aggregateErrorBreakdown(contexts: ExecutionContext[]): Record<string, number> {\n const breakdown: Record<string, number> = {};\n\n for (const context of contexts) {\n for (const [errorType, count] of Object.entries(context.statistics.errorBreakdown)) {\n breakdown[errorType] = (breakdown[errorType] || 0) + count;\n }\n }\n\n return breakdown;\n }\n\n /**\n * Calculate performance metrics across contexts\n */\n private calculatePerformanceMetrics(contexts: ExecutionContext[]): PerformanceMetrics {\n if (contexts.length === 0) {\n return {\n cpuUsage: 0,\n memoryUsage: 0,\n networkRequests: 0,\n fileSystemOperations: 0,\n throughput: {\n iterationsPerMinute: 0,\n progressEventsPerSecond: 0,\n toolCallsPerMinute: 0,\n },\n };\n }\n\n // Aggregate metrics from all contexts\n const avgMetrics = contexts.reduce(\n (acc, ctx) => ({\n cpuUsage: acc.cpuUsage + ctx.statistics.performanceMetrics.cpuUsage,\n memoryUsage: acc.memoryUsage + ctx.statistics.performanceMetrics.memoryUsage,\n networkRequests: acc.networkRequests + ctx.statistics.performanceMetrics.networkRequests,\n fileSystemOperations:\n acc.fileSystemOperations + ctx.statistics.performanceMetrics.fileSystemOperations,\n throughput: {\n iterationsPerMinute:\n acc.throughput.iterationsPerMinute +\n ctx.statistics.performanceMetrics.throughput.iterationsPerMinute,\n progressEventsPerSecond:\n acc.throughput.progressEventsPerSecond +\n ctx.statistics.performanceMetrics.throughput.progressEventsPerSecond,\n toolCallsPerMinute:\n acc.throughput.toolCallsPerMinute +\n ctx.statistics.performanceMetrics.throughput.toolCallsPerMinute,\n },\n }),\n {\n cpuUsage: 0,\n memoryUsage: 0,\n networkRequests: 0,\n fileSystemOperations: 0,\n throughput: {\n iterationsPerMinute: 0,\n progressEventsPerSecond: 0,\n toolCallsPerMinute: 0,\n },\n },\n );\n\n // Average the metrics\n const count = contexts.length;\n return {\n cpuUsage: avgMetrics.cpuUsage / count,\n memoryUsage: avgMetrics.memoryUsage / count,\n networkRequests: avgMetrics.networkRequests / count,\n fileSystemOperations: avgMetrics.fileSystemOperations / count,\n throughput: {\n iterationsPerMinute: avgMetrics.throughput.iterationsPerMinute / count,\n progressEventsPerSecond: avgMetrics.throughput.progressEventsPerSecond / count,\n toolCallsPerMinute: avgMetrics.throughput.toolCallsPerMinute / count,\n },\n };\n }\n\n /**\n * Sleep utility for delays\n */\n private async sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n\n// =============================================================================\n// Internal Types\n// =============================================================================\n\n/**\n * Internal execution context\n */\ninterface ExecutionContext {\n request: ExecutionRequest;\n status: ExecutionStatus;\n startTime: Date;\n endTime: Date | null;\n iterations: IterationResult[];\n statistics: ExecutionStatistics;\n progressEvents: ProgressEvent[];\n error: ExecutionError | null;\n abortController: AbortController;\n sessionContext: SessionContext;\n rateLimitInfo: RateLimitInfo;\n}\n\n// =============================================================================\n// Factory Functions\n// =============================================================================\n\n/**\n * Create an execution engine with default configuration\n *\n * @param config - Base juno-task configuration\n * @returns Configured execution engine\n */\nexport function createExecutionEngine(config: JunoTaskConfig): ExecutionEngine {\n return new ExecutionEngine({\n config,\n errorRecovery: DEFAULT_ERROR_RECOVERY_CONFIG,\n rateLimitConfig: DEFAULT_RATE_LIMIT_CONFIG,\n progressConfig: DEFAULT_PROGRESS_CONFIG,\n });\n}\n\n/**\n * Create an execution request with defaults\n *\n * @param options - Request options\n * @returns Execution request\n */\nexport function createExecutionRequest(options: {\n instruction: string;\n subagent?: SubagentType;\n backend?: BackendType;\n workingDirectory?: string;\n maxIterations?: number;\n model?: string;\n agents?: string;\n tools?: string[];\n allowedTools?: string[];\n appendAllowedTools?: string[];\n disallowedTools?: string[];\n requestId?: string;\n mcpServerName?: string;\n resume?: string;\n continueConversation?: boolean;\n}): ExecutionRequest {\n const result: ExecutionRequest = {\n requestId: options.requestId || `req-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,\n instruction: options.instruction,\n subagent: options.subagent || 'claude',\n backend: options.backend || 'shell',\n workingDirectory: options.workingDirectory || process.cwd(),\n maxIterations: options.maxIterations ?? 1,\n };\n\n if (options.model !== undefined) {\n (result as any).model = options.model;\n }\n\n if (options.agents !== undefined) {\n (result as any).agents = options.agents;\n }\n\n if (options.tools !== undefined) {\n (result as any).tools = options.tools;\n }\n\n if (options.allowedTools !== undefined) {\n (result as any).allowedTools = options.allowedTools;\n }\n\n if (options.appendAllowedTools !== undefined) {\n (result as any).appendAllowedTools = options.appendAllowedTools;\n }\n\n if (options.disallowedTools !== undefined) {\n (result as any).disallowedTools = options.disallowedTools;\n }\n\n if (options.mcpServerName !== undefined) {\n (result as any).mcpServerName = options.mcpServerName;\n }\n\n if (options.resume !== undefined) {\n (result as any).resume = options.resume;\n }\n\n if (options.continueConversation !== undefined) {\n (result as any).continueConversation = options.continueConversation;\n }\n\n return result;\n}\n","/**\n * Hook execution utility module for juno-task-ts\n *\n * Provides robust hook execution functionality with comprehensive logging,\n * error handling, and execution context tracking.\n *\n * @module utils/hooks\n */\n\nimport { execa } from 'execa';\nimport { logger, LogContext } from '../cli/utils/advanced-logger.js';\n\n/**\n * Supported hook types for lifecycle execution\n */\nexport type HookType = 'START_RUN' | 'START_ITERATION' | 'END_ITERATION' | 'END_RUN' | 'ON_STALE';\n\n/**\n * Hook configuration interface\n */\nexport interface Hook {\n /** List of bash commands to execute for this hook */\n commands: string[];\n}\n\n/**\n * Complete hooks configuration mapping hook types to their configurations\n */\nexport interface HooksConfig {\n [key: string]: Hook;\n}\n\n/**\n * Execution context for hooks - provides information about the current execution state\n */\nexport interface HookExecutionContext {\n /** Current iteration number (for iteration-based hooks) */\n iteration?: number;\n /** Session ID for tracking */\n sessionId?: string;\n /** Working directory for command execution */\n workingDirectory?: string;\n /** Additional metadata */\n metadata?: Record<string, any>;\n /** Run ID for tracking across hooks */\n runId?: string;\n /** Total iterations planned */\n totalIterations?: number;\n}\n\n/**\n * Result of a single command execution within a hook\n */\nexport interface CommandExecutionResult {\n /** The command that was executed */\n command: string;\n /** Exit code (0 for success) */\n exitCode: number;\n /** Standard output */\n stdout: string;\n /** Standard error output */\n stderr: string;\n /** Execution duration in milliseconds */\n duration: number;\n /** Whether the command succeeded */\n success: boolean;\n /** Error if execution failed */\n error?: Error;\n}\n\n/**\n * Result of executing all commands in a hook\n */\nexport interface HookExecutionResult {\n /** Hook type that was executed */\n hookType: HookType;\n /** Total execution duration for all commands */\n totalDuration: number;\n /** Results for each command */\n commandResults: CommandExecutionResult[];\n /** Overall success (true if all commands succeeded) */\n success: boolean;\n /** Number of commands executed */\n commandsExecuted: number;\n /** Number of commands that failed */\n commandsFailed: number;\n}\n\n/**\n * Hook execution options\n */\nexport interface HookExecutionOptions {\n /** Maximum timeout per command in milliseconds (default: 300000 = 5 minutes) */\n commandTimeout?: number | undefined;\n /** Environment variables to pass to commands */\n env?: Record<string, string> | undefined;\n /** Whether to continue executing commands if one fails (default: true) */\n continueOnError?: boolean | undefined;\n /** Custom logger context (default: 'SYSTEM') */\n logContext?: LogContext | undefined;\n}\n\n/**\n * Create a context-specific logger for hook execution\n */\nconst hookLogger = logger.child(LogContext.SYSTEM);\n\n/**\n * Execute a specific hook type with the provided context\n *\n * This is the main entry point for hook execution. It handles:\n * - Hook existence validation\n * - Sequential command execution\n * - Comprehensive logging with execution context\n * - Robust error handling (log but don't throw)\n * - Performance tracking\n *\n * @param hookType - The type of hook to execute\n * @param hooks - The complete hooks configuration\n * @param context - Execution context with iteration, session info, etc.\n * @param options - Additional execution options\n * @returns Promise that resolves when all commands complete (never throws)\n *\n * @example\n * ```typescript\n * const hooks = {\n * START_ITERATION: {\n * commands: ['echo \"Starting iteration $ITERATION\"', 'npm test']\n * }\n * };\n *\n * const context = {\n * iteration: 1,\n * sessionId: 'session-123',\n * workingDirectory: '/path/to/project'\n * };\n *\n * await executeHook('START_ITERATION', hooks, context);\n * ```\n */\nexport async function executeHook(\n hookType: HookType,\n hooks: HooksConfig,\n context: HookExecutionContext = {},\n options: HookExecutionOptions = {},\n): Promise<HookExecutionResult> {\n const startTime = Date.now();\n const {\n commandTimeout = 300000, // 5 minutes default (increased from 30s to support long-running hook scripts)\n env = {},\n continueOnError = true,\n logContext = LogContext.SYSTEM,\n } = options;\n\n // Create context-specific logger\n const contextLogger = logger.child(logContext);\n\n contextLogger.info(`Starting hook execution: ${hookType}`, {\n context,\n workingDirectory: context.workingDirectory || process.cwd(),\n commandTimeout,\n continueOnError,\n });\n\n // Check if hook exists\n const hook = hooks[hookType];\n if (!hook) {\n contextLogger.debug(`Hook ${hookType} not defined - skipping execution`);\n return {\n hookType,\n totalDuration: Date.now() - startTime,\n commandResults: [],\n success: true,\n commandsExecuted: 0,\n commandsFailed: 0,\n };\n }\n\n // Check if hook has commands\n if (!hook.commands || hook.commands.length === 0) {\n contextLogger.debug(`Hook ${hookType} has no commands - skipping execution`);\n return {\n hookType,\n totalDuration: Date.now() - startTime,\n commandResults: [],\n success: true,\n commandsExecuted: 0,\n commandsFailed: 0,\n };\n }\n\n contextLogger.info(`Executing ${hook.commands.length} commands for hook ${hookType}`);\n\n const commandResults: CommandExecutionResult[] = [];\n let commandsFailed = 0;\n\n // Execute each command sequentially\n for (let i = 0; i < hook.commands.length; i++) {\n const command = hook.commands[i]!;\n const commandStartTime = Date.now();\n\n contextLogger.info(`Executing command ${i + 1}/${hook.commands.length}: ${command}`, {\n commandIndex: i,\n totalCommands: hook.commands.length,\n });\n\n try {\n // Prepare environment variables with context\n const execEnv = {\n ...process.env,\n ...env,\n // Add context as environment variables\n HOOK_TYPE: hookType,\n ITERATION: context.iteration?.toString() || '',\n SESSION_ID: context.sessionId || '',\n RUN_ID: context.runId || '',\n TOTAL_ITERATIONS: context.totalIterations?.toString() || '',\n // Add any metadata as prefixed environment variables\n ...Object.fromEntries(\n Object.entries(context.metadata || {}).map(([key, value]) => [\n `JUNO_${key.toUpperCase()}`,\n String(value),\n ]),\n ),\n };\n\n // Execute command with timeout and proper working directory\n //\n // CRITICAL: Using `input: ''` to properly close stdin\n //\n // History of stdin handling issues:\n // - Issue #40: Added stdin: 'ignore' - fixed blocking but broke internal pipes\n // - Issue #41: Removed stdin: 'ignore', used default 'pipe' - allowed internal\n // pipes to work but caused commands to hang indefinitely when subprocess\n // tried to read stdin (because the stdin pipe was never closed)\n // - Issue #42 (current): Commands like `juno-kanban ... | grep -q \"...\"` would\n // hang for 5 minutes (timeout) because the shell's stdin pipe was never closed,\n // causing subprocesses to block waiting for EOF on stdin.\n //\n // Solution: Use `input: ''` which:\n // 1. Provides empty input to the subprocess\n // 2. Properly closes stdin (sends EOF)\n // 3. Allows internal pipes to work (shell manages its own pipes)\n // 4. Prevents commands from hanging waiting for stdin\n //\n // The key insight: `input: ''` tells execa to write an empty string to stdin\n // and then close it, which signals EOF to the subprocess. This is different\n // from `stdin: 'pipe'` (default) which leaves the pipe open indefinitely.\n const result = await execa(command, {\n shell: true,\n timeout: commandTimeout,\n cwd: context.workingDirectory || process.cwd(),\n env: execEnv,\n // Capture both stdout and stderr\n all: true,\n reject: false, // Don't throw on non-zero exit codes\n // Use input: '' to provide empty stdin and properly close it (sends EOF)\n // This prevents commands from hanging waiting for stdin while still\n // allowing internal pipe operations to work correctly\n input: '',\n });\n\n const duration = Date.now() - commandStartTime;\n const success = result.exitCode === 0;\n\n const commandResult: CommandExecutionResult = {\n command,\n exitCode: result.exitCode ?? -1,\n stdout: result.stdout || '',\n stderr: result.stderr || '',\n duration,\n success,\n };\n\n commandResults.push(commandResult);\n\n if (success) {\n contextLogger.info(`Command completed successfully`, {\n command,\n exitCode: result.exitCode,\n duration,\n stdout: result.stdout ? result.stdout.substring(0, 500) : undefined, // Truncate for logging\n });\n\n // Log stdout if present\n if (result.stdout) {\n contextLogger.debug(`Command stdout:`, { stdout: result.stdout });\n }\n } else {\n commandsFailed++;\n contextLogger.error(`Command failed`, {\n command,\n exitCode: result.exitCode,\n duration,\n stderr: result.stderr,\n stdout: result.stdout,\n });\n\n // Log stderr if present\n if (result.stderr) {\n contextLogger.error(`Command stderr:`, { stderr: result.stderr });\n }\n\n // If we shouldn't continue on error, break the loop\n if (!continueOnError) {\n contextLogger.warn(\n `Stopping hook execution due to command failure (continueOnError=false)`,\n );\n break;\n }\n }\n } catch (error) {\n const duration = Date.now() - commandStartTime;\n commandsFailed++;\n\n let errorMessage = 'Unknown error';\n let isTimeout = false;\n\n if (error instanceof Error) {\n errorMessage = error.message;\n // Check for execa-specific timeout property\n isTimeout = 'timedOut' in error ? Boolean((error as any).timedOut) : false;\n }\n\n const commandResult: CommandExecutionResult = {\n command,\n exitCode: -1,\n stdout: '',\n stderr: errorMessage,\n duration,\n success: false,\n error: error as Error,\n };\n\n commandResults.push(commandResult);\n\n if (isTimeout) {\n contextLogger.error(`Command timed out after ${commandTimeout}ms`, {\n command,\n timeout: commandTimeout,\n duration,\n error: errorMessage,\n });\n } else {\n contextLogger.error(`Command execution failed`, {\n command,\n duration,\n error: errorMessage,\n });\n }\n\n // If we shouldn't continue on error, break the loop\n if (!continueOnError) {\n contextLogger.warn(\n `Stopping hook execution due to command failure (continueOnError=false)`,\n );\n break;\n }\n }\n }\n\n const totalDuration = Date.now() - startTime;\n const success = commandsFailed === 0;\n const commandsExecuted = commandResults.length;\n\n const result: HookExecutionResult = {\n hookType,\n totalDuration,\n commandResults,\n success,\n commandsExecuted,\n commandsFailed,\n };\n\n contextLogger.info(`Hook execution completed`, {\n hookType,\n totalDuration,\n commandsExecuted,\n commandsFailed,\n success,\n });\n\n return result;\n}\n\n/**\n * Execute multiple hooks in sequence\n *\n * Convenience function for executing multiple hooks with the same context.\n * Each hook is executed independently - failure of one hook does not stop\n * execution of subsequent hooks.\n *\n * @param hookTypes - Array of hook types to execute\n * @param hooks - The complete hooks configuration\n * @param context - Execution context\n * @param options - Execution options\n * @returns Promise resolving to array of hook execution results\n */\nexport async function executeHooks(\n hookTypes: HookType[],\n hooks: HooksConfig,\n context: HookExecutionContext = {},\n options: HookExecutionOptions = {},\n): Promise<HookExecutionResult[]> {\n const results: HookExecutionResult[] = [];\n\n hookLogger.info(`Starting batch hook execution`, {\n hookTypes,\n context,\n });\n\n for (const hookType of hookTypes) {\n const result = await executeHook(hookType, hooks, context, options);\n results.push(result);\n }\n\n const totalSuccess = results.every((r) => r.success);\n const totalCommands = results.reduce((sum, r) => sum + r.commandsExecuted, 0);\n const totalFailed = results.reduce((sum, r) => sum + r.commandsFailed, 0);\n\n hookLogger.info(`Batch hook execution completed`, {\n hookTypes,\n totalHooks: results.length,\n totalCommands,\n totalFailed,\n success: totalSuccess,\n });\n\n return results;\n}\n\n/**\n * Validate hooks configuration\n *\n * Checks that all hook configurations are valid and provides warnings\n * for common issues.\n *\n * @param hooks - Hooks configuration to validate\n * @returns Validation result with any issues found\n */\nexport function validateHooksConfig(hooks: HooksConfig): {\n valid: boolean;\n issues: string[];\n warnings: string[];\n} {\n const issues: string[] = [];\n const warnings: string[] = [];\n\n const validHookTypes: HookType[] = [\n 'START_RUN',\n 'START_ITERATION',\n 'END_ITERATION',\n 'END_RUN',\n 'ON_STALE',\n ];\n\n for (const [hookType, hook] of Object.entries(hooks)) {\n // Check if hook type is valid\n if (!validHookTypes.includes(hookType as HookType)) {\n warnings.push(\n `Unknown hook type: ${hookType}. Valid types are: ${validHookTypes.join(', ')}`,\n );\n }\n\n // Check if hook has commands array\n if (!hook.commands) {\n issues.push(`Hook ${hookType} is missing 'commands' array`);\n continue;\n }\n\n if (!Array.isArray(hook.commands)) {\n issues.push(`Hook ${hookType} 'commands' must be an array`);\n continue;\n }\n\n // Check if commands are strings\n for (let i = 0; i < hook.commands.length; i++) {\n const command = hook.commands[i];\n if (typeof command !== 'string') {\n issues.push(`Hook ${hookType} command ${i} must be a string, got ${typeof command}`);\n } else if (command.trim() === '') {\n warnings.push(`Hook ${hookType} command ${i} is empty`);\n }\n }\n\n // Warn about potentially dangerous commands\n const dangerousPatterns = [/rm\\s+-rf\\s+\\//, /sudo\\s+rm/, /format\\s+c:/i, /del\\s+\\/s/i];\n\n for (const command of hook.commands) {\n if (typeof command === 'string') {\n for (const pattern of dangerousPatterns) {\n if (pattern.test(command)) {\n warnings.push(`Hook ${hookType} contains potentially dangerous command: ${command}`);\n }\n }\n }\n }\n }\n\n return {\n valid: issues.length === 0,\n issues,\n warnings,\n };\n}\n\n/**\n * Default export for convenience\n */\nexport default {\n executeHook,\n executeHooks,\n validateHooksConfig,\n};\n","/**\n * Core session management module for juno-code\n * @module core/session\n */\nimport * as path from 'node:path';\nimport * as fs from 'node:fs';\nimport { v4 as uuidv4 } from 'uuid';\nimport type { JunoTaskConfig, SessionStatus, SubagentType } from '../types/index';\n\n/** Session metadata */\nexport interface SessionInfo {\n id: string;\n name?: string;\n status: SessionStatus;\n subagent: SubagentType;\n createdAt: Date;\n updatedAt: Date;\n completedAt?: Date;\n workingDirectory: string;\n config: Partial<JunoTaskConfig>;\n tags: string[];\n metadata: Record<string, any>;\n}\n\n/** Session statistics - essential counters only */\nexport interface SessionStatistics {\n duration: number;\n iterations: number;\n toolCalls: number;\n errorCount: number;\n}\n\n/** Complete session state */\nexport interface Session {\n info: SessionInfo;\n context: { workingDirectory: string; config: JunoTaskConfig };\n statistics: SessionStatistics;\n history: SessionHistoryEntry[];\n result?: { success: boolean; output?: string; error?: string; finalState?: any };\n}\n\n/** History entry for conversation tracking */\nexport interface SessionHistoryEntry {\n id: string;\n timestamp: Date;\n type: 'prompt' | 'response' | 'tool_call' | 'error' | 'system';\n content: string;\n data?: any;\n duration?: number;\n iteration?: number;\n}\n\n/** Persistence layer abstraction */\nexport interface SessionStorage {\n saveSession(session: Session): Promise<void>;\n loadSession(sessionId: string): Promise<Session | null>;\n listSessions(filter?: SessionListFilter): Promise<SessionInfo[]>;\n removeSession(sessionId: string): Promise<void>;\n sessionExists(sessionId: string): Promise<boolean>;\n cleanup(options: CleanupOptions): Promise<void>;\n}\n\n/** Filter criteria for listing sessions */\nexport interface SessionListFilter {\n status?: SessionStatus[];\n subagent?: SubagentType[];\n dateRange?: { start?: Date; end?: Date };\n tags?: string[];\n limit?: number;\n offset?: number;\n sortBy?: 'createdAt' | 'updatedAt' | 'name';\n sortOrder?: 'asc' | 'desc';\n}\n\n/** Options for storage cleanup */\nexport interface CleanupOptions {\n removeEmpty?: boolean;\n removeOlderThanDays?: number;\n removeStatus?: SessionStatus[];\n dryRun?: boolean;\n}\n\n/** File-based session storage implementation */\nexport class FileSessionStorage implements SessionStorage {\n private readonly baseDir: string;\n private readonly sessionsDir: string;\n\n constructor(baseDir: string) {\n this.baseDir = path.resolve(baseDir);\n this.sessionsDir = path.join(this.baseDir, 'sessions');\n }\n\n async initialize(): Promise<void> {\n await fs.promises.mkdir(this.sessionsDir, { recursive: true });\n }\n\n private getSessionPath(sessionId: string): string {\n return path.join(this.sessionsDir, `${sessionId}.json`);\n }\n\n async saveSession(session: Session): Promise<void> {\n await this.initialize();\n const sessionPath = this.getSessionPath(session.info.id);\n const serializable = {\n ...session,\n info: {\n ...session.info,\n createdAt: session.info.createdAt.toISOString(),\n updatedAt: session.info.updatedAt.toISOString(),\n completedAt: session.info.completedAt?.toISOString(),\n },\n history: session.history.map((entry) => ({\n ...entry,\n timestamp: entry.timestamp.toISOString(),\n })),\n };\n await fs.promises.writeFile(sessionPath, JSON.stringify(serializable, null, 2), 'utf-8');\n }\n\n async loadSession(sessionId: string): Promise<Session | null> {\n const sessionPath = this.getSessionPath(sessionId);\n try {\n const data = await fs.promises.readFile(sessionPath, 'utf-8');\n const parsed = JSON.parse(data);\n return {\n ...parsed,\n info: {\n ...parsed.info,\n createdAt: new Date(parsed.info.createdAt),\n updatedAt: new Date(parsed.info.updatedAt),\n completedAt: parsed.info.completedAt ? new Date(parsed.info.completedAt) : undefined,\n },\n history: parsed.history.map((entry: any) => ({\n ...entry,\n timestamp: new Date(entry.timestamp),\n })),\n };\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;\n throw new Error(`Failed to load session ${sessionId}: ${error}`);\n }\n }\n\n async listSessions(filter?: SessionListFilter): Promise<SessionInfo[]> {\n await this.initialize();\n try {\n const files = await fs.promises.readdir(this.sessionsDir);\n const sessionFiles = files.filter((file) => file.endsWith('.json'));\n const sessions: SessionInfo[] = [];\n for (const file of sessionFiles) {\n try {\n const session = await this.loadSession(path.basename(file, '.json'));\n if (session) sessions.push(session.info);\n } catch (error) {\n console.warn(`Failed to load session from ${file}: ${error}`);\n }\n }\n\n let filtered = sessions;\n if (filter) {\n if (filter.status) filtered = filtered.filter((s) => filter.status!.includes(s.status));\n if (filter.subagent)\n filtered = filtered.filter((s) => filter.subagent!.includes(s.subagent));\n if (filter.dateRange) {\n if (filter.dateRange.start)\n filtered = filtered.filter((s) => s.createdAt >= filter.dateRange!.start!);\n if (filter.dateRange.end)\n filtered = filtered.filter((s) => s.createdAt <= filter.dateRange!.end!);\n }\n if (filter.tags && filter.tags.length > 0)\n filtered = filtered.filter((s) => filter.tags!.some((tag) => s.tags.includes(tag)));\n\n const sortBy = filter.sortBy || 'updatedAt';\n const sortOrder = filter.sortOrder || 'desc';\n filtered.sort((a, b) => {\n const aVal = a[sortBy],\n bVal = b[sortBy];\n if (aVal === undefined && bVal === undefined) return 0;\n if (aVal === undefined) return 1;\n if (bVal === undefined) return -1;\n if (aVal < bVal) return sortOrder === 'asc' ? -1 : 1;\n if (aVal > bVal) return sortOrder === 'asc' ? 1 : -1;\n return 0;\n });\n if (filter.offset) filtered = filtered.slice(filter.offset);\n if (filter.limit) filtered = filtered.slice(0, filter.limit);\n }\n return filtered;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [];\n throw error;\n }\n }\n\n async removeSession(sessionId: string): Promise<void> {\n try {\n await fs.promises.unlink(this.getSessionPath(sessionId));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT')\n throw new Error(`Failed to remove session ${sessionId}: ${error}`);\n }\n }\n\n async sessionExists(sessionId: string): Promise<boolean> {\n try {\n await fs.promises.access(this.getSessionPath(sessionId), fs.constants.F_OK);\n return true;\n } catch {\n return false;\n }\n }\n\n async cleanup(options: CleanupOptions): Promise<void> {\n await this.initialize();\n const files = await fs.promises.readdir(this.sessionsDir);\n const sessionFiles = files.filter((f) => f.endsWith('.json'));\n\n for (const file of sessionFiles) {\n const sessionId = path.basename(file, '.json');\n let shouldRemove = false;\n let session: Session | null = null;\n\n try {\n session = await this.loadSession(sessionId);\n } catch {\n // Corrupted/unreadable file — treat as removable when removeEmpty is set\n if (options.removeEmpty) shouldRemove = true;\n }\n\n if (session) {\n if (options.removeOlderThanDays) {\n const cutoff = new Date();\n cutoff.setDate(cutoff.getDate() - options.removeOlderThanDays);\n if (session.info.createdAt < cutoff) shouldRemove = true;\n }\n if (options.removeStatus && options.removeStatus.includes(session.info.status))\n shouldRemove = true;\n if (options.removeEmpty && session.history.length === 0 && !session.result)\n shouldRemove = true;\n }\n\n if (shouldRemove && !options.dryRun) await this.removeSession(sessionId);\n }\n }\n}\n\n/** Session manager - plain class for session lifecycle management */\nexport class SessionManager {\n private storage: SessionStorage;\n private activeSessions: Map<string, Session> = new Map();\n\n constructor(storage: SessionStorage) {\n this.storage = storage;\n }\n\n async createSession(options: {\n name?: string;\n subagent: SubagentType;\n config: JunoTaskConfig;\n tags?: string[];\n metadata?: Record<string, any>;\n }): Promise<Session> {\n const sessionId = uuidv4();\n const now = new Date();\n const session: Session = {\n info: {\n id: sessionId,\n ...(options.name !== undefined && { name: options.name }),\n status: 'running',\n subagent: options.subagent,\n createdAt: now,\n updatedAt: now,\n workingDirectory: options.config.workingDirectory,\n config: { ...options.config },\n tags: options.tags || [],\n metadata: options.metadata || {},\n },\n context: {\n workingDirectory: options.config.workingDirectory,\n config: { ...options.config },\n },\n statistics: { duration: 0, iterations: 0, toolCalls: 0, errorCount: 0 },\n history: [],\n };\n this.activeSessions.set(sessionId, session);\n await this.storage.saveSession(session);\n return session;\n }\n\n async updateSession(\n sessionId: string,\n updates: {\n status?: SessionStatus;\n name?: string;\n tags?: string[];\n metadata?: Record<string, any>;\n statistics?: Partial<SessionStatistics>;\n result?: Session['result'];\n },\n ): Promise<void> {\n let session = this.activeSessions.get(sessionId);\n if (!session) {\n const loaded = await this.storage.loadSession(sessionId);\n session = loaded || undefined;\n if (!session) throw new Error(`Session ${sessionId} not found`);\n }\n if (updates.status) session.info.status = updates.status;\n if (updates.name) session.info.name = updates.name;\n if (updates.tags) session.info.tags = updates.tags;\n if (updates.metadata) session.info.metadata = { ...session.info.metadata, ...updates.metadata };\n if (updates.statistics) session.statistics = { ...session.statistics, ...updates.statistics };\n if (updates.result) session.result = updates.result;\n session.info.updatedAt = new Date();\n this.activeSessions.set(sessionId, session);\n await this.storage.saveSession(session);\n }\n\n async completeSession(\n sessionId: string,\n result: {\n success: boolean;\n output?: string;\n error?: string;\n finalState?: any;\n },\n ): Promise<void> {\n const now = new Date();\n await this.updateSession(sessionId, {\n status: result.success ? 'completed' : 'failed',\n result,\n });\n const session = await this.getSession(sessionId);\n if (session) {\n session.info.completedAt = now;\n session.statistics.duration = now.getTime() - session.info.createdAt.getTime();\n await this.storage.saveSession(session);\n this.activeSessions.delete(sessionId);\n }\n }\n\n async cancelSession(sessionId: string): Promise<void> {\n await this.updateSession(sessionId, { status: 'cancelled' });\n this.activeSessions.delete(sessionId);\n }\n\n async getSession(sessionId: string): Promise<Session | null> {\n return this.activeSessions.get(sessionId) || (await this.storage.loadSession(sessionId));\n }\n\n async listSessions(filter?: SessionListFilter): Promise<SessionInfo[]> {\n return await this.storage.listSessions(filter);\n }\n\n async removeSession(sessionId: string): Promise<void> {\n await this.storage.removeSession(sessionId);\n this.activeSessions.delete(sessionId);\n }\n\n async cleanupSessions(options: CleanupOptions): Promise<void> {\n await this.storage.cleanup(options);\n }\n\n async addHistoryEntry(\n sessionId: string,\n entry: Omit<SessionHistoryEntry, 'id' | 'timestamp'>,\n ): Promise<void> {\n const session = await this.getSession(sessionId);\n if (!session) throw new Error(`Session ${sessionId} not found`);\n session.history.push({ id: uuidv4(), timestamp: new Date(), ...entry });\n await this.storage.saveSession(session);\n }\n\n async updateStatistics(sessionId: string, stats: Partial<SessionStatistics>): Promise<void> {\n await this.updateSession(sessionId, { statistics: stats });\n }\n\n async recordToolCall(\n sessionId: string,\n toolCall: {\n name: string;\n duration: number;\n success: boolean;\n },\n ): Promise<void> {\n const session = await this.getSession(sessionId);\n if (!session) return;\n session.statistics.toolCalls++;\n if (!toolCall.success) session.statistics.errorCount++;\n await this.storage.saveSession(session);\n }\n\n async getSessionContext(\n sessionId: string,\n options: {\n includeHistory?: boolean;\n includeStats?: boolean;\n maxHistoryEntries?: number;\n } = {},\n ): Promise<string> {\n const session = await this.getSession(sessionId);\n if (!session) return `Session ${sessionId}: Not found`;\n\n const lines = [\n `Session ${sessionId} Context:`,\n `Status: ${session.info.status}`,\n `Subagent: ${session.info.subagent}`,\n `Created: ${session.info.createdAt.toISOString()}`,\n `Working Directory: ${session.context.workingDirectory}`,\n ];\n if (session.info.tags.length > 0) lines.push(`Tags: ${session.info.tags.join(', ')}`);\n if (options.includeStats) {\n lines.push('', 'Statistics:');\n lines.push(` Iterations: ${session.statistics.iterations}`);\n lines.push(` Tool Calls: ${session.statistics.toolCalls}`);\n lines.push(` Duration: ${session.statistics.duration}ms`);\n }\n if (options.includeHistory && session.history?.length > 0) {\n lines.push('', 'Recent History:');\n const recent = session.history.slice(-(options.maxHistoryEntries || 5));\n for (const e of recent) {\n const time = e.timestamp?.toISOString()?.split('T')[1]?.split('.')[0] || 'unknown';\n lines.push(` [${time}] ${e.type}: ${e.content.substring(0, 100)}...`);\n }\n }\n return lines.join('\\n');\n }\n\n async getSessionSummary(sessionId: string): Promise<{\n info: SessionInfo;\n statistics: SessionStatistics;\n summary: {\n totalDuration: string;\n iterationsPerMinute: number;\n toolCallsPerIteration: number;\n errorRate: number;\n };\n } | null> {\n const session = await this.getSession(sessionId);\n if (!session) return null;\n const mins = session.statistics.duration / 60_000;\n const ipm = mins > 0 ? session.statistics.iterations / mins : 0;\n const tcpi =\n session.statistics.iterations > 0\n ? session.statistics.toolCalls / session.statistics.iterations\n : 0;\n const er =\n session.statistics.toolCalls > 0\n ? session.statistics.errorCount / session.statistics.toolCalls\n : 0;\n return {\n info: session.info,\n statistics: session.statistics,\n summary: {\n totalDuration: this.formatDuration(session.statistics.duration),\n iterationsPerMinute: Number(ipm.toFixed(2)),\n toolCallsPerIteration: Number(tcpi.toFixed(2)),\n errorRate: Number(er.toFixed(3)),\n },\n };\n }\n\n private formatDuration(ms: number): string {\n const s = Math.floor(ms / 1000);\n const m = Math.floor(s / 60);\n const h = Math.floor(m / 60);\n if (h > 0) return `${h}h ${m % 60}m ${s % 60}s`;\n if (m > 0) return `${m}m ${s % 60}s`;\n return `${s}s`;\n }\n}\n\n/** Create a session manager with file storage */\nexport async function createSessionManager(config: JunoTaskConfig): Promise<SessionManager> {\n const storage = new FileSessionStorage(config.sessionDirectory);\n await storage.initialize();\n return new SessionManager(storage);\n}\n","/**\n * Environment Utilities Module for juno-task-ts\n *\n * Provides comprehensive environment variable handling and detection utilities\n * for the juno-task-ts CLI tool. This module includes environment detection,\n * terminal capabilities, platform information, configuration directories,\n * and MCP server path detection.\n *\n * @module utils/environment\n */\n\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport * as process from 'node:process';\nimport { promises as fs } from 'node:fs';\n// Conditional import for execSync to improve tree shaking\n// import { execSync } from 'node:child_process';\n\n// ============================================================================\n// Types and Interfaces\n// ============================================================================\n\n/**\n * Color support levels for terminal output\n */\nexport type ColorSupport = 'none' | 'basic' | '256' | 'truecolor';\n\n/**\n * Node.js environment types\n */\nexport type NodeEnvironment = 'development' | 'production' | 'test';\n\n/**\n * Operating system platforms\n */\nexport type Platform = 'win32' | 'darwin' | 'linux' | 'freebsd' | 'openbsd' | 'sunos' | 'aix';\n\n/**\n * System architectures\n */\nexport type Architecture =\n | 'arm'\n | 'arm64'\n | 'ia32'\n | 'mips'\n | 'mipsel'\n | 'ppc'\n | 'ppc64'\n | 's390'\n | 's390x'\n | 'x64';\n\n/**\n * Shell types\n */\nexport type ShellType = 'bash' | 'zsh' | 'fish' | 'cmd' | 'powershell' | 'unknown';\n\n/**\n * Process information interface\n */\nexport interface ProcessInfo {\n pid: number;\n ppid: number;\n platform: Platform;\n arch: Architecture;\n nodeVersion: string;\n uptime: number;\n cwd: string;\n execPath: string;\n argv: string[];\n env: Record<string, string | undefined>;\n}\n\n/**\n * Memory usage information\n */\nexport interface MemoryUsage {\n rss: number;\n heapTotal: number;\n heapUsed: number;\n external: number;\n arrayBuffers: number;\n}\n\n/**\n * CPU usage information\n */\nexport interface CpuUsage {\n user: number;\n system: number;\n}\n\n/**\n * MCP server environment configuration\n */\nexport interface MCPServerEnvironment {\n PATH: string;\n NODE_ENV: string;\n [key: string]: string;\n}\n\n// ============================================================================\n// Environment Detection\n// ============================================================================\n\n/**\n * Detect if running in a headless/CI environment where interactive prompts should be avoided.\n * Based on the Python implementation patterns from budi-cli.\n *\n * @returns True if running in headless/CI environment\n *\n * @example\n * ```typescript\n * if (isHeadlessEnvironment()) {\n * console.log('Using non-interactive mode');\n * }\n * ```\n */\nexport function isHeadlessEnvironment(): boolean {\n // Check for CI environment indicators (matches Python implementation)\n const ciIndicators = [\n 'CI',\n 'CONTINUOUS_INTEGRATION',\n 'GITHUB_ACTIONS',\n 'GITLAB_CI',\n 'JENKINS_URL',\n 'TRAVIS',\n 'CIRCLECI',\n 'PYTEST_CURRENT_TEST', // Pytest test runner\n 'JUNO_TASK_HEADLESS', // Our custom flag for headless testing\n 'NODE_ENV', // Additional Node.js specific\n ];\n\n for (const indicator of ciIndicators) {\n if (process.env[indicator]) {\n return true;\n }\n }\n\n // Check if stdin/stdout are connected to a terminal\n if (!process.stdin.isTTY || !process.stdout.isTTY) {\n return true;\n }\n\n return false;\n}\n\n/**\n * Detect if running in a continuous integration environment.\n *\n * @returns True if running in CI environment\n *\n * @example\n * ```typescript\n * if (isCIEnvironment()) {\n * console.log('Running in CI environment');\n * }\n * ```\n */\nexport function isCIEnvironment(): boolean {\n const ciIndicators = [\n 'CI',\n 'CONTINUOUS_INTEGRATION',\n 'GITHUB_ACTIONS',\n 'GITLAB_CI',\n 'JENKINS_URL',\n 'TRAVIS',\n 'CIRCLECI',\n 'BUILDKITE',\n 'AZURE_PIPELINES',\n 'TEAMCITY_VERSION',\n ];\n\n return ciIndicators.some((indicator) => Boolean(process.env[indicator]));\n}\n\n/**\n * Check if terminal supports interactive input/output.\n *\n * @returns True if terminal supports interaction\n *\n * @example\n * ```typescript\n * if (isInteractiveTerminal()) {\n * // Show interactive prompts\n * }\n * ```\n */\nexport function isInteractiveTerminal(): boolean {\n return Boolean(process.stdin.isTTY && process.stdout.isTTY && !isHeadlessEnvironment());\n}\n\n/**\n * Detect if running in development mode.\n *\n * @returns True if in development mode\n *\n * @example\n * ```typescript\n * if (isDevelopmentMode()) {\n * console.log('Debug logging enabled');\n * }\n * ```\n */\nexport function isDevelopmentMode(): boolean {\n const nodeEnv = getNodeEnvironment();\n return nodeEnv === 'development' || Boolean(process.env.DEBUG);\n}\n\n/**\n * Get Node.js environment type.\n *\n * @returns The Node.js environment type\n *\n * @example\n * ```typescript\n * const env = getNodeEnvironment();\n * console.log(`Running in ${env} mode`);\n * ```\n */\nexport function getNodeEnvironment(): NodeEnvironment {\n const env = process.env.NODE_ENV?.toLowerCase();\n\n if (env === 'production') return 'production';\n if (env === 'test') return 'test';\n return 'development';\n}\n\n// ============================================================================\n// Environment Variable Utilities\n// ============================================================================\n\n/**\n * Get environment variable with optional type conversion.\n *\n * @param key - Environment variable name\n * @param defaultValue - Default value if variable is not set\n * @returns Environment variable value or default\n *\n * @example\n * ```typescript\n * const port = getEnvVar('PORT', '3000');\n * const timeout = getEnvVar('TIMEOUT', '30');\n * ```\n */\nexport function getEnvVar(key: string, defaultValue?: string): string | undefined {\n return process.env[key] ?? defaultValue;\n}\n\n/**\n * Get environment variable with fallback value.\n *\n * @param key - Environment variable name\n * @param defaultValue - Default value if variable is not set\n * @returns Environment variable value or default\n *\n * @example\n * ```typescript\n * const logLevel = getEnvVarWithDefault('LOG_LEVEL', 'info');\n * ```\n */\nexport function getEnvVarWithDefault(key: string, defaultValue: string): string {\n return process.env[key] ?? defaultValue;\n}\n\n/**\n * Set environment variable safely.\n *\n * @param key - Environment variable name\n * @param value - Value to set\n *\n * @example\n * ```typescript\n * setEnvVar('DEBUG', 'true');\n * ```\n */\nexport function setEnvVar(key: string, value: string): void {\n process.env[key] = value;\n}\n\n/**\n * Parse boolean value from environment variable string.\n *\n * @param value - Environment variable value\n * @param defaultValue - Default boolean value\n * @returns Parsed boolean value\n *\n * @example\n * ```typescript\n * const isVerbose = parseEnvBoolean(process.env.VERBOSE, false);\n * const isEnabled = parseEnvBoolean('true'); // returns true\n * ```\n */\nexport function parseEnvBoolean(value: string | undefined, defaultValue: boolean = false): boolean {\n if (!value) return defaultValue;\n\n const normalized = value.toLowerCase().trim();\n return ['true', '1', 'yes', 'on', 'enabled'].includes(normalized);\n}\n\n/**\n * Parse number value from environment variable string.\n *\n * @param value - Environment variable value\n * @param defaultValue - Default number value\n * @returns Parsed number value\n *\n * @example\n * ```typescript\n * const port = parseEnvNumber(process.env.PORT, 3000);\n * const timeout = parseEnvNumber('30'); // returns 30\n * ```\n */\nexport function parseEnvNumber(value: string | undefined, defaultValue: number = 0): number {\n if (!value) return defaultValue;\n\n const parsed = Number(value);\n return isNaN(parsed) ? defaultValue : parsed;\n}\n\n/**\n * Parse array from delimited environment variable string.\n *\n * @param value - Environment variable value\n * @param delimiter - Delimiter to split on\n * @param defaultValue - Default array value\n * @returns Parsed array\n *\n * @example\n * ```typescript\n * const paths = parseEnvArray(process.env.SEARCH_PATHS, ':', []);\n * const hosts = parseEnvArray('host1,host2,host3', ','); // returns ['host1', 'host2', 'host3']\n * ```\n */\nexport function parseEnvArray(\n value: string | undefined,\n delimiter: string = ',',\n defaultValue: string[] = [],\n): string[] {\n if (!value) return defaultValue;\n\n return value\n .split(delimiter)\n .map((item) => item.trim())\n .filter(Boolean);\n}\n\n// ============================================================================\n// Terminal Detection\n// ============================================================================\n\n/**\n * Get terminal width for formatting output.\n *\n * @returns Terminal width in columns\n *\n * @example\n * ```typescript\n * const width = getTerminalWidth();\n * console.log(`Terminal width: ${width} columns`);\n * ```\n */\nexport function getTerminalWidth(): number {\n return process.stdout.columns || 80;\n}\n\n/**\n * Get terminal height for formatting output.\n *\n * @returns Terminal height in rows\n *\n * @example\n * ```typescript\n * const height = getTerminalHeight();\n * console.log(`Terminal height: ${height} rows`);\n * ```\n */\nexport function getTerminalHeight(): number {\n return process.stdout.rows || 24;\n}\n\n/**\n * Check if terminal supports color output.\n *\n * @returns True if terminal supports colors\n *\n * @example\n * ```typescript\n * if (supportsColor()) {\n * console.log('\\x1b[32mGreen text\\x1b[0m');\n * }\n * ```\n */\nexport function supportsColor(): boolean {\n // Check for explicit color support flags\n if (process.env.FORCE_COLOR) {\n return true;\n }\n\n if (process.env.NO_COLOR || process.env.NODE_DISABLE_COLORS) {\n return false;\n }\n\n // Check if we're in a TTY\n if (!process.stdout.isTTY) {\n return false;\n }\n\n // Check TERM environment variable\n const term = process.env.TERM;\n if (!term || term === 'dumb') {\n return false;\n }\n\n // Check for common color-supporting terminals\n const colorTerms = ['color', 'ansi', 'truecolor', '256color', 'xterm'];\n return colorTerms.some((colorTerm) => term.includes(colorTerm));\n}\n\n/**\n * Get color capability level of the terminal.\n *\n * @returns Color support level\n *\n * @example\n * ```typescript\n * const colorSupport = getColorSupport();\n * if (colorSupport === 'truecolor') {\n * // Use RGB colors\n * }\n * ```\n */\nexport function getColorSupport(): ColorSupport {\n if (!supportsColor()) {\n return 'none';\n }\n\n const term = process.env.TERM || '';\n const colorTerm = process.env.COLORTERM || '';\n\n // Check for truecolor support\n if (colorTerm === 'truecolor' || term.includes('truecolor')) {\n return 'truecolor';\n }\n\n // Check for 256 color support\n if (term.includes('256') || term.includes('256color')) {\n return '256';\n }\n\n // Default to basic color support\n return 'basic';\n}\n\n/**\n * Detect if running inside a Docker container.\n *\n * @returns True if running in Docker\n *\n * @example\n * ```typescript\n * if (isInDocker()) {\n * console.log('Running in Docker container');\n * }\n * ```\n */\nexport function isInDocker(): boolean {\n try {\n // Check for .dockerenv file\n require('node:fs').accessSync('/.dockerenv');\n return true;\n } catch {\n // Check cgroup for docker\n try {\n const cgroup = require('node:fs').readFileSync('/proc/1/cgroup', 'utf8');\n return cgroup.includes('docker') || cgroup.includes('containerd');\n } catch {\n return false;\n }\n }\n}\n\n// ============================================================================\n// Platform Detection\n// ============================================================================\n\n/**\n * Get operating system platform information.\n *\n * @returns Platform information\n *\n * @example\n * ```typescript\n * const platform = getPlatform();\n * console.log(`Running on ${platform}`);\n * ```\n */\nexport function getPlatform(): Platform {\n return os.platform() as Platform;\n}\n\n/**\n * Get system architecture information.\n *\n * @returns System architecture\n *\n * @example\n * ```typescript\n * const arch = getArchitecture();\n * console.log(`System architecture: ${arch}`);\n * ```\n */\nexport function getArchitecture(): Architecture {\n return os.arch() as Architecture;\n}\n\n/**\n * Detect user's shell (bash, zsh, fish, etc.).\n *\n * @returns Detected shell type\n *\n * @example\n * ```typescript\n * const shell = getShell();\n * console.log(`User shell: ${shell}`);\n * ```\n */\nexport function getShell(): ShellType {\n const shell = process.env.SHELL || process.env.ComSpec || '';\n const shellName = path.basename(shell).toLowerCase();\n\n if (shellName.includes('bash')) return 'bash';\n if (shellName.includes('zsh')) return 'zsh';\n if (shellName.includes('fish')) return 'fish';\n if (shellName.includes('cmd')) return 'cmd';\n if (shellName.includes('powershell') || shellName.includes('pwsh')) return 'powershell';\n\n return 'unknown';\n}\n\n/**\n * Get user home directory path.\n *\n * @returns User home directory path\n *\n * @example\n * ```typescript\n * const home = getHomeDirectory();\n * console.log(`Home directory: ${home}`);\n * ```\n */\nexport function getHomeDirectory(): string {\n return os.homedir();\n}\n\n/**\n * Get system temporary directory path.\n *\n * @returns System temp directory path\n *\n * @example\n * ```typescript\n * const temp = getTempDirectory();\n * console.log(`Temp directory: ${temp}`);\n * ```\n */\nexport function getTempDirectory(): string {\n return os.tmpdir();\n}\n\n// ============================================================================\n// Configuration Directories\n// ============================================================================\n\n/**\n * Get user configuration directory path.\n * Follows XDG Base Directory specification on Unix systems.\n *\n * @param appName - Application name for subdirectory\n * @returns Configuration directory path\n *\n * @example\n * ```typescript\n * const configDir = getConfigDirectory('juno-task');\n * // Returns: ~/.config/juno-task (Linux), ~/Library/Application Support/juno-task (macOS), etc.\n * ```\n */\nexport function getConfigDirectory(appName: string = 'juno-task'): string {\n const platform = getPlatform();\n const home = getHomeDirectory();\n\n switch (platform) {\n case 'win32':\n return path.join(process.env.APPDATA || path.join(home, 'AppData', 'Roaming'), appName);\n case 'darwin':\n return path.join(home, 'Library', 'Application Support', appName);\n default:\n return path.join(process.env.XDG_CONFIG_HOME || path.join(home, '.config'), appName);\n }\n}\n\n/**\n * Get user data directory path.\n *\n * @param appName - Application name for subdirectory\n * @returns Data directory path\n *\n * @example\n * ```typescript\n * const dataDir = getDataDirectory('juno-task');\n * ```\n */\nexport function getDataDirectory(appName: string = 'juno-task'): string {\n const platform = getPlatform();\n const home = getHomeDirectory();\n\n switch (platform) {\n case 'win32':\n return path.join(process.env.LOCALAPPDATA || path.join(home, 'AppData', 'Local'), appName);\n case 'darwin':\n return path.join(home, 'Library', 'Application Support', appName);\n default:\n return path.join(process.env.XDG_DATA_HOME || path.join(home, '.local', 'share'), appName);\n }\n}\n\n/**\n * Get user cache directory path.\n *\n * @param appName - Application name for subdirectory\n * @returns Cache directory path\n *\n * @example\n * ```typescript\n * const cacheDir = getCacheDirectory('juno-task');\n * ```\n */\nexport function getCacheDirectory(appName: string = 'juno-task'): string {\n const platform = getPlatform();\n const home = getHomeDirectory();\n\n switch (platform) {\n case 'win32':\n return path.join(process.env.TEMP || path.join(home, 'AppData', 'Local', 'Temp'), appName);\n case 'darwin':\n return path.join(home, 'Library', 'Caches', appName);\n default:\n return path.join(process.env.XDG_CACHE_HOME || path.join(home, '.cache'), appName);\n }\n}\n\n/**\n * Create directory if it doesn't exist.\n *\n * @param dirPath - Directory path to create\n * @returns Promise that resolves when directory is created\n *\n * @example\n * ```typescript\n * await createDirectoryIfNotExists('/path/to/config');\n * ```\n */\nexport async function createDirectoryIfNotExists(dirPath: string): Promise<void> {\n try {\n await fs.mkdir(dirPath, { recursive: true });\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') {\n throw error;\n }\n }\n}\n\n// ============================================================================\n// Process Information\n// ============================================================================\n\n/**\n * Get current process information.\n *\n * @returns Process information object\n *\n * @example\n * ```typescript\n * const info = getProcessInfo();\n * console.log(`Process ID: ${info.pid}`);\n * ```\n */\nexport function getProcessInfo(): ProcessInfo {\n return {\n pid: process.pid,\n ppid: process.ppid || 0,\n platform: getPlatform(),\n arch: getArchitecture(),\n nodeVersion: process.version,\n uptime: process.uptime(),\n cwd: process.cwd(),\n execPath: process.execPath,\n argv: process.argv,\n env: process.env as Record<string, string | undefined>,\n };\n}\n\n/**\n * Check if running with root/administrator privileges.\n *\n * @returns True if running as root\n *\n * @example\n * ```typescript\n * if (isRunningAsRoot()) {\n * console.warn('Running with elevated privileges');\n * }\n * ```\n */\nexport function isRunningAsRoot(): boolean {\n const platform = getPlatform();\n\n if (platform === 'win32') {\n // On Windows, check if user is in Administrators group\n try {\n // Dynamic import to improve tree shaking\n const { execSync } = require('node:child_process');\n execSync('net session', { stdio: 'ignore' });\n return true;\n } catch {\n return false;\n }\n } else {\n // On Unix-like systems, check UID\n return process.getuid?.() === 0;\n }\n}\n\n/**\n * Get process memory usage information.\n *\n * @returns Memory usage information\n *\n * @example\n * ```typescript\n * const memory = getMemoryUsage();\n * console.log(`Heap used: ${(memory.heapUsed / 1024 / 1024).toFixed(2)} MB`);\n * ```\n */\nexport function getMemoryUsage(): MemoryUsage {\n return process.memoryUsage();\n}\n\n/**\n * Get CPU usage information.\n *\n * @returns CPU usage information\n *\n * @example\n * ```typescript\n * const cpu = getCpuUsage();\n * console.log(`User CPU time: ${cpu.user}μs`);\n * ```\n */\nexport function getCpuUsage(): CpuUsage {\n return process.cpuUsage();\n}\n\n// ============================================================================\n// MCP Server Path Detection\n// ============================================================================\n\n/**\n * Auto-discover MCP server location.\n * Searches common installation paths and PATH environment variable.\n *\n * @param serverName - MCP server executable name\n * @returns Promise that resolves to server path or null if not found\n *\n * @example\n * ```typescript\n * const serverPath = await findMCPServerPath('mcp-server');\n * if (serverPath) {\n * console.log(`Found MCP server at: ${serverPath}`);\n * }\n * ```\n */\nexport async function findMCPServerPath(serverName: string = 'mcp-server'): Promise<string | null> {\n const platform = getPlatform();\n const searchPaths: string[] = [];\n\n // Add PATH directories\n const pathEnv = process.env.PATH || '';\n searchPaths.push(...pathEnv.split(path.delimiter));\n\n // Add platform-specific common paths\n if (platform === 'win32') {\n searchPaths.push(\n 'C:\\\\Program Files\\\\MCP\\\\bin',\n 'C:\\\\Program Files (x86)\\\\MCP\\\\bin',\n path.join(process.env.LOCALAPPDATA || '', 'Programs', 'MCP', 'bin'),\n );\n } else {\n searchPaths.push(\n '/usr/local/bin',\n '/usr/bin',\n '/opt/mcp/bin',\n path.join(getHomeDirectory(), '.local', 'bin'),\n path.join(getHomeDirectory(), 'bin'),\n );\n }\n\n // Add executable extension on Windows\n const executable = platform === 'win32' ? `${serverName}.exe` : serverName;\n\n // Search for the executable\n for (const searchPath of searchPaths) {\n if (!searchPath) continue;\n\n const fullPath = path.join(searchPath, executable);\n try {\n await fs.access(fullPath, fs.constants.F_OK | fs.constants.X_OK);\n return fullPath;\n } catch {\n // Continue searching\n }\n }\n\n return null;\n}\n\n/**\n * Verify MCP server path is executable.\n *\n * @param serverPath - Path to MCP server executable\n * @returns Promise that resolves to true if valid and executable\n *\n * @example\n * ```typescript\n * const isValid = await validateMCPServerPath('/usr/local/bin/mcp-server');\n * if (isValid) {\n * console.log('MCP server is valid and executable');\n * }\n * ```\n */\nexport async function validateMCPServerPath(serverPath: string): Promise<boolean> {\n try {\n const stats = await fs.stat(serverPath);\n if (!stats.isFile()) {\n return false;\n }\n\n // Check if file is executable\n await fs.access(serverPath, fs.constants.X_OK);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Get environment configuration for MCP server.\n *\n * @param additionalEnv - Additional environment variables\n * @returns MCP server environment configuration\n *\n * @example\n * ```typescript\n * const env = getMCPServerEnvironment({ DEBUG: 'true' });\n * console.log('MCP server environment:', env);\n * ```\n */\nexport function getMCPServerEnvironment(\n additionalEnv: Record<string, string> = {},\n): MCPServerEnvironment {\n const baseEnv = {\n PATH: process.env.PATH || '',\n NODE_ENV: getNodeEnvironment(),\n HOME: getHomeDirectory(),\n TMPDIR: getTempDirectory(),\n };\n\n return {\n ...baseEnv,\n ...additionalEnv,\n };\n}\n","/**\n * Validation Utilities Module for juno-code\n *\n * Provides Zod-based validation for configuration values.\n *\n * @module utils/validation\n */\n\nimport { z } from 'zod';\nimport type { SubagentType, LogLevel, JunoTaskConfig } from '../types/index';\nimport { JunoTaskConfigSchema, validateConfig as coreValidateConfig } from '../core/config';\nimport { SUBAGENT_ALIASES } from '../cli/types';\n\n// ============================================================================\n// Zod Schemas\n// ============================================================================\n\n/**\n * Schema for validating subagent types with alias support\n */\nexport const SubagentSchema = z\n .string()\n .transform((value) => {\n if (['claude', 'cursor', 'codex', 'gemini', 'pi'].includes(value)) {\n return value as SubagentType;\n }\n\n const normalized = SUBAGENT_ALIASES[value];\n if (normalized) {\n return normalized;\n }\n\n throw new z.ZodError([\n {\n code: z.ZodIssueCode.invalid_enum_value,\n options: ['claude', 'cursor', 'codex', 'gemini', 'pi'],\n received: value,\n path: [],\n message: `Invalid subagent: ${value}. Valid options: claude, cursor, codex, gemini, pi`,\n },\n ]);\n })\n .refine(\n (value): value is SubagentType => ['claude', 'cursor', 'codex', 'gemini', 'pi'].includes(value),\n {\n message: 'Invalid subagent type',\n },\n );\n\n/**\n * Schema for validating log levels\n */\nexport const LogLevelSchema = z.enum(['error', 'warn', 'info', 'debug', 'trace'], {\n errorMap: (_issue, ctx) => ({\n message: `Invalid log level: ${ctx.data}. Valid options: error, warn, info, debug, trace`,\n }),\n});\n\n/**\n * Schema for validating session status\n */\nexport const SessionStatusSchema = z.enum(['running', 'completed', 'failed', 'cancelled'], {\n errorMap: (_issue, ctx) => ({\n message: `Invalid session status: ${ctx.data}. Valid options: running, completed, failed, cancelled`,\n }),\n});\n\n/**\n * Schema for validating iteration counts\n */\nexport const IterationsSchema = z\n .number()\n .int('Iterations must be an integer')\n .refine(\n (value) => value === -1 || value > 0,\n 'Iterations must be a positive integer or -1 for infinite',\n )\n .transform((value) => (value === -1 ? Infinity : value));\n\n/**\n * Schema for validating model names (subagent-specific)\n */\nexport const ModelSchema = z\n .string()\n .min(1, 'Model name cannot be empty')\n .refine((model) => {\n return /^[a-zA-Z0-9._-]+$/.test(model);\n }, 'Model name contains invalid characters');\n\n/**\n * Schema for runtime configuration validation\n */\nexport const ConfigValidationSchema = JunoTaskConfigSchema;\n\n// ============================================================================\n// Core Validation Functions\n// ============================================================================\n\n/**\n * Validate and normalize subagent names including aliases\n */\nexport function validateSubagent(subagent: string): SubagentType {\n return SubagentSchema.parse(subagent);\n}\n\n/**\n * Validate model names for specific subagents\n */\nexport function validateModel(model: string, _subagent?: SubagentType): string {\n return ModelSchema.parse(model);\n}\n\n/**\n * Validate iteration counts (positive integers or -1 for infinite)\n */\nexport function validateIterations(iterations: number): number {\n return IterationsSchema.parse(iterations);\n}\n\n/**\n * Validate log level strings\n */\nexport function validateLogLevel(logLevel: string): LogLevel {\n return LogLevelSchema.parse(logLevel);\n}\n\n// ============================================================================\n// Configuration Validation\n// ============================================================================\n\n/**\n * Complete configuration validation\n * Delegates to the core config validation.\n */\nexport function validateConfig(config: unknown): JunoTaskConfig {\n return coreValidateConfig(config);\n}\n\n/**\n * Environment variable validation\n */\nexport function validateEnvironmentVars(\n envVars: Record<string, string | undefined>,\n): Partial<JunoTaskConfig> {\n const config: Partial<JunoTaskConfig> = {};\n const errors: string[] = [];\n\n Object.entries(envVars).forEach(([key, value]) => {\n if (!key.startsWith('JUNO_TASK_') || value === undefined) {\n return;\n }\n\n try {\n switch (key) {\n case 'JUNO_TASK_DEFAULT_SUBAGENT':\n config.defaultSubagent = validateSubagent(value);\n break;\n case 'JUNO_TASK_LOG_LEVEL':\n config.logLevel = validateLogLevel(value);\n break;\n case 'JUNO_TASK_DEFAULT_MAX_ITERATIONS':\n config.defaultMaxIterations = validateIterations(parseInt(value, 10));\n break;\n case 'JUNO_TASK_VERBOSE':\n config.verbose = value.toLowerCase() === 'true';\n break;\n case 'JUNO_TASK_QUIET':\n config.quiet = value.toLowerCase() === 'true';\n break;\n case 'JUNO_TASK_INTERACTIVE':\n config.interactive = value.toLowerCase() === 'true';\n break;\n case 'JUNO_TASK_HEADLESS_MODE':\n config.headlessMode = value.toLowerCase() === 'true';\n break;\n }\n } catch (error) {\n if (error instanceof Error) {\n errors.push(`${key}: ${error.message}`);\n }\n }\n });\n\n if (errors.length > 0) {\n throw new Error(`Environment variable validation failed:\\n${errors.join('\\n')}`);\n }\n\n return config;\n}\n\n// ============================================================================\n// Type Re-exports\n// ============================================================================\n\nexport type { SubagentType, SessionStatus, LogLevel, JunoTaskConfig } from '../types/index';\n","/**\n * CLI Types Module for juno-code\n *\n * TypeScript interfaces and types for the CLI framework,\n * supporting commands, options, error handling, and constants.\n */\n\nimport type { SubagentType, SessionStatus, LogLevel, BackendType } from '../types/index';\n\n// ============================================================================\n// Command Structure Types\n// ============================================================================\n\n/**\n * Interface for usage examples\n */\nexport interface CommandExample {\n /** Full command example */\n command: string;\n /** Description of what the example does */\n description: string;\n}\n\n// ============================================================================\n// CLI Options Types\n// ============================================================================\n\n/**\n * Global CLI options available to all commands\n */\nexport interface GlobalCLIOptions {\n /** Enable verbose output with detailed progress */\n verbose?: boolean;\n /** Disable rich formatting, use plain text */\n quiet?: boolean;\n /** Configuration file path (.json, .toml, pyproject.toml) */\n config?: string;\n /** Log file path (auto-generated if not specified) */\n logFile?: string;\n /** Disable colored output */\n noColor?: boolean;\n /** Log level for output */\n logLevel?: LogLevel;\n /** Enable concurrent feedback collection during execution */\n enableFeedback?: boolean;\n /** Behavior when Claude hourly quota limit is reached: \"wait\" to sleep until reset, \"raise\" to exit immediately */\n onHourlyLimit?: 'wait' | 'raise';\n /** Skip execution of all lifecycle hooks */\n hooks?: boolean;\n}\n\n/**\n * Main execution command options\n */\nexport interface MainCommandOptions extends GlobalCLIOptions {\n /** Subagent to use (required) */\n subagent: SubagentType;\n /** Prompt input (file path or inline text) */\n prompt?: string;\n /** Prompt file path (alternative to -p \"$(cat file)\") */\n promptFile?: string;\n /** Working directory */\n cwd?: string;\n /** Maximum iterations (-1 for unlimited) */\n maxIterations?: number;\n /** Model to use (subagent-specific) */\n model?: string;\n /** Agents configuration (forwarded to shell backend --agents flag) */\n agents?: string;\n /** Available tools from built-in set (only works with --print mode, forwarded to shell backend --tools flag) */\n tools?: string[];\n /** Permission-based filtering of specific tool instances (forwarded to shell backend --allowedTools flag) */\n allowedTools?: string[];\n /** Disallowed tools for Claude (forwarded to shell backend --disallowed-tool flag) */\n disallowedTools?: string[];\n /** Append tools to default allowed-tools list (mutually exclusive with --allowed-tools, forwarded to shell backend --appendAllowedTools flag) */\n appendAllowedTools?: string[];\n /** Backend type (shell) */\n backend?: 'shell';\n /** Interactive mode for typing prompts */\n interactive?: boolean;\n /** Launch interactive prompt editor */\n interactivePrompt?: boolean;\n /** Resume a conversation by session ID (shell backend only) */\n resume?: string;\n /** Continue the most recent conversation (shell backend only) */\n continue?: boolean;\n}\n\n/**\n * Init command options\n */\nexport interface InitCommandOptions extends GlobalCLIOptions {\n /** Target directory */\n directory?: string;\n /** Force overwrite existing files */\n force?: boolean;\n /** Main task description */\n task?: string;\n /** Preferred subagent */\n subagent?: SubagentType;\n /** Repository URL */\n gitUrl?: string;\n /** Force interactive mode for guided setup */\n interactive?: boolean;\n /** Template variant to use */\n template?: string;\n /** Custom template variables */\n variables?: Record<string, string>;\n}\n\n/**\n * Start command options\n */\nexport interface StartCommandOptions extends GlobalCLIOptions {\n /** Subagent to use (optional override of config default) */\n subagent?: SubagentType;\n /** Backend type (shell) */\n backend?: BackendType;\n /** Maximum iterations */\n maxIterations?: number;\n /** Model to use */\n model?: string;\n /** Agents configuration (forwarded to shell backend --agents flag) */\n agents?: string;\n /** Available tools from built-in set (only works with --print mode, forwarded to shell backend --tools flag) */\n tools?: string[];\n /** Permission-based filtering of specific tool instances (forwarded to shell backend --allowedTools flag) */\n allowedTools?: string[];\n /** Disallowed tools for Claude (forwarded to shell backend --disallowed-tool flag) */\n disallowedTools?: string[];\n /** Append tools to default allowed-tools list (mutually exclusive with --allowed-tools, forwarded to shell backend --appendAllowedTools flag) */\n appendAllowedTools?: string[];\n /** Resume a conversation by session ID (shell backend only) */\n resume?: string;\n /** Continue the most recent conversation (shell backend only) */\n continue?: boolean;\n /** Project directory */\n directory?: string;\n /** Display performance metrics summary after execution */\n showMetrics?: boolean;\n /** Show interactive performance dashboard after execution */\n showDashboard?: boolean;\n /** Display performance trends from historical data */\n showTrends?: boolean;\n /** Save performance metrics to file */\n saveMetrics?: boolean | string;\n /** Custom path for metrics file */\n metricsFile?: string;\n /** Enable concurrent feedback collection during execution */\n enableFeedback?: boolean;\n /** Validate configuration and exit without executing */\n dryRun?: boolean;\n}\n\n/**\n * Feedback command options\n */\nexport interface FeedbackCommandOptions extends GlobalCLIOptions {\n /** Custom USER_FEEDBACK.md file path */\n file?: string;\n /** Interactive multiline input */\n interactive?: boolean;\n /** Issue description */\n issue?: string;\n /** Test criteria or success factors */\n test?: string;\n /** Test criteria alias */\n testCriteria?: string;\n}\n\n/**\n * Session list command options\n */\nexport interface SessionListOptions extends GlobalCLIOptions {\n /** Maximum sessions to show */\n limit?: number;\n /** Filter by subagent */\n subagent?: SubagentType;\n /** Filter by status */\n status?: SessionStatus[];\n}\n\n/**\n * Session info command options\n */\nexport interface SessionInfoOptions extends GlobalCLIOptions {\n /** Show detailed information */\n verbose?: boolean;\n}\n\n/**\n * Session remove command options\n */\nexport interface SessionRemoveOptions extends GlobalCLIOptions {\n /** Skip confirmation prompt */\n force?: boolean;\n}\n\n/**\n * Session clean command options\n */\nexport interface SessionCleanOptions extends GlobalCLIOptions {\n /** Remove sessions older than N days */\n days?: number;\n /** Remove only empty log files */\n empty?: boolean;\n /** Skip confirmation prompt */\n force?: boolean;\n}\n\n/**\n * Setup-git command options\n */\nexport interface SetupGitOptions extends GlobalCLIOptions {\n /** Show current upstream URL configuration */\n show?: boolean;\n /** Remove upstream URL configuration */\n remove?: boolean;\n}\n\n/**\n * Test command options\n */\nexport interface TestCommandOptions extends GlobalCLIOptions {\n /** Test type to generate/run */\n type?: 'unit' | 'integration' | 'e2e' | 'performance' | 'all';\n /** AI subagent for test generation */\n subagent?: SubagentType;\n /** AI intelligence level */\n intelligence?: 'basic' | 'smart' | 'comprehensive';\n /** Generate tests using AI */\n generate?: boolean;\n /** Execute tests */\n run?: boolean;\n /** Generate coverage report */\n coverage?: boolean | string;\n /** Analyze test quality and coverage */\n analyze?: boolean;\n /** Analysis quality level */\n quality?: 'basic' | 'thorough' | 'exhaustive';\n /** Generate improvement suggestions */\n suggestions?: boolean;\n /** Generate test report */\n report?: boolean | string;\n /** Report format */\n format?: 'json' | 'html' | 'markdown' | 'console';\n /** Test template to use */\n template?: string;\n /** Testing framework */\n framework?: 'vitest' | 'jest' | 'mocha' | 'custom';\n /** Watch mode for continuous testing */\n watch?: boolean;\n /** Test reporters (comma-separated) */\n reporters?: string[];\n}\n\n// ============================================================================\n// Parsed Arguments Types\n// ============================================================================\n\n/**\n * Parsed command line arguments\n */\nexport interface ParsedArgs {\n /** Command name */\n command: string;\n /** Subcommand name (if applicable) */\n subcommand?: string;\n /** Positional arguments */\n args: string[];\n /** Parsed options */\n options: Record<string, any>;\n /** Unknown options (for validation) */\n unknown: string[];\n}\n\n/**\n * Option validation result\n */\nexport interface OptionValidationResult {\n /** Whether validation passed */\n valid: boolean;\n /** Validation error messages */\n errors: string[];\n /** Validation warnings */\n warnings: string[];\n /** Normalized/coerced option values */\n normalizedOptions: Record<string, any>;\n}\n\n// ============================================================================\n// Error Types\n// ============================================================================\n\n/**\n * Base CLI error class\n */\nexport abstract class CLIError extends Error {\n /** Error code for programmatic handling */\n abstract code: string;\n /** Whether error should show help */\n showHelp: boolean = false;\n /** Suggested solutions */\n suggestions: string[] = [];\n\n constructor(message: string, showHelp: boolean = false) {\n super(message);\n this.name = this.constructor.name;\n this.showHelp = showHelp;\n }\n}\n\n/**\n * Validation error (user input issues)\n */\nexport class ValidationError extends CLIError {\n code = 'VALIDATION_ERROR';\n\n constructor(message: string, suggestions: string[] = []) {\n super(message, true);\n this.suggestions = suggestions;\n }\n}\n\n/**\n * Configuration error (config file/setup issues)\n */\nexport class ConfigurationError extends CLIError {\n code = 'CONFIGURATION_ERROR';\n\n constructor(message: string, suggestions: string[] = []) {\n super(message, false);\n this.suggestions = suggestions;\n }\n}\n\n/**\n * Runtime error (file system operations, process failures, etc.)\n */\nexport class RuntimeError extends CLIError {\n code = 'RUNTIME_ERROR';\n\n constructor(message: string, path?: string) {\n super(path ? `${message}: ${path}` : message);\n this.suggestions = [\n 'Check file/directory permissions',\n 'Verify path exists and is accessible',\n 'Use absolute paths to avoid ambiguity',\n ];\n }\n}\n\n// ============================================================================\n// Environment Variables\n// ============================================================================\n\n/**\n * Environment variable mappings for CLI options\n * Uses JUNO_CODE_* prefix exclusively (legacy JUNO_TASK_* removed)\n */\nexport const ENVIRONMENT_MAPPINGS = {\n // Core options\n JUNO_CODE_SUBAGENT: 'subagent',\n JUNO_CODE_AGENT: 'backend',\n JUNO_CODE_BACKEND: 'backend',\n JUNO_CODE_PROMPT: 'prompt',\n JUNO_CODE_CWD: 'cwd',\n JUNO_CODE_MAX_ITERATIONS: 'maxIterations',\n JUNO_CODE_MODEL: 'model',\n JUNO_CODE_LOG_FILE: 'logFile',\n JUNO_CODE_VERBOSE: 'verbose',\n JUNO_CODE_QUIET: 'quiet',\n JUNO_CODE_INTERACTIVE: 'interactive',\n JUNO_CODE_CONFIG: 'config',\n\n // MCP options\n JUNO_CODE_MCP_SERVER_PATH: 'mcpServerPath',\n JUNO_CODE_MCP_TIMEOUT: 'mcpTimeout',\n JUNO_CODE_MCP_RETRIES: 'mcpRetries',\n\n // Session options\n JUNO_CODE_SESSION_DIR: 'sessionDir',\n JUNO_CODE_LOG_LEVEL: 'logLevel',\n\n // Template options\n JUNO_CODE_TEMPLATE: 'template',\n JUNO_CODE_FORCE: 'force',\n\n // Git options\n JUNO_CODE_GIT_URL: 'gitUrl',\n\n // UI options\n JUNO_CODE_NO_COLOR: 'noColor',\n JUNO_CODE_HEADLESS: 'headless',\n\n // Feedback options\n JUNO_CODE_ENABLE_FEEDBACK: 'enableFeedback',\n\n // Special aliases\n JUNO_INTERACTIVE_FEEDBACK_MODE: 'enableFeedback', // Alias for enableFeedback\n} as const;\n\n/**\n * Type for environment variable keys\n */\nexport type EnvironmentVariable = keyof typeof ENVIRONMENT_MAPPINGS;\n\n/**\n * Type for CLI option keys\n */\nexport type CLIOptionKey = (typeof ENVIRONMENT_MAPPINGS)[EnvironmentVariable];\n\n// ============================================================================\n// Configuration Types\n// ============================================================================\n\n/**\n * Initialization data for project setup\n */\nexport interface InitializationData {\n /** Main task description */\n task: string;\n /** Preferred subagent */\n subagent: SubagentType;\n /** Repository URL (optional) */\n gitUrl?: string;\n /** Template variables */\n variables: Record<string, string>;\n /** Template variant */\n template: string;\n /** Additional metadata */\n metadata?: {\n author?: string;\n description?: string;\n tags?: string[];\n };\n}\n\n/**\n * Command execution result\n */\nexport interface CommandExecutionResult {\n /** Whether command succeeded */\n success: boolean;\n /** Exit code */\n exitCode: number;\n /** Execution time in milliseconds */\n duration: number;\n /** Output messages */\n output: string[];\n /** Error messages */\n errors: string[];\n}\n\n// ============================================================================\n// Type Guards\n// ============================================================================\n\n/**\n * Type guard for CLI errors\n */\nexport function isCLIError(error: unknown): error is CLIError {\n return error instanceof CLIError;\n}\n\n/**\n * Type guard for validation errors\n */\nexport function isValidationError(error: unknown): error is ValidationError {\n return error instanceof ValidationError;\n}\n\n/**\n * Type guard for configuration errors\n */\nexport function isConfigurationError(error: unknown): error is ConfigurationError {\n return error instanceof ConfigurationError;\n}\n\n/**\n * Type guard for runtime errors\n */\nexport function isRuntimeError(error: unknown): error is RuntimeError {\n return error instanceof RuntimeError;\n}\n\n// ============================================================================\n// Constants\n// ============================================================================\n\n/**\n * Supported subagent aliases\n */\nexport const SUBAGENT_ALIASES: Record<string, SubagentType> = {\n 'claude-code': 'claude',\n claude_code: 'claude',\n 'gemini-cli': 'gemini',\n 'cursor-agent': 'cursor',\n 'pi-agent': 'pi',\n};\n\n/**\n * Command categories for help organization\n */\nexport const COMMAND_CATEGORIES = {\n EXECUTION: ['juno-code', 'start'],\n PROJECT: ['init', 'setup-git'],\n TESTING: ['test'],\n SESSION: ['session'],\n FEEDBACK: ['feedback'],\n} as const;\n\n/**\n * Exit codes for different error types\n */\nexport const EXIT_CODES = {\n SUCCESS: 0,\n VALIDATION_ERROR: 1,\n CONFIGURATION_ERROR: 2,\n COMMAND_NOT_FOUND: 3,\n RUNTIME_ERROR: 5,\n UNEXPECTED_ERROR: 99,\n} as const;\n\nexport type ExitCode = (typeof EXIT_CODES)[keyof typeof EXIT_CODES];\n","/**\n * Core type definitions for juno-code\n */\n\n// Subagent types\nexport type SubagentType = 'claude' | 'cursor' | 'codex' | 'gemini' | 'pi';\n\n// Backend types for execution\nexport type BackendType = 'shell';\n\n// Session status\nexport type SessionStatus = 'running' | 'completed' | 'failed' | 'cancelled';\n\n// Log levels\nexport type LogLevel = 'error' | 'warn' | 'info' | 'debug' | 'trace';\n\n// On hourly limit behavior\nexport type OnHourlyLimit = 'wait' | 'raise';\n\n// Hook types\nexport type HookType = 'START_RUN' | 'START_ITERATION' | 'END_ITERATION' | 'END_RUN' | 'ON_STALE';\n\n// Hook configuration\nexport interface Hook {\n commands: string[];\n}\n\n// Hooks configuration mapping\nexport type Hooks = Record<HookType, Hook>;\n\n// Progress event types\nexport type ProgressEventType = 'tool_start' | 'tool_result' | 'thinking' | 'error' | 'info';\n\n// Base configuration interface\nexport interface JunoTaskConfig {\n // Core settings\n defaultSubagent: SubagentType;\n defaultMaxIterations: number;\n defaultModel?: string;\n defaultBackend: BackendType;\n\n // Project metadata\n mainTask?: string;\n\n // Logging settings\n logLevel: LogLevel;\n logFile?: string;\n verbose: boolean;\n quiet: boolean;\n\n // MCP settings\n mcpTimeout: number;\n mcpRetries: number;\n mcpServerPath?: string;\n mcpServerName?: string;\n\n // Hook settings\n hookCommandTimeout?: number;\n\n // Quota/hourly limit settings\n onHourlyLimit: OnHourlyLimit;\n\n // TUI settings\n interactive: boolean;\n headlessMode: boolean;\n\n // Paths\n workingDirectory: string;\n sessionDirectory: string;\n\n // Hooks configuration\n hooks?: Hooks;\n\n // Skip hooks execution\n skipHooks?: boolean;\n}\n\n// Global declarations for build-time constants\ndeclare global {\n const __VERSION__: string;\n const __DEV__: boolean;\n}\n"]}
1
+ {"version":3,"sources":["../src/version.ts","../src/core/errors.ts","../src/cli/utils/advanced-logger.ts","../src/types/execution.ts","../src/core/backends/shell-backend.ts","../src/index.ts","../src/core/config.ts","../src/templates/default-hooks.ts","../src/core/subagent-models.ts","../src/core/engine.ts","../src/utils/hooks.ts","../src/core/session.ts","../src/utils/environment.ts","../src/utils/validation.ts","../src/cli/types.ts","../src/types/index.ts"],"names":["version","LogLevel","chalk","fs","path2","fsExtra","resolve","env","os","spawn","stdout","z","path","fsPromises","yaml","nodeFs","result","execa","success","ExecutionStatus","EventEmitter","ShellBackend","resetTimeStr","path3","fs3","uuidv4","process2","delimiter","os2","path4","platform","LogLevelSchema"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKaA;AALb,IAAA,YAAA,GAAA,KAAA,CAAA;AAAA,EAAA,gBAAA,GAAA;AAKO,IAAMA,eAAA,GAAU,QAAA;AAAA,EAAA;AAAA,CAAA,CAAA;;;ACy2BhB,SAAS,wBAAwB,OAAA,EAAmC;AACzE,EAAA,KAAA,MAAW,WAAW,mBAAA,EAAqB;AACzC,IAAA,MAAM,KAAA,GAAQ,OAAA,CAAQ,KAAA,CAAM,OAAO,CAAA;AACnC,IAAA,IAAI,KAAA,EAAO;AACT,MAAA,IAAI;AACF,QAAA,OAAO,mBAAmB,KAAK,CAAA;AAAA,MACjC,CAAA,CAAA,MAAQ;AAAA,MAER;AAAA,IACF;AAAA,EACF;AACA,EAAA,OAAO,MAAA;AACT;AAKA,SAAS,mBAAmB,KAAA,EAA2C;AACrE,EAAA,MAAM,GAAG,KAAA,EAAO,KAAA,EAAO,MAAM,CAAA,GAAI,KAAA;AAGjC,EAAA,IAAI,KAAA,IAAS,KAAA,CAAM,QAAA,CAAS,GAAG,CAAA,EAAG;AAChC,IAAA,OAAO,IAAI,KAAK,KAAK,CAAA;AAAA,EACvB;AAGA,EAAA,IAAI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AAA,EAAY,KAAM,MAAA;AAC9C,UAAA;AAAA;AACJ,IACF,SAAS,KAAA,EAAO;AACd,MAAA,IAAI,iBAAiB,KAAA,EAAO;AAC1B,QAAA,MAAA,CAAO,KAAK,CAAA,EAAG,GAAG,CAAA,EAAA,EAAK,KAAA,CAAM,OAAO,CAAA,CAAE,CAAA;AAAA,MACxC;AAAA,IACF;AAAA,EACF,CAAC,CAAA;AAED,EAAA,IAAI,MAAA,CAAO,SAAS,CAAA,EAAG;AACrB,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA;AAAA,EAA4C,MAAA,CAAO,IAAA,CAAK,IAAI,CAAC,CAAA,CAAE,CAAA;AAAA,EACjF;AAEA,EAAA,OAAO,MAAA;AACT;;;AEhMA,YAAA,EAAA;;;AVyCA,YAAA,EAAA","file":"index.js","sourcesContent":["/**\n * Version information for juno-task-ts\n */\n\n// This will be replaced by the build process\nexport const version = __VERSION__ || '1.0.0';\n\n// Development flag\nexport const isDevelopment = __DEV__ || false;\n","/**\n * Execution error definitions for juno-task-ts\n *\n * Provides comprehensive error classes and utilities for execution operations,\n * including error codes, context tracking, recovery suggestions, and\n * specialized error types for different failure scenarios.\n *\n * Originally migrated from the MCP error module. The MCP system has been\n * removed; these are now the canonical execution error definitions.\n * Deprecated MCP-prefixed aliases are retained below for backward compatibility.\n *\n * @module core/errors\n * @version 2.0.0\n */\n\n// =============================================================================\n// Error Type Enums and Constants\n// =============================================================================\n\n/**\n * Execution error categories for targeted error handling\n */\nexport enum ExecutionErrorType {\n CONNECTION = 'connection',\n TIMEOUT = 'timeout',\n RATE_LIMIT = 'rate_limit',\n TOOL_EXECUTION = 'tool_execution',\n VALIDATION = 'validation',\n SERVER_NOT_FOUND = 'server_not_found',\n PROTOCOL = 'protocol',\n AUTHENTICATION = 'authentication',\n}\n\n/**\n * Error codes for specific error conditions\n */\nexport enum ExecutionErrorCode {\n // Connection errors\n CONNECTION_FAILED = 'MCP_CONNECTION_FAILED',\n CONNECTION_TIMEOUT = 'MCP_CONNECTION_TIMEOUT',\n CONNECTION_REFUSED = 'MCP_CONNECTION_REFUSED',\n CONNECTION_LOST = 'MCP_CONNECTION_LOST',\n RECONNECTION_FAILED = 'MCP_RECONNECTION_FAILED',\n\n // Tool execution errors\n TOOL_NOT_FOUND = 'MCP_TOOL_NOT_FOUND',\n TOOL_EXECUTION_FAILED = 'MCP_TOOL_EXECUTION_FAILED',\n TOOL_TIMEOUT = 'MCP_TOOL_TIMEOUT',\n TOOL_INVALID_ARGUMENTS = 'MCP_TOOL_INVALID_ARGUMENTS',\n\n // Rate limit errors\n RATE_LIMIT_EXCEEDED = 'MCP_RATE_LIMIT_EXCEEDED',\n RATE_LIMIT_HOURLY = 'MCP_RATE_LIMIT_HOURLY',\n RATE_LIMIT_DAILY = 'MCP_RATE_LIMIT_DAILY',\n\n // Validation errors\n VALIDATION_FAILED = 'MCP_VALIDATION_FAILED',\n INVALID_REQUEST = 'MCP_INVALID_REQUEST',\n MISSING_PARAMETERS = 'MCP_MISSING_PARAMETERS',\n INVALID_PARAMETERS = 'MCP_INVALID_PARAMETERS',\n\n // Server errors\n SERVER_NOT_FOUND = 'MCP_SERVER_NOT_FOUND',\n SERVER_NOT_EXECUTABLE = 'MCP_SERVER_NOT_EXECUTABLE',\n SERVER_STARTUP_FAILED = 'MCP_SERVER_STARTUP_FAILED',\n SERVER_CRASHED = 'MCP_SERVER_CRASHED',\n\n // Protocol errors\n PROTOCOL_ERROR = 'MCP_PROTOCOL_ERROR',\n INVALID_RESPONSE = 'MCP_INVALID_RESPONSE',\n VERSION_MISMATCH = 'MCP_VERSION_MISMATCH',\n\n // Authentication errors\n AUTHENTICATION_FAILED = 'MCP_AUTHENTICATION_FAILED',\n UNAUTHORIZED = 'MCP_UNAUTHORIZED',\n TOKEN_EXPIRED = 'MCP_TOKEN_EXPIRED',\n}\n\n/**\n * Rate limit message patterns for parsing reset times\n */\nexport const RATE_LIMIT_PATTERNS = [\n // Unix timestamp patterns (must come first to avoid conflicts)\n /resets?\\s+(?:at\\s+)?(\\d{10,13})/i,\n\n // ISO date patterns\n /resets?\\s+(?:at\\s+)?([\\d-]+T[\\d:.]+Z?)/i,\n\n // Standard patterns\n /resets\\s+(?:at\\s+)?(\\d{1,2}):?(\\d{2})?\\s*(am|pm)?/i,\n /resets\\s+(?:at\\s+)?(\\d{1,2})\\s*(am|pm)/i,\n\n // Duration-based patterns\n /try again in (\\d+)\\s*(minutes?|hours?|seconds?)/i,\n /wait\\s+(\\d+)\\s*(minutes?|hours?|seconds?)/i,\n\n // Specific service patterns\n /5-hour limit reached.*resets\\s+(?:at\\s+)?(\\d{1,2})\\s*(am|pm)/i,\n /hourly limit.*resets\\s+(?:at\\s+)?(\\d{1,2}):(\\d{2})/i,\n] as const;\n\n// =============================================================================\n// Error Context Interfaces\n// =============================================================================\n\n/**\n * Base error options for execution errors\n */\nexport interface ExecutionErrorOptions {\n /** Error code for programmatic handling */\n readonly code?: ExecutionErrorCode | undefined;\n\n /** Operation context when error occurred */\n readonly context?: string | undefined;\n\n /** Retry information */\n readonly retryInfo?: RetryInfo | undefined;\n\n /** Recovery suggestions for the user */\n readonly recoverySuggestions?: readonly string[] | undefined;\n\n /** Cause error for error chaining */\n readonly cause?: Error | undefined;\n\n /** Additional metadata */\n readonly metadata?: Readonly<Record<string, unknown>> | undefined;\n}\n\n/**\n * Retry information for error context\n */\nexport interface RetryInfo {\n /** Current attempt number */\n readonly attempt: number;\n\n /** Maximum attempts allowed */\n readonly maxAttempts: number;\n\n /** Next retry time */\n readonly nextRetryTime?: Date;\n\n /** Retry strategy used */\n readonly strategy: string;\n\n /** Backoff delay in milliseconds */\n readonly backoffDelay?: number;\n}\n\n/**\n * Server information for connection errors\n */\nexport interface ServerInfo {\n /** Server executable path */\n readonly path: string;\n\n /** Server version */\n readonly version?: string;\n\n /** Process ID */\n readonly pid?: number;\n\n /** Server status */\n readonly status: string;\n\n /** Server arguments */\n readonly args?: readonly string[];\n\n /** Working directory */\n readonly workingDirectory?: string;\n}\n\n/**\n * Tool information for tool errors\n */\nexport interface ToolInfo {\n /** Tool name */\n readonly name: string;\n\n /** Tool version */\n readonly version?: string;\n\n /** Subagent type */\n readonly subagent: string;\n\n /** Model used */\n readonly model?: string;\n\n /** Tool capabilities */\n readonly capabilities?: readonly string[];\n}\n\n/**\n * Tool execution details for error context\n */\nexport interface ToolExecutionDetails {\n /** Execution start time */\n readonly startTime: Date;\n\n /** Execution duration in milliseconds */\n readonly duration: number;\n\n /** Arguments used */\n readonly arguments: Readonly<Record<string, unknown>>;\n\n /** Progress events captured */\n readonly progressEvents?: readonly unknown[];\n\n /** Execution timeout */\n readonly timeout?: number;\n\n /** Session ID */\n readonly sessionId?: string;\n}\n\n// =============================================================================\n// Base Execution Error Class\n// =============================================================================\n\n/**\n * Base execution error class with enhanced context and recovery information\n */\nexport abstract class ExecutionError extends Error {\n /** Error type classification */\n public readonly type: ExecutionErrorType;\n\n /** Error code for programmatic handling */\n public readonly code: ExecutionErrorCode;\n\n /** Error timestamp */\n public readonly timestamp: Date;\n\n /** Operation context */\n public readonly context?: string | undefined;\n\n /** Retry information */\n public readonly retryInfo?: RetryInfo | undefined;\n\n /** Recovery suggestions */\n public readonly recoverySuggestions?: readonly string[] | undefined;\n\n /** Additional metadata */\n public readonly metadata?: Readonly<Record<string, unknown>> | undefined;\n\n /** Cause error for error chaining */\n public override readonly cause?: Error | undefined;\n\n constructor(\n message: string,\n type: ExecutionErrorType,\n code: ExecutionErrorCode,\n options?: ExecutionErrorOptions,\n ) {\n super(message);\n this.name = this.constructor.name;\n this.type = type;\n this.code = options?.code ?? code;\n this.timestamp = new Date();\n this.context = options?.context;\n this.retryInfo = options?.retryInfo;\n this.recoverySuggestions = options?.recoverySuggestions;\n this.metadata = options?.metadata;\n this.cause = options?.cause;\n\n // Maintain proper stack trace\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n\n /**\n * Get user-friendly error message\n */\n getUserMessage(): string {\n return this.message;\n }\n\n /**\n * Get technical error details\n */\n getTechnicalDetails(): string {\n const details = [\n `Error: ${this.name}`,\n `Type: ${this.type}`,\n `Code: ${this.code}`,\n `Message: ${this.message}`,\n `Timestamp: ${this.timestamp.toISOString()}`,\n ];\n\n if (this.context) {\n details.push(`Context: ${this.context}`);\n }\n\n if (this.retryInfo) {\n details.push(`Retry: ${this.retryInfo.attempt}/${this.retryInfo.maxAttempts}`);\n }\n\n if (this.cause) {\n details.push(`Cause: ${this.cause.message}`);\n }\n\n return details.join('\\n');\n }\n\n /**\n * Check if error is retryable\n */\n isRetryable(): boolean {\n if (!this.retryInfo) {\n return false;\n }\n return this.retryInfo.attempt < this.retryInfo.maxAttempts;\n }\n\n /**\n * Get time until next retry\n */\n getRetryDelay(): number {\n if (!this.retryInfo?.nextRetryTime) {\n return 0;\n }\n return Math.max(0, this.retryInfo.nextRetryTime.getTime() - Date.now());\n }\n\n /**\n * Serialize error to JSON\n */\n toJSON(): Record<string, unknown> {\n return {\n name: this.name,\n type: this.type,\n code: this.code,\n message: this.message,\n timestamp: this.timestamp.toISOString(),\n context: this.context,\n retryInfo: this.retryInfo,\n recoverySuggestions: this.recoverySuggestions,\n metadata: this.metadata,\n stack: this.stack,\n };\n }\n}\n\n// =============================================================================\n// Connection Error Classes\n// =============================================================================\n\n/**\n * Connection error for server connection failures\n */\nexport class ConnectionError extends ExecutionError {\n /** Server information */\n public readonly serverInfo?: ServerInfo | undefined;\n\n constructor(\n message: string,\n context?: string,\n serverInfo?: ServerInfo,\n options?: ExecutionErrorOptions,\n ) {\n const code = options?.code ?? ExecutionErrorCode.CONNECTION_FAILED;\n const suggestions = options?.recoverySuggestions ?? [\n 'Check if the server is running',\n 'Verify server path and permissions',\n 'Check network connectivity',\n 'Review server configuration',\n ];\n\n super(message, ExecutionErrorType.CONNECTION, code, {\n ...options,\n context,\n recoverySuggestions: suggestions,\n });\n\n this.serverInfo = serverInfo;\n }\n\n /**\n * Create connection timeout error\n */\n static timeout(timeoutMs: number, serverPath?: string): ConnectionError {\n return new ConnectionError(\n `Connection timeout after ${timeoutMs}ms`,\n 'connection_timeout',\n serverPath ? { path: serverPath, status: 'timeout' } : undefined,\n {\n code: ExecutionErrorCode.CONNECTION_TIMEOUT,\n recoverySuggestions: [\n 'Increase connection timeout value',\n 'Check server responsiveness',\n 'Verify network latency',\n ],\n },\n );\n }\n\n /**\n * Create connection refused error\n */\n static refused(serverPath: string, port?: number): ConnectionError {\n return new ConnectionError(\n `Connection refused to ${serverPath}${port ? `:${port}` : ''}`,\n 'connection_refused',\n { path: serverPath, status: 'refused' },\n {\n code: ExecutionErrorCode.CONNECTION_REFUSED,\n recoverySuggestions: [\n 'Verify server is running and listening',\n 'Check server address and port',\n 'Review firewall settings',\n ],\n },\n );\n }\n\n /**\n * Create server not found error\n */\n static serverNotFound(serverPath: string): ConnectionError {\n return new ConnectionError(\n `Server not found at path: ${serverPath}`,\n 'server_discovery',\n { path: serverPath, status: 'not_found' },\n {\n code: ExecutionErrorCode.SERVER_NOT_FOUND,\n recoverySuggestions: [\n 'Check server installation path',\n 'Verify executable permissions',\n 'Install the server package',\n 'Update PATH environment variable',\n ],\n },\n );\n }\n}\n\n// =============================================================================\n// Tool Error Classes\n// =============================================================================\n\n/**\n * Tool execution error\n */\nexport class ToolError extends ExecutionError {\n /** Tool information */\n public readonly toolInfo: ToolInfo;\n\n /** Execution details */\n public readonly executionDetails?: ToolExecutionDetails | undefined;\n\n constructor(\n message: string,\n toolInfo: ToolInfo,\n context?: string,\n options?: ExecutionErrorOptions & { executionDetails?: ToolExecutionDetails | undefined },\n ) {\n const code = options?.code ?? ExecutionErrorCode.TOOL_EXECUTION_FAILED;\n const suggestions = options?.recoverySuggestions ?? [\n 'Check tool arguments and parameters',\n 'Verify tool is available and accessible',\n 'Review tool documentation',\n 'Check server logs for details',\n ];\n\n super(message, ExecutionErrorType.TOOL_EXECUTION, code, {\n ...options,\n context,\n recoverySuggestions: suggestions,\n });\n\n this.toolInfo = toolInfo;\n this.executionDetails = options?.executionDetails;\n }\n\n /**\n * Create tool not found error\n */\n static notFound(toolName: string): ToolError {\n return new ToolError(\n `Tool not found: ${toolName}`,\n { name: toolName, subagent: 'unknown' },\n 'tool_discovery',\n {\n code: ExecutionErrorCode.TOOL_NOT_FOUND,\n recoverySuggestions: [\n 'Check available tools with listTools()',\n 'Verify tool name spelling',\n 'Ensure server supports this tool',\n ],\n },\n );\n }\n\n /**\n * Create tool timeout error\n */\n static timeout(\n toolName: string,\n timeoutMs: number,\n executionDetails?: ToolExecutionDetails,\n ): ToolError {\n return new ToolError(\n `Tool execution timeout: ${toolName} (${timeoutMs}ms)`,\n { name: toolName, subagent: 'unknown' },\n 'tool_timeout',\n {\n code: ExecutionErrorCode.TOOL_TIMEOUT,\n executionDetails,\n recoverySuggestions: [\n 'Increase tool execution timeout',\n 'Check tool complexity and resource usage',\n 'Consider breaking task into smaller parts',\n ],\n },\n );\n }\n\n /**\n * Create invalid arguments error\n */\n static invalidArguments(\n toolName: string,\n invalidArgs: Record<string, unknown>,\n expectedFormat?: string,\n ): ToolError {\n return new ToolError(\n `Invalid arguments for tool: ${toolName}`,\n { name: toolName, subagent: 'unknown' },\n 'argument_validation',\n {\n code: ExecutionErrorCode.TOOL_INVALID_ARGUMENTS,\n metadata: { invalidArgs, expectedFormat },\n recoverySuggestions: [\n 'Check tool documentation for required arguments',\n 'Verify argument types and formats',\n 'Review tool schema definition',\n ],\n },\n );\n }\n}\n\n// =============================================================================\n// Timeout Error Classes\n// =============================================================================\n\n/**\n * Timeout error for operation timeouts\n */\nexport class TimeoutError extends ExecutionError {\n /** Timeout duration in milliseconds */\n public readonly timeoutMs: number;\n\n /** Operation type that timed out */\n public readonly operationType: string;\n\n constructor(\n message: string,\n timeoutMs: number,\n operationType: string,\n context?: string,\n options?: ExecutionErrorOptions,\n ) {\n const code = options?.code ?? ExecutionErrorCode.CONNECTION_TIMEOUT;\n const suggestions = options?.recoverySuggestions ?? [\n 'Increase timeout value',\n 'Check operation complexity',\n 'Verify network connectivity',\n 'Consider breaking operation into smaller parts',\n ];\n\n super(message, ExecutionErrorType.TIMEOUT, code, {\n ...options,\n context,\n recoverySuggestions: suggestions,\n });\n\n this.timeoutMs = timeoutMs;\n this.operationType = operationType;\n }\n\n /**\n * Create connection timeout error\n */\n static connection(timeoutMs: number): TimeoutError {\n return new TimeoutError(\n `Connection timeout after ${timeoutMs}ms`,\n timeoutMs,\n 'connection',\n 'backend_connection',\n {\n code: ExecutionErrorCode.CONNECTION_TIMEOUT,\n recoverySuggestions: [\n 'Increase connection timeout',\n 'Check server startup time',\n 'Verify network latency',\n ],\n },\n );\n }\n\n /**\n * Create tool execution timeout error\n */\n static toolExecution(toolName: string, timeoutMs: number): TimeoutError {\n return new TimeoutError(\n `Tool execution timeout: ${toolName} (${timeoutMs}ms)`,\n timeoutMs,\n 'tool_execution',\n `tool_${toolName}`,\n {\n code: ExecutionErrorCode.TOOL_TIMEOUT,\n recoverySuggestions: [\n 'Increase tool execution timeout',\n 'Optimize tool parameters',\n 'Check tool resource usage',\n ],\n },\n );\n }\n}\n\n// =============================================================================\n// Rate Limit Error Classes\n// =============================================================================\n\n/**\n * Rate limit error with reset time parsing\n */\nexport class RateLimitError extends ExecutionError {\n /** Rate limit reset time */\n public readonly resetTime?: Date | undefined;\n\n /** Current rate limit tier */\n public readonly tier?: string | undefined;\n\n /** Requests remaining */\n public readonly remaining: number;\n\n /** Rate limit window */\n public readonly window?: string | undefined;\n\n constructor(\n message: string,\n remaining: number = 0,\n resetTime?: Date,\n tier?: string,\n context?: string,\n options?: ExecutionErrorOptions,\n ) {\n const code = options?.code ?? ExecutionErrorCode.RATE_LIMIT_EXCEEDED;\n const waitTime = resetTime ? Math.ceil((resetTime.getTime() - Date.now()) / 1000) : 0;\n const suggestions = options?.recoverySuggestions ?? [\n `Wait ${waitTime > 0 ? waitTime + ' seconds' : 'for rate limit reset'}`,\n 'Reduce request frequency',\n 'Implement request queuing',\n 'Consider upgrading service tier',\n ];\n\n super(message, ExecutionErrorType.RATE_LIMIT, code, {\n ...options,\n context,\n recoverySuggestions: suggestions,\n retryInfo: resetTime\n ? {\n attempt: 1,\n maxAttempts: 1,\n nextRetryTime: resetTime,\n strategy: 'rate_limit_wait',\n }\n : options?.retryInfo,\n });\n\n this.resetTime = resetTime;\n this.tier = tier;\n this.remaining = remaining;\n }\n\n /**\n * Parse rate limit error from message text\n */\n static fromMessage(message: string, context?: string): RateLimitError {\n const resetTime = parseRateLimitResetTime(message);\n\n // Extract remaining requests if available\n const remainingMatch = message.match(/(\\d+)\\s*(?:requests?|calls?)\\s*remaining/i);\n const remaining = remainingMatch ? parseInt(remainingMatch[1]!, 10) : 0;\n\n // Extract tier information if available\n const tierMatch = message.match(/tier[:\\s]*([a-zA-Z0-9_-]+)/i);\n const tier = tierMatch ? tierMatch[1] : undefined;\n\n return new RateLimitError(message, remaining, resetTime, tier, context, {\n code: ExecutionErrorCode.RATE_LIMIT_EXCEEDED,\n metadata: { originalMessage: message },\n });\n }\n\n /**\n * Create hourly rate limit error\n */\n static hourly(resetTime: Date, remaining: number = 0): RateLimitError {\n return new RateLimitError(\n `Hourly rate limit exceeded. Resets at ${resetTime.toLocaleTimeString()}`,\n remaining,\n resetTime,\n 'hourly',\n 'hourly_limit',\n {\n code: ExecutionErrorCode.RATE_LIMIT_HOURLY,\n },\n );\n }\n\n /**\n * Create daily rate limit error\n */\n static daily(resetTime: Date, remaining: number = 0): RateLimitError {\n return new RateLimitError(\n `Daily rate limit exceeded. Resets at ${resetTime.toLocaleDateString()} ${resetTime.toLocaleTimeString()}`,\n remaining,\n resetTime,\n 'daily',\n 'daily_limit',\n {\n code: ExecutionErrorCode.RATE_LIMIT_DAILY,\n },\n );\n }\n\n /**\n * Get wait time in milliseconds\n */\n getWaitTimeMs(): number {\n if (!this.resetTime) {\n return 0;\n }\n return Math.max(0, this.resetTime.getTime() - Date.now());\n }\n\n /**\n * Get wait time in seconds\n */\n getWaitTimeSeconds(): number {\n return Math.ceil(this.getWaitTimeMs() / 1000);\n }\n}\n\n// =============================================================================\n// Validation Error Classes\n// =============================================================================\n\n/**\n * Validation error for input validation failures\n */\nexport class ValidationError extends ExecutionError {\n /** Validation rule that failed */\n public readonly rule: string;\n\n /** Invalid value */\n public readonly value: unknown;\n\n /** Expected format/value */\n public readonly expected?: string | undefined;\n\n /** Field path for nested validation */\n public readonly field?: string | undefined;\n\n constructor(\n message: string,\n rule: string,\n value: unknown,\n expected?: string,\n field?: string,\n context?: string,\n options?: ExecutionErrorOptions,\n ) {\n const code = options?.code ?? ExecutionErrorCode.VALIDATION_FAILED;\n const suggestions = options?.recoverySuggestions ?? [\n 'Check parameter types and formats',\n 'Refer to API documentation',\n 'Validate input before sending',\n ];\n\n super(message, ExecutionErrorType.VALIDATION, code, {\n ...options,\n context,\n recoverySuggestions: suggestions,\n });\n\n this.rule = rule;\n this.value = value;\n this.expected = expected;\n this.field = field;\n }\n\n /**\n * Create required field error\n */\n static required(field: string): ValidationError {\n return new ValidationError(\n `Required field missing: ${field}`,\n 'required',\n undefined,\n 'non-empty value',\n field,\n 'parameter_validation',\n {\n code: ExecutionErrorCode.MISSING_PARAMETERS,\n },\n );\n }\n\n /**\n * Create type mismatch error\n */\n static typeMismatch(field: string, value: unknown, expectedType: string): ValidationError {\n return new ValidationError(\n `Invalid type for field '${field}': expected ${expectedType}, got ${typeof value}`,\n 'type_mismatch',\n value,\n expectedType,\n field,\n 'type_validation',\n {\n code: ExecutionErrorCode.INVALID_PARAMETERS,\n },\n );\n }\n\n /**\n * Create format error\n */\n static format(field: string, value: unknown, expectedFormat: string): ValidationError {\n return new ValidationError(\n `Invalid format for field '${field}': expected ${expectedFormat}`,\n 'format',\n value,\n expectedFormat,\n field,\n 'format_validation',\n {\n code: ExecutionErrorCode.INVALID_PARAMETERS,\n },\n );\n }\n\n /**\n * Create range error\n */\n static range(field: string, value: unknown, min?: number, max?: number): ValidationError {\n const range =\n min !== undefined && max !== undefined\n ? `${min}-${max}`\n : min !== undefined\n ? `>= ${min}`\n : `<= ${max}`;\n\n return new ValidationError(\n `Value out of range for field '${field}': expected ${range}`,\n 'range',\n value,\n range,\n field,\n 'range_validation',\n {\n code: ExecutionErrorCode.INVALID_PARAMETERS,\n },\n );\n }\n}\n\n// =============================================================================\n// Utility Functions\n// =============================================================================\n\n/**\n * Parse rate limit reset time from various message formats\n */\nexport function parseRateLimitResetTime(message: string): Date | undefined {\n for (const pattern of RATE_LIMIT_PATTERNS) {\n const match = message.match(pattern);\n if (match) {\n try {\n return parseTimeFromMatch(match);\n } catch {\n // Continue to next pattern\n }\n }\n }\n return undefined;\n}\n\n/**\n * Parse time information from regex match\n */\nfunction parseTimeFromMatch(match: RegExpMatchArray): Date | undefined {\n const [, time1, time2, period] = match;\n\n // Handle ISO date string (check before Unix timestamp to avoid conflicts)\n if (time1 && time1.includes('T')) {\n return new Date(time1);\n }\n\n // Handle Unix timestamp\n if (time1 && time1.length >= 10) {\n const timestamp = parseInt(time1, 10);\n return new Date(timestamp > 9999999999 ? timestamp : timestamp * 1000);\n }\n\n // Handle duration-based patterns\n if (time2 && (time2.includes('minute') || time2.includes('hour') || time2.includes('second'))) {\n const duration = parseInt(time1!, 10);\n const unit = time2.toLowerCase();\n const now = new Date();\n\n if (unit.includes('minute')) {\n return new Date(now.getTime() + duration * 60 * 1000);\n } else if (unit.includes('hour')) {\n return new Date(now.getTime() + duration * 60 * 60 * 1000);\n } else if (unit.includes('second')) {\n return new Date(now.getTime() + duration * 1000);\n }\n }\n\n // Handle time-based patterns (e.g., \"3:30 PM\", \"15:30\")\n if (time1) {\n const hour = parseInt(time1, 10);\n const minute = time2 ? parseInt(time2, 10) : 0;\n let adjustedHour = hour;\n\n if (period) {\n const isPM = period.toLowerCase().includes('pm');\n if (isPM && hour < 12) {\n adjustedHour += 12;\n } else if (!isPM && hour === 12) {\n adjustedHour = 0;\n }\n }\n\n const resetTime = new Date();\n resetTime.setHours(adjustedHour, minute, 0, 0);\n\n // If the time has passed today, set it for tomorrow\n if (resetTime <= new Date()) {\n resetTime.setDate(resetTime.getDate() + 1);\n }\n\n return resetTime;\n }\n\n return undefined;\n}\n\n/**\n * Type guards for error checking\n */\n\n/**\n * Check if error is an execution error\n */\nexport function isExecutionError(error: unknown): error is ExecutionError {\n return error instanceof ExecutionError;\n}\n\n/**\n * Check if error is a connection error\n */\nexport function isConnectionError(error: unknown): error is ConnectionError {\n return error instanceof ConnectionError;\n}\n\n/**\n * Check if error is a tool error\n */\nexport function isToolError(error: unknown): error is ToolError {\n return error instanceof ToolError;\n}\n\n/**\n * Check if error is a timeout error\n */\nexport function isTimeoutError(error: unknown): error is TimeoutError {\n return error instanceof TimeoutError;\n}\n\n/**\n * Check if error is a rate limit error\n */\nexport function isRateLimitError(error: unknown): error is RateLimitError {\n return error instanceof RateLimitError;\n}\n\n/**\n * Check if error is a validation error\n */\nexport function isValidationError(error: unknown): error is ValidationError {\n return error instanceof ValidationError;\n}\n\n/**\n * Check if error is retryable\n */\nexport function isRetryableError(error: unknown): boolean {\n if (!isExecutionError(error)) {\n return false;\n }\n\n // Rate limits are retryable after the reset time\n if (isRateLimitError(error)) {\n return true;\n }\n\n // Connection errors are usually retryable\n if (isConnectionError(error)) {\n return true;\n }\n\n // Some timeout errors are retryable\n if (isTimeoutError(error)) {\n return true;\n }\n\n // Validation errors are not retryable\n if (isValidationError(error)) {\n return false;\n }\n\n return error.isRetryable();\n}\n\n/**\n * Get error category for recovery strategy\n */\nexport function getErrorCategory(error: unknown): ExecutionErrorType | 'unknown' {\n if (isExecutionError(error)) {\n return error.type;\n }\n return 'unknown';\n}\n\n/**\n * Format error for user display\n */\nexport function formatErrorForUser(error: unknown): string {\n if (isExecutionError(error)) {\n return error.getUserMessage();\n }\n\n if (error instanceof Error) {\n return error.message;\n }\n\n return String(error);\n}\n\n/**\n * Format error for logging\n */\nexport function formatErrorForLogging(error: unknown): string {\n if (isExecutionError(error)) {\n return error.getTechnicalDetails();\n }\n\n if (error instanceof Error) {\n return `${error.name}: ${error.message}\\n${error.stack || 'No stack trace'}`;\n }\n\n return `Unknown error: ${JSON.stringify(error)}`;\n}\n\n/**\n * Extract recovery suggestions from error\n */\nexport function getRecoverySuggestions(error: unknown): string[] {\n if (isExecutionError(error) && error.recoverySuggestions) {\n return Array.from(error.recoverySuggestions);\n }\n\n // Default suggestions based on error type\n if (isConnectionError(error)) {\n return ['Check network connectivity', 'Verify server is running', 'Check server configuration'];\n }\n\n if (isRateLimitError(error)) {\n return ['Wait for rate limit reset', 'Reduce request frequency', 'Implement request queuing'];\n }\n\n if (isValidationError(error)) {\n return ['Check input parameters', 'Refer to API documentation', 'Validate data before sending'];\n }\n\n return [\n 'Check error message for details',\n 'Review configuration',\n 'Contact support if problem persists',\n ];\n}\n\n/**\n * Create error chain from multiple errors\n */\nexport function createErrorChain(errors: Error[]): ExecutionError {\n if (errors.length === 0) {\n return new ConnectionError('Unknown error occurred', 'error_chain');\n }\n\n if (errors.length === 1) {\n const error = errors[0]!;\n if (isExecutionError(error)) {\n return error;\n }\n return new ConnectionError(error.message, 'wrapped_error', undefined, {\n cause: error,\n });\n }\n\n const primaryError = errors[0]!;\n const additionalErrors = errors.slice(1);\n\n return new ConnectionError(\n `Multiple errors occurred: ${primaryError.message}`,\n 'error_chain',\n undefined,\n {\n cause: primaryError,\n metadata: {\n additionalErrors: additionalErrors.map((e) => ({\n name: e.name,\n message: e.message,\n })),\n },\n recoverySuggestions: [\n 'Address the primary error first',\n 'Check for cascading failures',\n 'Review system configuration',\n ],\n },\n );\n}\n\n// =============================================================================\n// Error Recovery Utilities\n// =============================================================================\n\n/**\n * Error recovery strategy type\n */\nexport type ErrorRecoveryStrategy =\n | 'retry'\n | 'wait'\n | 'reconnect'\n | 'fallback'\n | 'abort'\n | 'manual';\n\n/**\n * Get recommended recovery strategy for error\n */\nexport function getRecoveryStrategy(error: unknown): ErrorRecoveryStrategy {\n if (isRateLimitError(error)) {\n return 'wait';\n }\n\n if (isConnectionError(error)) {\n return 'reconnect';\n }\n\n if (isTimeoutError(error)) {\n return 'retry';\n }\n\n if (isValidationError(error)) {\n return 'manual';\n }\n\n if (isToolError(error)) {\n return 'fallback';\n }\n\n return 'abort';\n}\n\n/**\n * Calculate retry delay based on error and attempt\n */\nexport function calculateRetryDelay(\n error: unknown,\n attempt: number,\n baseDelay: number = 1000,\n maxDelay: number = 30000,\n): number {\n if (isRateLimitError(error)) {\n return error.getWaitTimeMs();\n }\n\n // Exponential backoff with jitter\n const exponentialDelay = Math.min(baseDelay * Math.pow(2, attempt - 1), maxDelay);\n const jitter = exponentialDelay * 0.1 * (Math.random() - 0.5);\n\n return Math.max(0, exponentialDelay + jitter);\n}\n\n// =============================================================================\n// Deprecated Aliases (backward compatibility)\n// The MCP system has been removed. These aliases are kept temporarily so that\n// any external consumers referencing the old MCP-prefixed names continue to\n// compile. They will be removed in a future major version.\n// =============================================================================\n\n/** @deprecated Use ExecutionErrorType instead */\nexport const MCPErrorType = ExecutionErrorType;\n/** @deprecated Use ExecutionErrorType instead */\nexport type MCPErrorType = ExecutionErrorType;\n\n/** @deprecated Use ExecutionErrorCode instead */\nexport const MCPErrorCode = ExecutionErrorCode;\n/** @deprecated Use ExecutionErrorCode instead */\nexport type MCPErrorCode = ExecutionErrorCode;\n\n/** @deprecated Use ExecutionErrorOptions instead */\nexport type MCPErrorOptions = ExecutionErrorOptions;\n\n/** @deprecated Use ExecutionError instead */\nexport type MCPError = ExecutionError;\n/** @deprecated Use ExecutionError instead */\nexport const MCPError = ExecutionError;\n\n/** @deprecated Use ConnectionError instead */\nexport type MCPConnectionError = ConnectionError;\n/** @deprecated Use ConnectionError instead */\nexport const MCPConnectionError = ConnectionError;\n\n/** @deprecated Use ToolError instead */\nexport type MCPToolError = ToolError;\n/** @deprecated Use ToolError instead */\nexport const MCPToolError = ToolError;\n\n/** @deprecated Use TimeoutError instead */\nexport type MCPTimeoutError = TimeoutError;\n/** @deprecated Use TimeoutError instead */\nexport const MCPTimeoutError = TimeoutError;\n\n/** @deprecated Use RateLimitError instead */\nexport type MCPRateLimitError = RateLimitError;\n/** @deprecated Use RateLimitError instead */\nexport const MCPRateLimitError = RateLimitError;\n\n/** @deprecated Use ValidationError instead */\nexport type MCPValidationError = ValidationError;\n/** @deprecated Use ValidationError instead */\nexport const MCPValidationError = ValidationError;\n\n/** @deprecated Use isExecutionError instead */\nexport const isMCPError = isExecutionError;\n","/**\n * Advanced Log Formatting System for juno-code\n *\n * Provides structured, colorized logging with multiple log levels and contexts.\n * All output goes to stderr to keep stdout clean for structured results.\n */\n\nimport chalk from 'chalk';\n\n// ============================================================================\n// Log Level and Context Types\n// ============================================================================\n\nexport enum LogLevel {\n TRACE = 0,\n DEBUG = 1,\n INFO = 2,\n WARN = 3,\n ERROR = 4,\n FATAL = 5,\n}\n\nexport enum LogContext {\n CLI = 'CLI',\n MCP = 'MCP',\n ENGINE = 'ENGINE',\n SESSION = 'SESSION',\n TEMPLATE = 'TEMPLATE',\n CONFIG = 'CONFIG',\n PERFORMANCE = 'PERFORMANCE',\n SYSTEM = 'SYSTEM',\n}\n\nexport interface LogEntry {\n timestamp: Date;\n level: LogLevel;\n context: LogContext;\n message: string;\n data?: any;\n duration?: number;\n}\n\nexport interface LoggerOptions {\n level: LogLevel;\n showTimestamp: boolean;\n showContext: boolean;\n showLevel: boolean;\n colorize: boolean;\n output: 'console';\n}\n\n// ============================================================================\n// Advanced Logger Class\n// ============================================================================\n\nexport class AdvancedLogger {\n private options: LoggerOptions;\n\n constructor(options: Partial<LoggerOptions> = {}) {\n this.options = {\n level: LogLevel.INFO,\n showTimestamp: true,\n showContext: true,\n showLevel: true,\n colorize: true,\n output: 'console',\n ...options,\n };\n }\n\n trace(message: string, context: LogContext = LogContext.SYSTEM, data?: any): void {\n this.log(LogLevel.TRACE, message, context, data);\n }\n\n debug(message: string, context: LogContext = LogContext.SYSTEM, data?: any): void {\n this.log(LogLevel.DEBUG, message, context, data);\n }\n\n info(message: string, context: LogContext = LogContext.SYSTEM, data?: any): void {\n this.log(LogLevel.INFO, message, context, data);\n }\n\n warn(message: string, context: LogContext = LogContext.SYSTEM, data?: any): void {\n this.log(LogLevel.WARN, message, context, data);\n }\n\n error(message: string, context: LogContext = LogContext.SYSTEM, data?: any): void {\n this.log(LogLevel.ERROR, message, context, data);\n }\n\n fatal(message: string, context: LogContext = LogContext.SYSTEM, data?: any): void {\n this.log(LogLevel.FATAL, message, context, data);\n }\n\n /**\n * Change log level\n */\n setLevel(level: LogLevel): void {\n this.options.level = level;\n }\n\n /**\n * Create a child logger with specific context\n */\n child(context: LogContext): ContextLogger {\n return new ContextLogger(this, context);\n }\n\n /**\n * Core logging method\n */\n private log(level: LogLevel, message: string, context: LogContext, data?: any): void {\n if (level < this.options.level) return;\n\n const entry: LogEntry = {\n timestamp: new Date(),\n level,\n context,\n message,\n data,\n };\n\n const formatted = this.formatSimple(entry);\n this.output(formatted);\n }\n\n /**\n * Simple format: [LEVEL] [CONTEXT] Message (duration)\n */\n private formatSimple(entry: LogEntry): string {\n const parts: string[] = [];\n\n if (this.options.showLevel) {\n const levelStr = this.formatLevel(entry.level);\n parts.push(`[${levelStr}]`);\n }\n\n if (this.options.showContext) {\n const contextStr = this.options.colorize\n ? chalk.gray(`[${entry.context}]`)\n : `[${entry.context}]`;\n parts.push(contextStr);\n }\n\n parts.push(entry.message);\n\n if (entry.duration !== undefined) {\n const durationStr = this.options.colorize\n ? chalk.cyan(`(${entry.duration}ms)`)\n : `(${entry.duration}ms)`;\n parts.push(durationStr);\n }\n\n return parts.join(' ');\n }\n\n /**\n * Format log level with appropriate color\n */\n private formatLevel(level: LogLevel): string {\n const levelName = LogLevel[level].padEnd(5);\n\n if (!this.options.colorize) return levelName;\n\n switch (level) {\n case LogLevel.TRACE:\n return chalk.gray(levelName);\n case LogLevel.DEBUG:\n return chalk.blue(levelName);\n case LogLevel.INFO:\n return chalk.green(levelName);\n case LogLevel.WARN:\n return chalk.yellow(levelName);\n case LogLevel.ERROR:\n return chalk.red(levelName);\n case LogLevel.FATAL:\n return chalk.redBright.bold(levelName);\n default:\n return levelName;\n }\n }\n\n /**\n * Output formatted log to stderr\n */\n private output(formatted: string): void {\n console.error(formatted);\n }\n}\n\n// ============================================================================\n// Context Logger Class\n// ============================================================================\n\nexport class ContextLogger {\n constructor(\n private parent: AdvancedLogger,\n private context: LogContext,\n ) {}\n\n trace(message: string, data?: any): void {\n this.parent.trace(message, this.context, data);\n }\n\n debug(message: string, data?: any): void {\n this.parent.debug(message, this.context, data);\n }\n\n info(message: string, data?: any): void {\n this.parent.info(message, this.context, data);\n }\n\n warn(message: string, data?: any): void {\n this.parent.warn(message, this.context, data);\n }\n\n error(message: string, data?: any): void {\n this.parent.error(message, this.context, data);\n }\n\n fatal(message: string, data?: any): void {\n this.parent.fatal(message, this.context, data);\n }\n}\n\n// ============================================================================\n// Global Logger Instance\n// ============================================================================\n\nexport const logger = new AdvancedLogger({\n level: LogLevel.INFO,\n colorize: true,\n output: 'console',\n});\n\n// Export context-specific loggers\nexport const cliLogger = logger.child(LogContext.CLI);\nexport const mcpLogger = logger.child(LogContext.MCP);\nexport const engineLogger = logger.child(LogContext.ENGINE);\nexport const sessionLogger = logger.child(LogContext.SESSION);\nexport const templateLogger = logger.child(LogContext.TEMPLATE);\nexport const configLogger = logger.child(LogContext.CONFIG);\nexport const performanceLogger = logger.child(LogContext.PERFORMANCE);\n\nexport default AdvancedLogger;\n","/**\n * Execution type definitions for juno-code\n *\n * This module provides comprehensive TypeScript types for task execution,\n * including progress tracking, tool calls, subagent integration,\n * session management, and connection lifecycle.\n *\n * @module execution\n * @since 1.0.0\n */\n\n// =============================================================================\n// Core Types & Enums\n// =============================================================================\n\n/**\n * Supported subagent types for tool mapping\n */\nexport type SubagentType = 'claude' | 'cursor' | 'codex' | 'gemini' | 'pi';\n\n/**\n * Extended subagent aliases for flexible naming\n */\nexport type SubagentAlias = 'claude-code' | 'claude_code' | 'gemini-cli' | 'cursor-agent';\n\n/**\n * Connection state lifecycle\n */\nexport enum MCPConnectionState {\n DISCONNECTED = 'disconnected',\n CONNECTING = 'connecting',\n CONNECTED = 'connected',\n RECONNECTING = 'reconnecting',\n FAILED = 'failed',\n CLOSING = 'closing',\n}\n\n/**\n * Progress event types from Roundtable server format\n */\nexport enum ProgressEventType {\n TOOL_START = 'tool_start',\n TOOL_RESULT = 'tool_result',\n THINKING = 'thinking',\n ERROR = 'error',\n INFO = 'info',\n DEBUG = 'debug',\n}\n\n/**\n * Error categories for targeted error handling\n */\nexport enum MCPErrorType {\n CONNECTION = 'connection',\n TIMEOUT = 'timeout',\n RATE_LIMIT = 'rate_limit',\n TOOL_EXECUTION = 'tool_execution',\n VALIDATION = 'validation',\n SERVER_NOT_FOUND = 'server_not_found',\n PROTOCOL = 'protocol',\n AUTHENTICATION = 'authentication',\n}\n\n/**\n * Tool execution status for tracking\n */\nexport enum ToolExecutionStatus {\n PENDING = 'pending',\n RUNNING = 'running',\n COMPLETED = 'completed',\n FAILED = 'failed',\n CANCELLED = 'cancelled',\n TIMEOUT = 'timeout',\n}\n\n// =============================================================================\n// Configuration Types\n// =============================================================================\n\n/**\n * Core server configuration interface\n *\n * @example\n * ```typescript\n * const config: MCPServerConfig = {\n * serverPath: './mcp_server',\n * timeout: 3600,\n * retries: 3,\n * retryDelay: 1000,\n * workingDirectory: process.cwd(),\n * environment: {\n * 'API_KEY': 'your-key'\n * }\n * };\n * ```\n */\nexport interface MCPServerConfig {\n /** Optional path to server executable - will auto-discover if not provided */\n readonly serverPath?: string;\n\n /** Tool execution timeout in milliseconds (default: 3600000ms = 1 hour) */\n readonly timeout: number;\n\n /** Maximum retry attempts for failed operations (default: 3) */\n readonly retries: number;\n\n /** Delay between retry attempts in milliseconds (default: 1000ms) */\n readonly retryDelay: number;\n\n /** Working directory for server process execution */\n readonly workingDirectory: string;\n\n /** Additional environment variables for server process */\n readonly environment?: Readonly<Record<string, string>>;\n\n /** Custom server arguments (advanced usage) */\n readonly serverArgs?: readonly string[];\n\n /** Enable debug logging for communications */\n readonly debug?: boolean;\n\n /** Maximum memory usage for server process in MB */\n readonly maxMemoryMB?: number;\n\n /** Process priority for server subprocess */\n readonly processPriority?: 'low' | 'normal' | 'high';\n}\n\n/**\n * Connection retry configuration with exponential backoff\n */\nexport interface RetryConfig {\n /** Maximum number of retry attempts */\n readonly maxRetries: number;\n\n /** Initial delay between retries in milliseconds */\n readonly initialDelay: number;\n\n /** Maximum delay between retries in milliseconds */\n readonly maxDelay: number;\n\n /** Exponential backoff multiplier */\n readonly backoffMultiplier: number;\n\n /** Jitter factor to randomize retry timing (0-1) */\n readonly jitterFactor: number;\n\n /** Custom retry condition predicate */\n readonly shouldRetry?: (error: Error, attempt: number) => boolean;\n}\n\n/**\n * Rate limiting configuration and state\n */\nexport interface RateLimitConfig {\n /** Maximum requests per time window */\n readonly maxRequests: number;\n\n /** Time window in milliseconds */\n readonly windowMs: number;\n\n /** Burst allowance for short-term spikes */\n readonly burstAllowance: number;\n\n /** Enable adaptive rate limiting based on server responses */\n readonly adaptive: boolean;\n}\n\n// =============================================================================\n// Progress Tracking Types\n// =============================================================================\n\n/**\n * Progress event interface matching Roundtable server format\n * Format: \"Backend #count: event_type => content\"\n *\n * @example\n * ```typescript\n * const progressEvent: ProgressEvent = {\n * sessionId: 'session-123',\n * timestamp: new Date(),\n * backend: 'claude',\n * count: 1,\n * type: ProgressEventType.TOOL_START,\n * content: 'Starting code analysis...',\n * toolId: 'claude_1',\n * metadata: {\n * duration: 150,\n * tokens: 1024\n * }\n * };\n * ```\n */\nexport interface ProgressEvent {\n /** Unique session identifier for correlation */\n readonly sessionId: string;\n\n /** Event timestamp */\n readonly timestamp: Date;\n\n /** Subagent backend name (claude, cursor, codex, gemini) */\n readonly backend: string;\n\n /** Sequential event number within session */\n readonly count: number;\n\n /** Progress event classification */\n readonly type: ProgressEventType;\n\n /** Event content/message from subagent */\n readonly content: string;\n\n /** Generated tool correlation ID for tracking */\n readonly toolId: string;\n\n /** Additional event metadata */\n readonly metadata?: Readonly<Record<string, unknown>>;\n\n /** Parent event ID for nested operations */\n readonly parentId?: string;\n\n /** Event priority level */\n readonly priority?: 'low' | 'normal' | 'high';\n}\n\n/**\n * Progress callback function signature\n * Callbacks must never throw errors to avoid breaking execution flow\n *\n * @param event - The progress event to handle\n * @returns Promise<void> - Should handle errors internally\n */\nexport type ProgressCallback = (event: ProgressEvent) => Promise<void> | void;\n\n/**\n * Progress metadata for context tracking\n */\nexport interface ProgressMetadata {\n /** Operation start time */\n readonly startTime: Date;\n\n /** Total events processed */\n readonly eventCount: number;\n\n /** Last event timestamp */\n readonly lastEventTime?: Date;\n\n /** Operation context */\n readonly context: string;\n\n /** User-defined tags for categorization */\n readonly tags?: readonly string[];\n\n /** Performance metrics */\n readonly metrics?: ProgressMetrics;\n}\n\n/**\n * Performance metrics for progress tracking\n */\nexport interface ProgressMetrics {\n /** Average event processing time in milliseconds */\n readonly avgProcessingTime: number;\n\n /** Events processed per second */\n readonly eventsPerSecond: number;\n\n /** Memory usage in bytes */\n readonly memoryUsage: number;\n\n /** CPU usage percentage */\n readonly cpuUsage: number;\n}\n\n// =============================================================================\n// Tool Execution Types\n// =============================================================================\n\n/**\n * Tool call request structure\n *\n * @example\n * ```typescript\n * const request: ToolCallRequest = {\n * toolName: 'claude_subagent',\n * arguments: {\n * instruction: 'Analyze this code',\n * project_path: '/path/to/project',\n * model: 'sonnet-4'\n * },\n * timeout: 30000,\n * priority: 'high',\n * metadata: {\n * userId: 'user-123',\n * sessionId: 'session-456'\n * }\n * };\n * ```\n */\nexport interface ToolCallRequest {\n /** Tool name (mapped from subagent name) */\n readonly toolName: string;\n\n /** Tool arguments object */\n readonly arguments: Readonly<Record<string, unknown>>;\n\n /** Request timeout in milliseconds */\n readonly timeout?: number;\n\n /** Request priority level */\n readonly priority?: 'low' | 'normal' | 'high';\n\n /** Additional request metadata */\n readonly metadata?: Readonly<Record<string, unknown>>;\n\n /** Callback for progress events */\n readonly progressCallback?: ProgressCallback;\n\n /** Unique request identifier */\n readonly requestId?: string;\n}\n\n/**\n * Tool call result structure\n */\nexport interface ToolCallResult {\n /** Tool execution result content */\n readonly content: string;\n\n /** Execution status */\n readonly status: ToolExecutionStatus;\n\n /** Execution start time */\n readonly startTime: Date;\n\n /** Execution end time */\n readonly endTime: Date;\n\n /** Total execution duration in milliseconds */\n readonly duration: number;\n\n /** Any error that occurred during execution */\n readonly error?: Error;\n\n /** Progress events generated during execution */\n readonly progressEvents: readonly ProgressEvent[];\n\n /** Tool execution metadata */\n readonly metadata?: ToolExecutionMetadata;\n\n /** Request that generated this result */\n readonly request: ToolCallRequest;\n}\n\n/**\n * Tool execution metadata\n */\nexport interface ToolExecutionMetadata {\n /** Number of tokens used */\n readonly tokensUsed?: number;\n\n /** Estimated cost */\n readonly estimatedCost?: number;\n\n /** Model used for execution */\n readonly model?: string;\n\n /** Server version */\n readonly serverVersion?: string;\n\n /** Performance metrics */\n readonly performanceMetrics?: ToolPerformanceMetrics;\n\n /** Raw subagent response payload (for programmatic capture / session resume) */\n readonly subAgentResponse?: any;\n\n /** Indicates the content string is structured (e.g., JSON) and safe to parse */\n readonly structuredOutput?: boolean;\n\n /** Content type for the tool output (e.g., application/json) */\n readonly contentType?: string;\n\n /** Original raw output emitted by the tool (pre-structuring) */\n readonly rawOutput?: string;\n\n /** Quota limit information detected during execution */\n readonly quotaLimitInfo?: any;\n}\n\n/**\n * Tool performance metrics\n */\nexport interface ToolPerformanceMetrics {\n /** CPU usage during execution */\n readonly cpuUsage: number;\n\n /** Memory usage during execution */\n readonly memoryUsage: number;\n\n /** Network usage in bytes */\n readonly networkUsage: number;\n\n /** Processing time breakdown */\n readonly timingBreakdown: Record<string, number>;\n}\n\n// =============================================================================\n// Subagent Integration Types\n// =============================================================================\n\n/**\n * Subagent information and capabilities\n */\nexport interface SubagentInfo {\n /** Subagent identifier */\n readonly id: SubagentType;\n\n /** Display name */\n readonly name: string;\n\n /** Supported capabilities */\n readonly capabilities: readonly SubagentCapability[];\n\n /** Available models */\n readonly models: readonly string[];\n\n /** Default model */\n readonly defaultModel: string;\n\n /** Current availability status */\n readonly status: SubagentStatus;\n\n /** Rate limiting information */\n readonly rateLimits?: RateLimitInfo;\n\n /** Performance characteristics */\n readonly performance?: SubagentPerformance;\n}\n\n/**\n * Subagent capability types\n */\nexport enum SubagentCapability {\n CODE_GENERATION = 'code_generation',\n CODE_ANALYSIS = 'code_analysis',\n DEBUGGING = 'debugging',\n REFACTORING = 'refactoring',\n DOCUMENTATION = 'documentation',\n TESTING = 'testing',\n ARCHITECTURE = 'architecture',\n REVIEW = 'review',\n}\n\n/**\n * Subagent status\n */\nexport enum SubagentStatus {\n AVAILABLE = 'available',\n BUSY = 'busy',\n RATE_LIMITED = 'rate_limited',\n UNAVAILABLE = 'unavailable',\n ERROR = 'error',\n MAINTENANCE = 'maintenance',\n}\n\n/**\n * Rate limit information\n */\nexport interface RateLimitInfo {\n /** Requests remaining in current window */\n readonly remaining: number;\n\n /** Total requests allowed per window */\n readonly limit: number;\n\n /** Window reset time */\n readonly resetTime: Date;\n\n /** Current rate limit tier */\n readonly tier: string;\n}\n\n/**\n * Subagent performance characteristics\n */\nexport interface SubagentPerformance {\n /** Average response time in milliseconds */\n readonly avgResponseTime: number;\n\n /** Success rate percentage */\n readonly successRate: number;\n\n /** Current load level */\n readonly loadLevel: 'low' | 'medium' | 'high';\n\n /** Quality score (0-100) */\n readonly qualityScore: number;\n}\n\n/**\n * Subagent tool mapping configuration\n */\nexport interface SubagentMapper {\n /** Core subagent to tool name mapping */\n readonly mapping: Readonly<Record<SubagentType, string>>;\n\n /** Alias to subagent mapping */\n readonly aliases: Readonly<Record<SubagentAlias, SubagentType>>;\n\n /** Model validation rules */\n readonly modelValidation: Readonly<Record<SubagentType, ModelValidationRule>>;\n\n /** Default configurations per subagent */\n readonly defaults: Readonly<Record<SubagentType, SubagentDefaults>>;\n}\n\n/**\n * Model validation rule\n */\nexport interface ModelValidationRule {\n /** Allowed models for this subagent */\n readonly allowedModels: readonly string[];\n\n /** Default model if none specified */\n readonly defaultModel: string;\n\n /** Custom validation function */\n readonly customValidator?: (model: string) => boolean;\n}\n\n/**\n * Default subagent configuration\n */\nexport interface SubagentDefaults {\n /** Default timeout in milliseconds */\n readonly timeout: number;\n\n /** Default model */\n readonly model: string;\n\n /** Default arguments */\n readonly arguments: Readonly<Record<string, unknown>>;\n\n /** Default priority */\n readonly priority: 'low' | 'normal' | 'high';\n}\n\n// =============================================================================\n// Connection Management Types\n// =============================================================================\n\n/**\n * Connection lifecycle event\n */\nexport interface ConnectionEvent {\n /** Event type */\n readonly type: ConnectionEventType;\n\n /** Event timestamp */\n readonly timestamp: Date;\n\n /** Connection state after event */\n readonly state: MCPConnectionState;\n\n /** Event details */\n readonly details?: string;\n\n /** Error information if applicable */\n readonly error?: Error;\n}\n\n/**\n * Connection event types\n */\nexport enum ConnectionEventType {\n CONNECTING = 'connecting',\n CONNECTED = 'connected',\n DISCONNECTED = 'disconnected',\n RECONNECTING = 'reconnecting',\n ERROR = 'error',\n TIMEOUT = 'timeout',\n RATE_LIMITED = 'rate_limited',\n}\n\n/**\n * Connection health monitoring\n */\nexport interface ConnectionHealth {\n /** Current connection state */\n readonly state: MCPConnectionState;\n\n /** Connection uptime in milliseconds */\n readonly uptime: number;\n\n /** Number of successful operations */\n readonly successfulOperations: number;\n\n /** Number of failed operations */\n readonly failedOperations: number;\n\n /** Average response time */\n readonly avgResponseTime: number;\n\n /** Last successful operation time */\n readonly lastSuccessTime?: Date;\n\n /** Last error time */\n readonly lastErrorTime?: Date;\n\n /** Current error streak */\n readonly errorStreak: number;\n}\n\n/**\n * Connection recovery strategy\n */\nexport interface RecoveryStrategy {\n /** Strategy type */\n readonly type: RecoveryStrategyType;\n\n /** Strategy configuration */\n readonly config: RecoveryConfig;\n\n /** Custom recovery function */\n readonly customRecovery?: () => Promise<boolean>;\n}\n\n/**\n * Recovery strategy types\n */\nexport enum RecoveryStrategyType {\n IMMEDIATE_RETRY = 'immediate_retry',\n EXPONENTIAL_BACKOFF = 'exponential_backoff',\n CIRCUIT_BREAKER = 'circuit_breaker',\n GRACEFUL_DEGRADATION = 'graceful_degradation',\n CUSTOM = 'custom',\n}\n\n/**\n * Recovery configuration\n */\nexport interface RecoveryConfig {\n /** Maximum recovery attempts */\n readonly maxAttempts: number;\n\n /** Recovery timeout */\n readonly timeout: number;\n\n /** Strategy-specific parameters */\n readonly parameters: Readonly<Record<string, unknown>>;\n}\n\n// =============================================================================\n// Session Integration Types\n// =============================================================================\n\n/**\n * Session context (renamed from MCPSessionContext)\n */\nexport interface SessionContext {\n /** Unique session identifier */\n readonly sessionId: string;\n\n /** Session start time */\n readonly startTime: Date;\n\n /** User identifier */\n readonly userId?: string;\n\n /** Session metadata */\n readonly metadata: Readonly<Record<string, unknown>>;\n\n /** Active tool calls */\n readonly activeToolCalls: readonly string[];\n\n /** Session state */\n readonly state: SessionState;\n\n /** Last activity time */\n readonly lastActivity: Date;\n}\n\n/** @deprecated Use SessionContext instead */\nexport type MCPSessionContext = SessionContext;\n\n/**\n * Session state\n */\nexport enum SessionState {\n INITIALIZING = 'initializing',\n ACTIVE = 'active',\n IDLE = 'idle',\n SUSPENDED = 'suspended',\n COMPLETED = 'completed',\n FAILED = 'failed',\n}\n\n/**\n * Session persistence configuration\n */\nexport interface SessionPersistence {\n /** Enable session persistence */\n readonly enabled: boolean;\n\n /** Storage backend type */\n readonly storageType: SessionStorageType;\n\n /** Storage configuration */\n readonly storageConfig: SessionStorageConfig;\n\n /** Session TTL in milliseconds */\n readonly ttlMs: number;\n\n /** Auto-cleanup interval */\n readonly cleanupIntervalMs: number;\n}\n\n/**\n * Session storage types\n */\nexport enum SessionStorageType {\n MEMORY = 'memory',\n FILE = 'file',\n DATABASE = 'database',\n REDIS = 'redis',\n}\n\n/**\n * Session storage configuration\n */\nexport interface SessionStorageConfig {\n /** Storage-specific parameters */\n readonly parameters: Readonly<Record<string, unknown>>;\n\n /** Encryption configuration */\n readonly encryption?: EncryptionConfig;\n\n /** Compression configuration */\n readonly compression?: CompressionConfig;\n}\n\n/**\n * Encryption configuration\n */\nexport interface EncryptionConfig {\n /** Encryption algorithm */\n readonly algorithm: string;\n\n /** Key derivation parameters */\n readonly keyDerivation: KeyDerivationConfig;\n}\n\n/**\n * Key derivation configuration\n */\nexport interface KeyDerivationConfig {\n /** KDF algorithm */\n readonly algorithm: string;\n\n /** Salt length */\n readonly saltLength: number;\n\n /** Iteration count */\n readonly iterations: number;\n}\n\n/**\n * Compression configuration\n */\nexport interface CompressionConfig {\n /** Compression algorithm */\n readonly algorithm: 'gzip' | 'deflate' | 'brotli';\n\n /** Compression level */\n readonly level: number;\n}\n\n// =============================================================================\n// Error Types - Imported from core/errors.ts\n// =============================================================================\n\n// Import error types from dedicated errors module\nexport type {\n ExecutionError,\n ConnectionError,\n ToolError,\n TimeoutError,\n RateLimitError,\n ValidationError,\n ExecutionErrorOptions,\n RetryInfo,\n ServerInfo,\n ToolInfo,\n ToolExecutionDetails,\n} from '../core/errors.js';\n\n// =============================================================================\n// Utility Types\n// =============================================================================\n\n/**\n * Type-safe event emitter interface for events\n */\nexport interface MCPEventEmitter {\n on<T extends keyof MCPEventMap>(event: T, listener: MCPEventMap[T]): void;\n off<T extends keyof MCPEventMap>(event: T, listener: MCPEventMap[T]): void;\n emit<T extends keyof MCPEventMap>(event: T, ...args: Parameters<MCPEventMap[T]>): boolean;\n}\n\n/**\n * Event map for type-safe event handling\n */\nexport interface MCPEventMap {\n 'connection:state': (state: MCPConnectionState) => void;\n 'connection:error': (error: Error) => void;\n 'progress:event': (event: ProgressEvent) => void;\n 'tool:start': (request: ToolCallRequest) => void;\n 'tool:complete': (result: ToolCallResult) => void;\n 'tool:error': (error: Error) => void;\n 'session:create': (context: SessionContext) => void;\n 'session:end': (sessionId: string) => void;\n 'rate-limit:reached': (error: Error) => void;\n}\n\n/**\n * Utility type for making properties optional\n */\nexport type PartialBy<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;\n\n/**\n * Utility type for making properties required\n */\nexport type RequiredBy<T, K extends keyof T> = T & Required<Pick<T, K>>;\n\n/**\n * Utility type for deep readonly\n */\nexport type DeepReadonly<T> = {\n readonly [P in keyof T]: T[P] extends object ? DeepReadonly<T[P]> : T[P];\n};\n\n/**\n * Utility type for extracting promise return type\n */\nexport type Awaited<T> = T extends Promise<infer U> ? U : T;\n\n/**\n * Type guard for progress events\n */\nexport function isProgressEvent(obj: unknown): obj is ProgressEvent {\n return (\n typeof obj === 'object' &&\n obj !== null &&\n 'sessionId' in obj &&\n 'timestamp' in obj &&\n 'backend' in obj &&\n 'count' in obj &&\n 'type' in obj &&\n 'content' in obj &&\n 'toolId' in obj\n );\n}\n\n// Import type guards from errors module\nexport { isExecutionError } from '../core/errors.js';\n\n/**\n * Type guard for subagent types\n */\nexport function isSubagentType(value: string): value is SubagentType {\n return ['claude', 'cursor', 'codex', 'gemini', 'pi'].includes(value);\n}\n\n/**\n * Type guard for connection states\n */\nexport function isConnectionState(value: string): value is MCPConnectionState {\n return Object.values(MCPConnectionState).includes(value as MCPConnectionState);\n}\n\n// =============================================================================\n// Factory Types\n// =============================================================================\n\n/**\n * Client factory configuration\n */\nexport interface MCPClientFactory {\n /** Create client with configuration */\n create(config: MCPServerConfig): Promise<MCPClient>;\n\n /** Create mock client for testing */\n createMock(mockConfig?: MockClientConfig): MockMCPClient;\n\n /** Validate configuration */\n validateConfig(config: MCPServerConfig): ValidationResult;\n}\n\n/**\n * Mock client configuration for testing\n */\nexport interface MockClientConfig {\n /** Predefined tool responses */\n readonly toolResponses: Readonly<Record<string, string>>;\n\n /** Simulated progress events */\n readonly progressEvents: readonly ProgressEvent[];\n\n /** Simulated errors */\n readonly errors: readonly Error[];\n\n /** Response delays */\n readonly responseDelays: Readonly<Record<string, number>>;\n}\n\n/**\n * Validation result\n */\nexport interface ValidationResult {\n /** Validation success */\n readonly valid: boolean;\n\n /** Validation errors */\n readonly errors: readonly string[];\n\n /** Validation warnings */\n readonly warnings: readonly string[];\n}\n\n/**\n * Abstract client interface\n */\nexport interface MCPClient {\n /** Connect to server */\n connect(): Promise<void>;\n\n /** Disconnect from server */\n disconnect(): Promise<void>;\n\n /** Check connection status */\n isConnected(): boolean;\n\n /** Call tool with progress tracking */\n callTool(request: ToolCallRequest): Promise<ToolCallResult>;\n\n /** List available tools */\n listTools(): Promise<readonly string[]>;\n\n /** Get subagent information */\n getSubagentInfo(subagent: SubagentType): Promise<SubagentInfo>;\n\n /** Add progress callback */\n onProgress(callback: ProgressCallback): () => void;\n\n /** Get connection health */\n getHealth(): ConnectionHealth;\n\n /** Event emitter interface */\n on<T extends keyof MCPEventMap>(event: T, listener: MCPEventMap[T]): void;\n off<T extends keyof MCPEventMap>(event: T, listener: MCPEventMap[T]): void;\n}\n\n/**\n * Mock client interface for testing\n */\nexport interface MockMCPClient extends MCPClient {\n /** Add mock tool response */\n addToolResponse(toolName: string, response: string): void;\n\n /** Simulate progress event */\n simulateProgressEvent(event: ProgressEvent): void;\n\n /** Simulate error */\n simulateError(error: Error): void;\n\n /** Reset mock state */\n reset(): void;\n}\n\n// =============================================================================\n// Constants\n// =============================================================================\n\n/**\n * Default configuration values\n */\nexport const MCP_DEFAULTS = {\n TIMEOUT: 3600000, // 1 hour\n RETRIES: 3,\n RETRY_DELAY: 1000, // 1 second\n MAX_MEMORY_MB: 512,\n PROCESS_PRIORITY: 'normal' as const,\n CONNECTION_TIMEOUT: 30000, // 30 seconds\n HEALTH_CHECK_INTERVAL: 60000, // 1 minute\n SESSION_TTL: 86400000, // 24 hours\n CLEANUP_INTERVAL: 3600000, // 1 hour\n} as const;\n\n/**\n * Subagent to tool mapping\n */\nexport const SUBAGENT_TOOL_MAPPING: Record<SubagentType, string> = {\n claude: 'claude_subagent',\n cursor: 'cursor_subagent',\n codex: 'codex_subagent',\n gemini: 'gemini_subagent',\n pi: 'pi_subagent',\n} as const;\n\n/**\n * Subagent alias mapping\n */\nexport const SUBAGENT_ALIASES: Record<SubagentAlias, SubagentType> = {\n 'claude-code': 'claude',\n claude_code: 'claude',\n 'gemini-cli': 'gemini',\n 'cursor-agent': 'cursor',\n} as const;\n\n/**\n * Progress event parsing patterns\n */\nexport const PROGRESS_PATTERNS = {\n /** Main progress message pattern: \"Backend #count: event_type => content\" */\n MAIN: /^(.+?)\\s+#(\\d+):\\s+(\\w+)\\s*=>\\s*(.+)$/,\n\n /** Tool call patterns for detection */\n TOOL_CALLS: [\n /calling\\s+tool[:\\s]*([a-zA-Z_][a-zA-Z0-9_]*)/i,\n /<function_calls>\\s*<invoke name=\"([^\"]+)\"/i,\n /tool[:\\s]*([a-zA-Z_][a-zA-Z0-9_]*)/i,\n ],\n\n /** Rate limit patterns */\n RATE_LIMITS: [\n /resets\\s+(at\\s+)?(\\d{1,2}):(\\d{2})\\s*(am|pm)?/i,\n /resets\\s+(at\\s+)?(\\d{1,2})\\s*(am|pm)/i,\n /try again in (\\d+)\\s*(minutes?|hours?)/i,\n /5-hour limit reached.*resets\\s+(at\\s+)?(\\d{1,2})\\s*(am|pm)/i,\n ],\n} as const;\n","/**\n * Shell Backend Implementation for juno-code\n *\n * Executes shell scripts from ~/.juno_code/services/ directory\n * Supports JSON streaming output and converts to progress events\n */\n\nimport { spawn, ChildProcess } from 'node:child_process';\nimport { promises as fs } from 'node:fs';\nimport * as path from 'node:path';\nimport os from 'node:os';\nimport fsExtra from 'fs-extra';\nimport type { Backend } from '../backend-manager.js';\nimport {\n ProgressEventType,\n ToolExecutionStatus,\n} from '../../types/execution.js';\nimport type {\n ToolCallRequest,\n ToolCallResult,\n ProgressEvent,\n ProgressCallback,\n ToolExecutionMetadata,\n} from '../../types/execution.js';\nimport { engineLogger } from '../../cli/utils/advanced-logger.js';\n\n// =============================================================================\n// Type Definitions\n// =============================================================================\n\n/**\n * Shell backend configuration\n */\nexport interface ShellBackendConfig {\n /** Working directory for execution */\n workingDirectory: string;\n\n /** Path to services directory (default: ~/.juno_code/services) */\n servicesPath: string;\n\n /** Enable debug logging */\n debug?: boolean;\n\n /** Timeout for script execution in milliseconds */\n timeout?: number;\n\n /** Environment variables to pass to shell scripts */\n environment?: Record<string, string>;\n\n /** Enable JSON streaming parsing */\n enableJsonStreaming?: boolean;\n\n /** Output full JSON format instead of simplified messages (for verbose mode) */\n outputRawJson?: boolean;\n}\n\n/**\n * Script execution result\n */\ninterface ScriptExecutionResult {\n success: boolean;\n output: string;\n error?: string;\n exitCode: number;\n duration: number;\n subAgentResponse?: any;\n metadata?: Record<string, any>;\n}\n\n/**\n * Quota limit information extracted from Claude or Codex response\n */\nexport interface QuotaLimitInfo {\n /** Whether a quota limit was detected */\n detected: boolean;\n /** The parsed reset time as a Date object */\n resetTime?: Date;\n /** Sleep duration in milliseconds until the reset time */\n sleepDurationMs?: number;\n /** The timezone extracted from the message */\n timezone?: string;\n /** Original error message */\n originalMessage?: string;\n /** Which subagent triggered the quota limit */\n source?: 'claude' | 'codex';\n}\n\n// =============================================================================\n// Quota Limit Detection Utilities\n// =============================================================================\n\n/**\n * Common timezone aliases and their UTC offsets\n */\nconst TIMEZONE_OFFSETS: Record<string, number> = {\n // North American timezones\n 'America/Toronto': -5,\n 'America/New_York': -5,\n 'US/Eastern': -5,\n 'America/Chicago': -6,\n 'US/Central': -6,\n 'America/Denver': -7,\n 'US/Mountain': -7,\n 'America/Los_Angeles': -8,\n 'US/Pacific': -8,\n // European timezones\n 'Europe/London': 0,\n UTC: 0,\n GMT: 0,\n 'Europe/Paris': 1,\n 'Europe/Berlin': 1,\n CET: 1,\n // Other common timezones\n 'Asia/Tokyo': 9,\n 'Asia/Shanghai': 8,\n 'Australia/Sydney': 11,\n};\n\n/**\n * Parse reset time from Claude quota limit message\n * Handles formats like:\n * - \"resets 8pm (America/Toronto)\"\n * - \"resets 10am (UTC)\"\n * - \"resets 11:30pm (US/Eastern)\"\n * - \"resets 2:00 PM (America/New_York)\"\n */\nfunction parseResetTime(message: string): { resetTime: Date; timezone: string } | null {\n // Pattern to match: \"resets HH[:MM] [AM/PM] (TIMEZONE)\"\n const resetPattern = /resets\\s+(\\d{1,2})(?::(\\d{2}))?\\s*(am|pm)?\\s*\\(([^)]+)\\)/i;\n const match = message.match(resetPattern);\n\n if (!match) {\n return null;\n }\n\n let hours = parseInt(match[1]!, 10);\n const minutes = match[2] ? parseInt(match[2]!, 10) : 0;\n const ampm = match[3]?.toLowerCase();\n const timezone = match[4]!.trim();\n\n // Convert to 24-hour format\n if (ampm === 'pm' && hours !== 12) {\n hours += 12;\n } else if (ampm === 'am' && hours === 12) {\n hours = 0;\n }\n\n // Get timezone offset (default to local if unknown)\n const timezoneOffset = TIMEZONE_OFFSETS[timezone];\n\n // Create reset time in the specified timezone\n const now = new Date();\n const resetTime = new Date();\n\n if (timezoneOffset !== undefined) {\n // Set the reset time in the target timezone\n resetTime.setUTCHours(hours - timezoneOffset, minutes, 0, 0);\n\n // If the reset time is in the past, add a day\n if (resetTime.getTime() <= now.getTime()) {\n resetTime.setTime(resetTime.getTime() + 24 * 60 * 60 * 1000);\n }\n } else {\n // Fallback: assume it's in the local timezone\n resetTime.setHours(hours, minutes, 0, 0);\n\n // If the reset time is in the past, add a day\n if (resetTime.getTime() <= now.getTime()) {\n resetTime.setTime(resetTime.getTime() + 24 * 60 * 60 * 1000);\n }\n }\n\n return { resetTime, timezone };\n}\n\n/**\n * Parse reset time from Codex quota limit message\n * Handles formats like:\n * - \"try again at Feb 4th, 2026 1:50 AM\"\n * - \"try again at February 4, 2026 1:50 AM\"\n * - \"try again at Jan 15th, 2026 11:30 PM\"\n */\nfunction parseCodexResetTime(message: string): { resetTime: Date } | null {\n // Pattern to match: \"try again at Month Day[st/nd/rd/th], Year HH:MM AM/PM\"\n const resetPattern =\n /try again at\\s+(\\w+)\\s+(\\d{1,2})(?:st|nd|rd|th)?,?\\s*(\\d{4})\\s+(\\d{1,2}):(\\d{2})\\s*(AM|PM)/i;\n const match = message.match(resetPattern);\n\n if (!match) {\n return null;\n }\n\n const monthStr = match[1]!;\n const day = parseInt(match[2]!, 10);\n const year = parseInt(match[3]!, 10);\n let hours = parseInt(match[4]!, 10);\n const minutes = parseInt(match[5]!, 10);\n const ampm = match[6]!.toUpperCase();\n\n // Convert month name to number\n const MONTH_MAP: Record<string, number> = {\n jan: 0,\n january: 0,\n feb: 1,\n february: 1,\n mar: 2,\n march: 2,\n apr: 3,\n april: 3,\n may: 4,\n jun: 5,\n june: 5,\n jul: 6,\n july: 6,\n aug: 7,\n august: 7,\n sep: 8,\n september: 8,\n oct: 9,\n october: 9,\n nov: 10,\n november: 10,\n dec: 11,\n december: 11,\n };\n\n const month = MONTH_MAP[monthStr.toLowerCase()];\n if (month === undefined) {\n return null;\n }\n\n // Convert 12-hour format to 24-hour format\n if (ampm === 'PM' && hours !== 12) {\n hours += 12;\n } else if (ampm === 'AM' && hours === 12) {\n hours = 0;\n }\n\n // Codex provides an absolute date/time, construct it directly\n // The time is assumed to be in the user's local timezone (Codex doesn't specify timezone)\n const resetTime = new Date(year, month, day, hours, minutes, 0, 0);\n\n // If the reset time is in the past, it's likely already passed; add 24h as fallback\n const now = new Date();\n if (resetTime.getTime() <= now.getTime()) {\n resetTime.setTime(resetTime.getTime() + 24 * 60 * 60 * 1000);\n }\n\n return { resetTime };\n}\n\n/**\n * Detect and parse quota limit error from Claude or Codex response\n */\nexport function detectQuotaLimit(message: string | undefined | null): QuotaLimitInfo {\n if (!message || typeof message !== 'string') {\n return { detected: false };\n }\n\n // Check for quota limit patterns:\n // Claude: \"You've hit your limit · resets 8pm (America/Toronto)\"\n // Codex: \"You've hit your usage limit. ... try again at Feb 4th, 2026 1:50 AM.\"\n const claudePattern = /you'?ve hit your limit/i;\n const codexPattern = /you'?ve hit your usage limit/i;\n\n const isClaudeQuota = claudePattern.test(message) && !codexPattern.test(message);\n const isCodexQuota = codexPattern.test(message);\n\n if (!isClaudeQuota && !isCodexQuota) {\n return { detected: false };\n }\n\n const source = isCodexQuota ? 'codex' : 'claude';\n\n // Try to parse the reset time - Claude format first, then Codex format\n const parsedClaude = parseResetTime(message);\n if (parsedClaude) {\n const now = new Date();\n const sleepDurationMs = Math.max(0, parsedClaude.resetTime.getTime() - now.getTime());\n\n return {\n detected: true,\n resetTime: parsedClaude.resetTime,\n sleepDurationMs,\n timezone: parsedClaude.timezone,\n originalMessage: message,\n source,\n };\n }\n\n // Try Codex reset time format (\"try again at Feb 4th, 2026 1:50 AM\")\n const parsedCodex = parseCodexResetTime(message);\n if (parsedCodex) {\n const now = new Date();\n const sleepDurationMs = Math.max(0, parsedCodex.resetTime.getTime() - now.getTime());\n\n return {\n detected: true,\n resetTime: parsedCodex.resetTime,\n sleepDurationMs,\n timezone: 'local',\n originalMessage: message,\n source,\n };\n }\n\n // Quota limit detected but couldn't parse reset time\n // Default to 5 minutes wait\n return {\n detected: true,\n sleepDurationMs: 5 * 60 * 1000, // 5 minutes default\n originalMessage: message,\n source,\n };\n}\n\n/**\n * Format duration in human-readable form\n */\nexport function formatDuration(ms: number): string {\n const totalSeconds = Math.ceil(ms / 1000);\n const hours = Math.floor(totalSeconds / 3600);\n const minutes = Math.floor((totalSeconds % 3600) / 60);\n const seconds = totalSeconds % 60;\n\n const parts: string[] = [];\n if (hours > 0) parts.push(`${hours}h`);\n if (minutes > 0) parts.push(`${minutes}m`);\n if (seconds > 0 || parts.length === 0) parts.push(`${seconds}s`);\n\n return parts.join(' ');\n}\n\n// =============================================================================\n// Shell Backend Implementation\n// =============================================================================\n\n/**\n * Shell backend that executes scripts from ~/.juno_code/services/\n */\nexport class ShellBackend implements Backend {\n readonly type = 'shell' as const;\n readonly name = 'Shell Scripts Backend';\n\n private config: ShellBackendConfig | null = null;\n private progressCallbacks: ProgressCallback[] = [];\n private eventCounter = 0;\n private jsonBuffer = ''; // Buffer for handling partial JSON objects\n private logFilePath: string | null = null; // Path to current log file\n\n /**\n * Configure the shell backend\n */\n configure(config: ShellBackendConfig): void {\n this.config = config;\n }\n\n /**\n * Initialize the backend\n */\n async initialize(): Promise<void> {\n if (!this.config) {\n throw new Error('Shell backend not configured. Call configure() first.');\n }\n\n // Ensure services directory exists\n try {\n await fs.access(this.config.servicesPath);\n } catch (error) {\n throw new Error(\n `Services directory not found: ${this.config.servicesPath}. Please create the directory and add subagent scripts.`,\n );\n }\n\n if (this.config.debug) {\n engineLogger.info(\n `Shell backend initialized with services path: ${this.config.servicesPath}`,\n );\n }\n }\n\n /**\n * Execute a tool call request using shell scripts\n */\n async execute(request: ToolCallRequest): Promise<ToolCallResult> {\n if (!this.config) {\n throw new Error('Shell backend not configured');\n }\n\n const startTime = Date.now();\n const toolId = `shell_${request.toolName}_${startTime}`;\n\n // Extract subagent name and create log file\n const subagentType = this.extractSubagentFromToolName(request.toolName);\n try {\n this.logFilePath = await this.createLogFile(subagentType);\n } catch (error) {\n // Log creation failed - continue without file logging\n if (this.config.debug) {\n engineLogger.warn(\n `Failed to create log file, continuing without file logging: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n this.logFilePath = null;\n }\n\n // Emit tool start event\n await this.emitProgressEvent({\n sessionId: (request.metadata?.sessionId as string) || 'unknown',\n timestamp: new Date(),\n backend: 'shell',\n count: ++this.eventCounter,\n type: ProgressEventType.TOOL_START,\n content: `Starting ${request.toolName} via shell script`,\n toolId,\n metadata: {\n toolName: request.toolName,\n arguments: request.arguments,\n phase: 'initialization',\n },\n });\n\n try {\n // Find appropriate script for the subagent (already extracted above)\n const scriptPath = await this.findScriptForSubagent(subagentType);\n\n // Execute the script\n const result = await this.executeScript(scriptPath, request, toolId, subagentType);\n\n const duration = Date.now() - startTime;\n\n // Emit completion event\n await this.emitProgressEvent({\n sessionId: (request.metadata?.sessionId as string) || 'unknown',\n timestamp: new Date(),\n backend: 'shell',\n count: ++this.eventCounter,\n type: ProgressEventType.TOOL_RESULT,\n content: `${request.toolName} completed successfully (${duration}ms)`,\n toolId,\n metadata: {\n toolName: request.toolName,\n duration,\n success: result.success,\n phase: 'completion',\n },\n });\n\n const structuredResult = this.buildStructuredOutput(subagentType, result);\n\n const toolResult: Record<string, unknown> = {\n content: structuredResult.content,\n status: result.success ? ToolExecutionStatus.COMPLETED : ToolExecutionStatus.FAILED,\n startTime: new Date(startTime),\n endTime: new Date(),\n duration,\n progressEvents: [] as ProgressEvent[],\n request,\n };\n if (result.error) {\n toolResult.error = new Error(result.error);\n }\n if (structuredResult.metadata) {\n toolResult.metadata = structuredResult.metadata;\n }\n return toolResult as unknown as ToolCallResult;\n } catch (error) {\n const duration = Date.now() - startTime;\n\n // Emit error event\n await this.emitProgressEvent({\n sessionId: (request.metadata?.sessionId as string) || 'unknown',\n timestamp: new Date(),\n backend: 'shell',\n count: ++this.eventCounter,\n type: ProgressEventType.ERROR,\n content: `${request.toolName} failed: ${error instanceof Error ? error.message : String(error)}`,\n toolId,\n metadata: {\n toolName: request.toolName,\n duration,\n success: false,\n error: error instanceof Error ? error.message : String(error),\n phase: 'error',\n },\n });\n\n throw error;\n }\n }\n\n /**\n * Check if shell backend is available\n */\n async isAvailable(): Promise<boolean> {\n if (!this.config) {\n return false;\n }\n\n try {\n // Check if services directory exists\n const stats = await fs.stat(this.config.servicesPath);\n if (!stats.isDirectory()) {\n return false;\n }\n\n // Check if at least one subagent script exists\n const scripts = await this.findAvailableScripts();\n return scripts.length > 0;\n } catch (error) {\n return false;\n }\n }\n\n /**\n * Set progress callback\n */\n onProgress(callback: ProgressCallback): () => void {\n this.progressCallbacks.push(callback);\n return () => {\n const index = this.progressCallbacks.indexOf(callback);\n if (index !== -1) {\n this.progressCallbacks.splice(index, 1);\n }\n };\n }\n\n /**\n * Clean up resources\n */\n async cleanup(): Promise<void> {\n // Nothing to clean up for shell backend\n this.progressCallbacks = [];\n }\n\n // =============================================================================\n // Private Implementation Methods\n // =============================================================================\n\n /**\n * Create log file path and ensure log directory exists\n */\n private async createLogFile(subagentName: string): Promise<string> {\n // Format timestamp as YYYYMMDD_HHMMSS\n const now = new Date();\n const timestamp =\n now.getFullYear().toString() +\n (now.getMonth() + 1).toString().padStart(2, '0') +\n now.getDate().toString().padStart(2, '0') +\n '_' +\n now.getHours().toString().padStart(2, '0') +\n now.getMinutes().toString().padStart(2, '0') +\n now.getSeconds().toString().padStart(2, '0');\n\n // Create log directory path\n const logDir = path.join(this.config!.workingDirectory, '.juno_task', 'logs');\n\n // Ensure log directory exists\n try {\n await fsExtra.ensureDir(logDir);\n } catch (error) {\n if (this.config?.debug) {\n engineLogger.warn(\n `Failed to create log directory: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n throw new Error(`Failed to create log directory: ${logDir}`);\n }\n\n // Create log file path\n const logFileName = `${subagentName}_shell_${timestamp}.log`;\n const logFilePath = path.join(logDir, logFileName);\n\n if (this.config?.debug) {\n engineLogger.debug(`Created log file path: ${logFilePath}`);\n }\n\n return logFilePath;\n }\n\n /**\n * Write log entry to file\n */\n private async writeToLogFile(message: string): Promise<void> {\n if (!this.logFilePath) {\n return; // No log file configured\n }\n\n try {\n // Append to log file with timestamp\n const timestamp = new Date().toISOString();\n const logEntry = `[${timestamp}] ${message}\\n`;\n await fsExtra.appendFile(this.logFilePath, logEntry, 'utf-8');\n } catch (error) {\n // Don't throw - just log the error if debug is enabled\n if (this.config?.debug) {\n engineLogger.warn(\n `Failed to write to log file: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n }\n\n /**\n * Extract subagent type from tool name\n */\n private extractSubagentFromToolName(toolName: string): string {\n // Map tool names to subagent types\n const toolMapping: Record<string, string> = {\n claude_subagent: 'claude',\n cursor_subagent: 'cursor',\n codex_subagent: 'codex',\n gemini_subagent: 'gemini',\n pi_subagent: 'pi',\n };\n\n return toolMapping[toolName] || toolName.replace('_subagent', '');\n }\n\n /**\n * Find script for a specific subagent\n */\n private async findScriptForSubagent(subagent: string): Promise<string> {\n const possibleNames = [\n `${subagent}.py`, // Subagent-specific Python script (e.g. claude.py, codex.py)\n `${subagent}.sh`, // Subagent-specific shell script\n `subagent.py`, // Generic Python script (fallback)\n `subagent.sh`, // Generic shell script (fallback)\n ];\n\n const checkedPaths: string[] = [];\n\n for (const name of possibleNames) {\n const scriptPath = path.join(this.config!.servicesPath, name);\n checkedPaths.push(scriptPath);\n\n try {\n const stats = await fs.stat(scriptPath);\n if (stats.isFile()) {\n if (this.config!.debug) {\n engineLogger.debug(`Found script for ${subagent}: ${scriptPath}`);\n }\n return scriptPath;\n }\n } catch (error) {\n // Continue to next possibility\n if (this.config!.debug) {\n engineLogger.debug(`Script not found: ${scriptPath}`);\n }\n }\n }\n\n throw new Error(\n `No script found for subagent: ${subagent}. Checked paths: ${checkedPaths.join(', ')}`,\n );\n }\n\n /**\n * Find all available scripts in services directory\n */\n private async findAvailableScripts(): Promise<string[]> {\n try {\n const files = await fs.readdir(this.config!.servicesPath);\n const scriptFiles = files.filter((file) => file.endsWith('.py') || file.endsWith('.sh'));\n return scriptFiles;\n } catch (error) {\n return [];\n }\n }\n\n /**\n * Execute a shell script\n */\n private async executeScript(\n scriptPath: string,\n request: ToolCallRequest,\n toolId: string,\n subagentType: string,\n ): Promise<ScriptExecutionResult> {\n return new Promise(async (resolve, reject) => {\n const startTime = Date.now();\n const isPython = scriptPath.endsWith('.py');\n const isGemini = subagentType === 'gemini';\n\n // Prepare environment variables\n const env: Record<string, string | undefined> = {\n ...process.env,\n ...this.config!.environment,\n // Pass request data as environment variables\n JUNO_INSTRUCTION: String(request.arguments?.instruction ?? ''),\n JUNO_PROJECT_PATH: String(request.arguments?.project_path ?? this.config!.workingDirectory),\n JUNO_MODEL: String(request.arguments?.model ?? ''),\n JUNO_ITERATION: String(request.arguments?.iteration ?? 1),\n JUNO_TOOL_ID: toolId,\n };\n\n if (isGemini) {\n env.GEMINI_OUTPUT_FORMAT = env.GEMINI_OUTPUT_FORMAT || 'stream-json';\n }\n\n // Capture file for structured subagent responses (claude.py, pi.py, codex.py support)\n let captureDir: string | null = null;\n let capturePath: string | null = null;\n if (subagentType === 'claude' || subagentType === 'pi' || subagentType === 'codex') {\n try {\n captureDir = await fs.mkdtemp(path.join(os.tmpdir(), 'juno-shell-'));\n capturePath = path.join(captureDir, `subagent_${toolId}.json`);\n env.JUNO_SUBAGENT_CAPTURE_PATH = capturePath;\n } catch (error) {\n if (this.config?.debug) {\n engineLogger.warn(\n `Failed to prepare subagent capture path: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n }\n\n // Build command arguments for the script\n const command = isPython ? 'python3' : 'bash';\n const args = [scriptPath];\n\n // For Python scripts, add the prompt as -p argument\n if (isPython && request.arguments?.instruction) {\n args.push('-p', String(request.arguments.instruction));\n }\n\n // For Python scripts, add the model as -m argument if provided\n if (isPython && request.arguments?.model) {\n args.push('-m', String(request.arguments.model));\n }\n\n // For Gemini, force stream-json output format by default to preserve headless parity\n if (isPython && isGemini) {\n args.push('--output-format', env.GEMINI_OUTPUT_FORMAT || 'stream-json');\n }\n\n // For Python scripts, add the agents configuration if provided\n if (isPython && request.arguments?.agents) {\n args.push('--agents', String(request.arguments.agents));\n }\n\n // For Python scripts, add available tools from built-in set if provided (--tools)\n if (isPython && request.arguments?.tools && Array.isArray(request.arguments.tools)) {\n args.push('--tools');\n args.push(...(request.arguments.tools as string[]));\n }\n\n // For Python scripts, add permission-based allowed tools if provided (--allowedTools)\n if (\n isPython &&\n request.arguments?.allowedTools &&\n Array.isArray(request.arguments.allowedTools)\n ) {\n args.push('--allowedTools');\n args.push(...(request.arguments.allowedTools as string[]));\n }\n\n // For Python scripts, add append allowed tools if provided (--appendAllowedTools)\n if (\n isPython &&\n request.arguments?.appendAllowedTools &&\n Array.isArray(request.arguments.appendAllowedTools)\n ) {\n args.push('--appendAllowedTools');\n args.push(...(request.arguments.appendAllowedTools as string[]));\n }\n\n // For Python scripts, add disallowed tools if provided (--disallowedTools)\n if (\n isPython &&\n request.arguments?.disallowedTools &&\n Array.isArray(request.arguments.disallowedTools)\n ) {\n args.push('--disallowedTools');\n args.push(...(request.arguments.disallowedTools as string[]));\n }\n\n // For Python scripts, add thinking level if provided (--thinking LEVEL)\n if (isPython && request.arguments?.thinking) {\n args.push('--thinking', String(request.arguments.thinking));\n }\n\n // For Python scripts, add resume flag if provided (--resume SESSION_ID)\n if (isPython && request.arguments?.resume) {\n args.push('--resume', String(request.arguments.resume));\n }\n\n // For Python scripts, add continue flag if provided (--continue)\n if (isPython && request.arguments?.continueConversation) {\n args.push('--continue');\n }\n\n // For Pi subagent, explicitly pass --cd for working directory\n if (isPython && subagentType === 'pi' && request.arguments?.project_path) {\n args.push('--cd', String(request.arguments.project_path));\n }\n\n // For Pi subagent, forward live mode flag when requested\n if (isPython && subagentType === 'pi' && request.arguments?.live === true) {\n args.push('--live');\n }\n\n // For Python scripts, pass verbose flag if verbose mode is enabled\n if (isPython && this.config!.debug) {\n args.push('--verbose');\n }\n\n if (this.config!.debug) {\n // Show command with truncated prompt for readability\n const displayArgs = args.map((a, i) => {\n if (i > 0 && args[i - 1] === '-p' && a.length > 200) {\n return `\"${a.substring(0, 200)}...\" (${a.length} chars)`;\n }\n return a;\n });\n engineLogger.debug(`Executing script: ${command} ${displayArgs.join(' ')}`);\n engineLogger.debug(`Working directory: ${this.config!.workingDirectory}`);\n engineLogger.debug(`Subagent type: ${subagentType}`);\n engineLogger.debug(\n `Environment variables: ${Object.keys(env)\n .filter((k) => k.startsWith('JUNO_') || k.startsWith('PI_'))\n .join(', ')}`,\n );\n }\n\n const isPiLiveMode = isPython && subagentType === 'pi' && request.arguments?.live === true;\n const shouldAttachLiveTerminal = isPiLiveMode && process.stdout.isTTY === true;\n\n if (this.config!.debug && isPiLiveMode) {\n engineLogger.debug(\n `Pi live mode stdio: ${shouldAttachLiveTerminal ? 'inherit (interactive TTY or stdout-tty fallback)' : 'pipe (headless/non-TTY)'}`,\n );\n }\n\n // Spawn the process\n const child: ChildProcess = spawn(command, args, {\n env,\n cwd: this.config!.workingDirectory,\n stdio: shouldAttachLiveTerminal ? 'inherit' : ['pipe', 'pipe', 'pipe'],\n });\n\n // Close stdin immediately for headless mode to avoid waiting for input.\n // In live Pi mode with terminal passthrough (including stdout-tty fallback),\n // keep inherited stdin open so pi.py can reattach /dev/tty when needed.\n if (!shouldAttachLiveTerminal && child.stdin) {\n child.stdin.end();\n }\n\n let stdout = '';\n let stderr = '';\n let isProcessKilled = false;\n\n // Handle stdout (JSON streaming or TEXT streaming)\n child.stdout?.on('data', (chunk: Buffer) => {\n const data = chunk.toString();\n stdout += data;\n\n if (this.config!.debug) {\n engineLogger.debug(`Script stdout chunk: ${data.length} bytes`);\n }\n\n // Try to parse and emit streaming events (handles both JSON and TEXT formats)\n if (this.config!.enableJsonStreaming !== false) {\n try {\n this.parseAndEmitStreamingEvents(\n data,\n (request.metadata?.sessionId as string) || 'unknown',\n toolId,\n );\n } catch (error) {\n if (this.config!.debug) {\n engineLogger.warn(\n `Streaming parse error: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n }\n });\n\n // Handle stderr - stream as progress events for user visibility\n child.stderr?.on('data', (chunk: Buffer) => {\n const errorData = chunk.toString();\n stderr += errorData;\n\n if (this.config!.debug) {\n engineLogger.debug(`Script stderr: ${errorData}`);\n }\n\n // Emit stderr lines as progress events so errors are visible during execution\n const lines = errorData.split('\\n');\n for (const line of lines) {\n if (!line.trim()) continue;\n this.emitProgressEvent({\n sessionId: (request.metadata?.sessionId as string) || 'unknown',\n timestamp: new Date(),\n backend: 'shell',\n count: ++this.eventCounter,\n type: ProgressEventType.THINKING,\n content: line,\n toolId,\n metadata: {\n format: 'text',\n source: 'stderr',\n raw: true,\n },\n }).catch((error) => {\n if (this.config?.debug) {\n engineLogger.warn(\n `Failed to emit stderr progress event: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n });\n }\n });\n\n // Handle process completion\n child.on('close', (exitCode) => {\n void (async () => {\n if (isProcessKilled) return; // Prevent double resolution\n\n const duration = Date.now() - startTime;\n const success = exitCode === 0;\n\n let subAgentResponse: any;\n if (capturePath) {\n try {\n const captured = await fs.readFile(capturePath, 'utf-8');\n if (captured.trim()) {\n subAgentResponse = JSON.parse(captured);\n }\n } catch (error) {\n // ENOENT is expected when the subagent exits without producing a result event\n const isNotFound = (error as NodeJS.ErrnoException)?.code === 'ENOENT';\n if (!isNotFound && this.config?.debug) {\n engineLogger.warn(\n `Failed to read subagent capture: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n } finally {\n if (captureDir) {\n try {\n await fs.rm(captureDir, { recursive: true, force: true });\n } catch (cleanupError) {\n if (this.config?.debug) {\n engineLogger.warn(\n `Failed to clean capture directory: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`,\n );\n }\n }\n }\n }\n }\n\n if (this.config!.debug) {\n engineLogger.debug(\n `Script execution completed with exit code: ${exitCode}, duration: ${duration}ms`,\n );\n engineLogger.debug(`Stdout length: ${stdout.length}, Stderr length: ${stderr.length}`);\n }\n\n const execResult: ScriptExecutionResult = {\n success,\n output: stdout,\n exitCode: exitCode || 0,\n duration,\n };\n if (stderr) {\n execResult.error = stderr;\n }\n if (subAgentResponse) {\n execResult.subAgentResponse = subAgentResponse;\n }\n resolve(execResult);\n })();\n });\n\n // Handle process errors\n child.on('error', (error) => {\n if (isProcessKilled) return; // Prevent double resolution\n\n if (this.config!.debug) {\n engineLogger.error(`Script execution error: ${error.message}`);\n }\n reject(new Error(`Failed to execute script: ${error.message}`));\n });\n\n // Apply timeout if configured\n const timeout = this.config!.timeout || 43200000; // 12 hours default for long-running operations\n const timer = setTimeout(() => {\n if (isProcessKilled) return;\n\n isProcessKilled = true;\n if (this.config!.debug) {\n engineLogger.warn(`Script execution timed out after ${timeout}ms, killing process`);\n }\n\n child.kill('SIGTERM');\n\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\n reject(new Error(`Script execution timed out after ${timeout}ms`));\n }, timeout);\n\n // Clear timeout when process completes\n child.on('close', () => {\n clearTimeout(timer);\n });\n\n child.on('error', () => {\n clearTimeout(timer);\n });\n });\n }\n\n /**\n * Build a structured, JSON-parsable result payload for programmatic capture while\n * preserving the shell backend's existing on-screen streaming behavior.\n */\n private buildStructuredOutput(\n subagentType: string,\n result: ScriptExecutionResult,\n ): { content: string; metadata?: ToolExecutionMetadata } {\n if (subagentType === 'claude') {\n const claudeEvent = result.subAgentResponse ?? this.extractLastJsonEvent(result.output);\n const isError = claudeEvent?.is_error ?? claudeEvent?.subtype === 'error' ?? !result.success;\n\n // Check for quota limit error\n const resultText = claudeEvent?.result ?? claudeEvent?.error ?? '';\n const quotaLimitInfo = detectQuotaLimit(resultText);\n\n const structuredPayload = {\n type: 'result',\n subtype: claudeEvent?.subtype || (isError ? 'error' : 'success'),\n is_error: isError,\n result: claudeEvent?.result ?? claudeEvent?.error ?? claudeEvent?.content ?? result.output,\n error: claudeEvent?.error,\n stderr: result.error,\n datetime: claudeEvent?.datetime,\n counter: claudeEvent?.counter,\n session_id: claudeEvent?.session_id,\n num_turns: claudeEvent?.num_turns,\n duration_ms: claudeEvent?.duration_ms ?? result.duration,\n exit_code: result.exitCode,\n total_cost_usd: claudeEvent?.total_cost_usd,\n usage: claudeEvent?.usage,\n modelUsage: claudeEvent?.modelUsage || claudeEvent?.model_usage || {},\n permission_denials: claudeEvent?.permission_denials || [],\n uuid: claudeEvent?.uuid,\n sub_agent_response: claudeEvent,\n // Add quota limit info if detected\n ...(quotaLimitInfo.detected && { quota_limit: quotaLimitInfo }),\n };\n\n const metadataObj: Record<string, unknown> = {\n structuredOutput: true,\n contentType: 'application/json',\n rawOutput: result.output,\n };\n if (claudeEvent) {\n metadataObj.subAgentResponse = claudeEvent;\n }\n if (quotaLimitInfo.detected) {\n metadataObj.quotaLimitInfo = quotaLimitInfo;\n }\n const metadata = metadataObj as ToolExecutionMetadata;\n\n return {\n content: JSON.stringify(structuredPayload),\n metadata,\n };\n }\n\n // Check for Codex quota limit errors in output\n if (subagentType === 'codex') {\n // Codex streams JSON events; look for error/turn.failed events with quota messages\n const codexQuotaMessage = this.extractCodexQuotaMessage(result.output, result.error);\n if (codexQuotaMessage) {\n const quotaLimitInfo = detectQuotaLimit(codexQuotaMessage);\n if (quotaLimitInfo.detected) {\n const metadata: ToolExecutionMetadata = {\n structuredOutput: true,\n contentType: 'application/json',\n rawOutput: result.output,\n quotaLimitInfo,\n };\n const structuredPayload = {\n type: 'result',\n subtype: 'error',\n is_error: true,\n result: codexQuotaMessage,\n error: codexQuotaMessage,\n exit_code: result.exitCode,\n duration_ms: result.duration,\n quota_limit: quotaLimitInfo,\n };\n return {\n content: JSON.stringify(structuredPayload),\n metadata,\n };\n }\n }\n }\n\n // For Codex subagent: extract structured result from capture file or last JSON event\n if (subagentType === 'codex') {\n const codexEvent = result.subAgentResponse ?? this.extractLastJsonEvent(result.output);\n if (codexEvent) {\n const isError = codexEvent.is_error ?? !result.success;\n // Extract message text from agent_message event format\n // Codex events can be: {msg: {message: \"...\"}} (legacy) or {item: {text: \"...\"}} (item.completed)\n const msgPayload = codexEvent.msg ?? codexEvent;\n const itemPayload =\n typeof codexEvent.item === 'object' && codexEvent.item ? codexEvent.item : undefined;\n const messageText =\n msgPayload.message ??\n msgPayload.text ??\n itemPayload?.text ??\n itemPayload?.message ??\n msgPayload.content ??\n result.output;\n const structuredPayload = {\n type: 'result',\n subtype: codexEvent.subtype || (isError ? 'error' : 'success'),\n is_error: isError,\n result: messageText,\n error: isError ? messageText : undefined,\n stderr: result.error,\n exit_code: result.exitCode,\n duration_ms: result.duration,\n sub_agent_response: codexEvent,\n };\n const metadata: ToolExecutionMetadata = {\n ...(codexEvent ? { subAgentResponse: codexEvent } : undefined),\n structuredOutput: true,\n contentType: 'application/json',\n rawOutput: result.output,\n };\n return {\n content: JSON.stringify(structuredPayload),\n metadata,\n };\n }\n }\n\n // For Pi subagent: extract structured result from capture file or last JSON event\n if (subagentType === 'pi') {\n const piEvent = result.subAgentResponse ?? this.extractLastJsonEvent(result.output);\n if (piEvent) {\n // Extract result text: prefer .result, fall back to .messages array (agent_end events)\n let resultText: string | undefined = piEvent.result;\n if (!resultText && Array.isArray(piEvent.messages)) {\n // agent_end event: extract last assistant message text\n for (let i = piEvent.messages.length - 1; i >= 0; i--) {\n const msg = piEvent.messages[i];\n if (msg?.role === 'assistant') {\n // Extract text from content array\n const content = msg.content;\n if (typeof content === 'string') {\n resultText = content;\n } else if (Array.isArray(content)) {\n const texts: string[] = [];\n for (const item of content) {\n if (typeof item === 'string') texts.push(item);\n else if (item?.type === 'text' && typeof item.text === 'string')\n texts.push(item.text);\n }\n resultText = texts.join('\\n');\n }\n if (resultText) break;\n }\n }\n }\n if (resultText) {\n const isError = piEvent.is_error ?? !result.success;\n // Sanitize piEvent: strip bulky messages array and redundant type from sub_agent_response\n // to reduce token usage in the structured output\n const sanitizedPiEvent = { ...piEvent };\n delete sanitizedPiEvent.messages;\n // Also sanitize nested sub_agent_response if present (from pi.py capture)\n if (\n sanitizedPiEvent.sub_agent_response &&\n typeof sanitizedPiEvent.sub_agent_response === 'object'\n ) {\n const inner = { ...sanitizedPiEvent.sub_agent_response };\n delete inner.messages;\n delete inner.type;\n sanitizedPiEvent.sub_agent_response = inner;\n }\n const usage = piEvent.usage;\n const totalCostUsd =\n typeof piEvent.total_cost_usd === 'number'\n ? piEvent.total_cost_usd\n : typeof usage?.cost?.total === 'number'\n ? usage.cost.total\n : undefined;\n\n const structuredPayload = {\n type: 'result',\n subtype: piEvent.subtype || (isError ? 'error' : 'success'),\n is_error: isError,\n result: resultText,\n error: piEvent.error,\n stderr: result.error,\n session_id: piEvent.session_id,\n exit_code: result.exitCode,\n duration_ms: piEvent.duration_ms ?? result.duration,\n total_cost_usd: totalCostUsd,\n usage,\n sub_agent_response: sanitizedPiEvent,\n };\n const metadata: ToolExecutionMetadata = {\n ...(piEvent ? { subAgentResponse: piEvent } : undefined),\n structuredOutput: true,\n contentType: 'application/json',\n rawOutput: result.output,\n };\n return {\n content: JSON.stringify(structuredPayload),\n metadata,\n };\n }\n }\n }\n\n // For generic subagents: build structured error output on failure\n if (!result.success) {\n const errorMessage = result.error?.trim() || result.output?.trim() || 'Unknown error';\n const structuredPayload = {\n type: 'result',\n subtype: 'error',\n is_error: true,\n result: errorMessage,\n error: errorMessage,\n stderr: result.error,\n exit_code: result.exitCode,\n duration_ms: result.duration,\n };\n const metadata: ToolExecutionMetadata = {\n structuredOutput: true,\n contentType: 'application/json',\n rawOutput: result.output,\n };\n return {\n content: JSON.stringify(structuredPayload),\n metadata,\n };\n }\n\n const returnValue: { content: string; metadata?: ToolExecutionMetadata } = {\n content: result.output,\n };\n if (result.metadata) {\n returnValue.metadata = result.metadata as ToolExecutionMetadata;\n }\n return returnValue;\n }\n\n /**\n * Extract quota limit message from Codex stream output\n * Codex outputs JSON events like:\n * {\"type\": \"error\", \"message\": \"You've hit your usage limit...\"}\n * {\"type\": \"turn.failed\", \"error\": {\"message\": \"You've hit your usage limit...\"}}\n */\n private extractCodexQuotaMessage(output: string, stderr?: string): string | null {\n const sources = [output, stderr].filter(Boolean);\n\n for (const source of sources) {\n const lines = source!\n .split('\\n')\n .map((l) => l.trim())\n .filter(Boolean);\n for (const line of lines) {\n try {\n const parsed = JSON.parse(line);\n // Check type=error events\n if (parsed?.type === 'error' && parsed?.message) {\n if (/you'?ve hit your usage limit/i.test(parsed.message)) {\n return parsed.message;\n }\n }\n // Check type=turn.failed events\n if (parsed?.type === 'turn.failed' && parsed?.error?.message) {\n if (/you'?ve hit your usage limit/i.test(parsed.error.message)) {\n return parsed.error.message;\n }\n }\n } catch {\n // Not JSON, check as plain text\n if (/you'?ve hit your usage limit/i.test(line)) {\n return line;\n }\n }\n }\n }\n\n return null;\n }\n\n /**\n * Extract the last valid JSON object from a script's stdout to use as a structured payload fallback.\n */\n private extractLastJsonEvent(output: string): any | null {\n if (!output) {\n return null;\n }\n\n const lines = output\n .split('\\n')\n .map((line) => line.trim())\n .filter(Boolean);\n\n for (let i = lines.length - 1; i >= 0; i--) {\n try {\n const parsed = JSON.parse(lines[i]!);\n if (parsed && typeof parsed === 'object') {\n return parsed;\n }\n } catch {\n // Ignore parse failures and continue scanning earlier lines\n }\n }\n\n return null;\n }\n\n /**\n * Parse streaming events from script output\n * Handles both JSON format (Claude) and TEXT format (Codex)\n *\n * Strategy:\n * 1. Try to parse each line as JSON first (for Claude)\n * 2. If JSON parsing fails, treat as TEXT streaming (for Codex and other text-based subagents)\n * 3. Emit all text lines (including whitespace-only) as progress events for real-time display\n */\n private parseAndEmitStreamingEvents(data: string, sessionId: string, toolId?: string): void {\n // Handle partial lines by maintaining a buffer\n if (!this.jsonBuffer) {\n this.jsonBuffer = '';\n }\n\n this.jsonBuffer += data;\n\n const streamToolId = toolId || `stream_${Date.now()}`;\n\n // Split by lines, but keep the last potentially incomplete line in buffer\n const lines = this.jsonBuffer.split('\\n');\n this.jsonBuffer = lines.pop() || ''; // Keep last incomplete line\n\n // Process complete lines\n for (const line of lines) {\n const rawLine = line.endsWith('\\r') ? line.slice(0, -1) : line;\n if (!rawLine) continue;\n\n const hasNonWhitespace = rawLine.trim().length > 0;\n\n // Preserve whitespace-only lines (tabs/spaces) as-is for accurate pretty output rendering\n if (!hasNonWhitespace) {\n this.emitProgressEvent({\n sessionId,\n timestamp: new Date(),\n backend: 'shell',\n count: ++this.eventCounter,\n type: ProgressEventType.THINKING,\n content: rawLine,\n toolId: streamToolId,\n metadata: {\n format: 'text',\n raw: true,\n },\n }).catch((error) => {\n if (this.config?.debug) {\n engineLogger.warn(\n `Failed to emit whitespace-only streaming event: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n });\n continue;\n }\n\n const trimmedLine = rawLine.trim();\n\n // Try JSON parsing first (for Claude and other JSON-outputting subagents)\n let isJsonParsed = false;\n try {\n const jsonEvent = JSON.parse(trimmedLine);\n\n // Detect format: Claude CLI or generic StreamingEvent\n let progressEvent: ProgressEvent;\n\n if (this.isClaudeCliEvent(jsonEvent)) {\n // Handle Claude CLI specific format\n // Pass the original trimmedLine for raw JSON output mode\n progressEvent = this.convertClaudeEventToProgress(jsonEvent, sessionId, rawLine, streamToolId);\n isJsonParsed = true;\n } else if (this.isGenericStreamingEvent(jsonEvent)) {\n // Handle generic StreamingEvent format\n progressEvent = {\n sessionId,\n timestamp: jsonEvent.timestamp ? new Date(jsonEvent.timestamp) : new Date(),\n backend: 'shell',\n count: ++this.eventCounter,\n type: jsonEvent.type as ProgressEventType,\n content: jsonEvent.content,\n toolId: streamToolId,\n metadata: jsonEvent.metadata,\n };\n isJsonParsed = true;\n } else {\n // Unknown JSON format, treat as text below\n if (this.config?.debug) {\n engineLogger.debug(`Unknown JSON format, treating as text: ${trimmedLine}`);\n }\n }\n\n // Emit the progress event if JSON was successfully parsed\n if (isJsonParsed) {\n this.emitProgressEvent(progressEvent!).catch((error) => {\n if (this.config?.debug) {\n engineLogger.warn(\n `Failed to emit progress event: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n });\n }\n } catch (error) {\n // Not JSON - this is expected for text-based subagents like Codex\n // Treat as TEXT streaming and emit as thinking event\n isJsonParsed = false;\n }\n\n // If not JSON, handle as TEXT streaming (for Codex and other text-based outputs)\n if (!isJsonParsed && trimmedLine.length > 0) {\n this.emitProgressEvent({\n sessionId,\n timestamp: new Date(),\n backend: 'shell',\n count: ++this.eventCounter,\n type: ProgressEventType.THINKING,\n content: rawLine,\n toolId: streamToolId,\n metadata: {\n format: 'text',\n raw: true,\n },\n }).catch((error) => {\n if (this.config?.debug) {\n engineLogger.warn(\n `Failed to emit text streaming event: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n });\n }\n }\n }\n\n /**\n * Check if JSON event is Claude CLI format\n */\n private isClaudeCliEvent(event: any): boolean {\n return (\n event &&\n typeof event === 'object' &&\n event.type &&\n ['system', 'assistant', 'result'].includes(event.type)\n );\n }\n\n /**\n * Check if JSON event is generic StreamingEvent format\n */\n private isGenericStreamingEvent(event: any): boolean {\n return event && typeof event === 'object' && event.type && event.content !== undefined;\n }\n\n /**\n * Convert Claude CLI event to ProgressEvent format\n */\n private convertClaudeEventToProgress(\n event: any,\n sessionId: string,\n originalLine?: string,\n toolId?: string,\n ): ProgressEvent {\n let type: ProgressEventType;\n let content: string;\n const metadata: Record<string, any> = {};\n const eventToolId = toolId || `claude_${Date.now()}`;\n\n // If outputRawJson is enabled, pass the original JSON line for jq-style formatting\n // This allows the progress display to format it with colors and indentation\n if (this.config?.outputRawJson && originalLine) {\n // Determine event type based on Claude CLI format\n switch (event.type) {\n case 'system':\n type = ProgressEventType.TOOL_START;\n break;\n case 'assistant':\n type = ProgressEventType.THINKING;\n break;\n case 'result':\n type = event.is_error || event.subtype === 'error' ? ProgressEventType.ERROR : ProgressEventType.TOOL_RESULT;\n break;\n default:\n type = ProgressEventType.THINKING;\n }\n\n // Pass the raw JSON for jq-style formatting in the display layer\n content = originalLine;\n metadata.rawJsonOutput = true;\n metadata.originalType = event.type;\n metadata.parsedEvent = event; // Keep parsed version for metadata access\n\n return {\n sessionId,\n timestamp: new Date(),\n backend: 'shell',\n count: ++this.eventCounter,\n type,\n content,\n toolId: eventToolId,\n metadata,\n };\n }\n\n // Original simplified format (when outputRawJson is false/undefined)\n switch (event.type) {\n case 'system':\n // System/init event\n type = ProgressEventType.TOOL_START;\n content = `Initializing Claude session`;\n metadata.subtype = event.subtype;\n metadata.sessionId = event.session_id;\n metadata.model = event.model;\n metadata.tools = event.tools;\n metadata.cwd = event.cwd;\n break;\n\n case 'assistant':\n // Assistant message event\n type = ProgressEventType.THINKING;\n // Check if this is pretty-formatted JSON from claude.py\n if (!event.message && (event.content !== undefined || event.tool_use !== undefined)) {\n // Pretty-formatted: { \"type\": \"assistant\", \"datetime\": \"...\", \"content\": \"...\", \"counter\": \"...\" }\n // or with tool_use: { \"type\": \"assistant\", \"datetime\": \"...\", \"tool_use\": {...}, \"counter\": \"...\" }\n if (event.content && typeof event.content === 'string') {\n content = event.content;\n } else if (event.tool_use) {\n // For tool_use, show the tool name and input\n content = `Tool: ${event.tool_use.name}`;\n metadata.tool_use = event.tool_use; // Preserve tool_use data in metadata\n } else {\n content = ''; // Empty content (content was explicitly set to undefined/empty)\n }\n } else if (event.message?.content && Array.isArray(event.message.content)) {\n // Original format: Extract content from message.content array\n const textContent = event.message.content.find((c: any) => c.type === 'text');\n content = textContent?.text || 'Processing...';\n } else {\n content = 'Processing...';\n }\n metadata.messageId = event.message?.id;\n metadata.model = event.message?.model;\n metadata.usage = event.message?.usage;\n metadata.sessionId = event.session_id;\n metadata.datetime = event.datetime; // Preserve datetime from pretty format\n metadata.counter = event.counter; // Preserve counter from pretty format\n break;\n\n case 'result':\n // Result event\n if (event.is_error || event.subtype === 'error') {\n type = ProgressEventType.ERROR;\n content = event.result || event.error || 'Execution failed';\n } else {\n type = ProgressEventType.TOOL_RESULT;\n content = event.result || 'Execution completed';\n }\n metadata.subtype = event.subtype;\n metadata.duration = event.duration_ms;\n metadata.cost = event.total_cost_usd;\n metadata.usage = event.usage;\n metadata.sessionId = event.session_id;\n break;\n\n default:\n // Fallback to thinking\n type = ProgressEventType.THINKING;\n content = JSON.stringify(event);\n metadata.unknownType = event.type;\n }\n\n return {\n sessionId,\n timestamp: new Date(),\n backend: 'shell',\n count: ++this.eventCounter,\n type,\n content,\n toolId: eventToolId,\n metadata,\n };\n }\n\n\n /**\n * Emit progress event to all callbacks\n */\n private async emitProgressEvent(event: ProgressEvent): Promise<void> {\n // Write to log file first\n if (this.logFilePath) {\n const logMessage = `[${event.type}] ${event.content}${event.metadata ? ' | metadata: ' + JSON.stringify(event.metadata) : ''}`;\n await this.writeToLogFile(logMessage);\n }\n\n // Then emit to callbacks for screen display\n for (const callback of this.progressCallbacks) {\n try {\n await callback(event);\n } catch (error) {\n // Don't break on callback errors\n if (this.config?.debug) {\n engineLogger.warn(\n `Progress callback error: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n }\n }\n}\n","/**\n * juno-code - TypeScript implementation of juno-code CLI tool\n *\n * Main entry point for the library exports\n */\n\n// Core exports\nexport * from './core/config';\nexport * from './templates/default-hooks';\nexport * from './core/engine';\nexport * from './core/session';\n// Utility exports (excluding validateConfig to avoid conflicts)\nexport * from './utils/environment';\nexport {\n executeHook,\n executeHooks,\n validateHooksConfig,\n type HooksConfig,\n type HookExecutionContext,\n type HookExecutionOptions,\n type HookExecutionResult,\n type CommandExecutionResult,\n} from './utils/hooks';\nexport {\n SubagentSchema,\n LogLevelSchema,\n SessionStatusSchema,\n IterationsSchema,\n ModelSchema,\n ConfigValidationSchema,\n validateSubagent,\n validateModel,\n validateIterations,\n validateLogLevel,\n validateEnvironmentVars,\n} from './utils/validation';\n\n// Type exports (consolidated to avoid conflicts)\nexport * from './types';\n\n// Version information\nexport { version } from './version';\n","/**\n * Core configuration module for juno-code\n *\n * Provides comprehensive configuration management with multi-source loading,\n * validation, and environment variable support.\n *\n * @module core/config\n */\n\nimport { z } from 'zod';\nimport * as path from 'node:path';\nimport * as nodeFs from 'node:fs';\nimport { promises as fsPromises } from 'node:fs';\nimport * as yaml from 'js-yaml';\nimport fs from 'fs-extra';\nimport type { JunoTaskConfig } from '../types/index';\nimport { getDefaultHooks } from '../templates/default-hooks.js';\nimport { SUBAGENT_DEFAULT_MODELS } from './subagent-models.js';\n\n/**\n * Environment variable mapping for configuration options\n * All config options can be set via JUNO_CODE_* environment variables\n * Uses JUNO_CODE_* environment variables\n */\nexport const ENV_VAR_MAPPING = {\n // Core settings\n JUNO_CODE_DEFAULT_SUBAGENT: 'defaultSubagent',\n JUNO_CODE_DEFAULT_BACKEND: 'defaultBackend',\n JUNO_CODE_DEFAULT_MAX_ITERATIONS: 'defaultMaxIterations',\n JUNO_CODE_DEFAULT_MODEL: 'defaultModel',\n\n // Logging settings\n JUNO_CODE_LOG_LEVEL: 'logLevel',\n JUNO_CODE_LOG_FILE: 'logFile',\n JUNO_CODE_VERBOSE: 'verbose',\n JUNO_CODE_QUIET: 'quiet',\n\n // MCP settings\n JUNO_CODE_MCP_TIMEOUT: 'mcpTimeout',\n JUNO_CODE_MCP_RETRIES: 'mcpRetries',\n JUNO_CODE_MCP_SERVER_PATH: 'mcpServerPath',\n JUNO_CODE_MCP_SERVER_NAME: 'mcpServerName',\n\n // Hook settings\n JUNO_CODE_HOOK_COMMAND_TIMEOUT: 'hookCommandTimeout',\n\n // Quota/hourly limit settings\n JUNO_CODE_ON_HOURLY_LIMIT: 'onHourlyLimit',\n\n // TUI settings\n JUNO_CODE_INTERACTIVE: 'interactive',\n JUNO_CODE_HEADLESS_MODE: 'headlessMode',\n\n // Paths\n JUNO_CODE_WORKING_DIRECTORY: 'workingDirectory',\n JUNO_CODE_SESSION_DIRECTORY: 'sessionDirectory',\n} as const;\n\n/**\n * Zod schema for validating subagent types\n */\nconst SubagentTypeSchema = z.enum(['claude', 'cursor', 'codex', 'gemini', 'pi']);\n\n/**\n * Zod schema for validating backend types\n */\nconst BackendTypeSchema = z.enum(['shell']);\n\n/**\n * Zod schema for validating log levels\n */\nconst LogLevelSchema = z.enum(['error', 'warn', 'info', 'debug', 'trace']);\n\n/**\n * Zod schema for validating on-hourly-limit behavior\n */\nconst OnHourlyLimitSchema = z.enum(['wait', 'raise']);\n\n/**\n * Zod schema for validating hook types\n */\nconst HookTypeSchema = z.enum([\n 'START_RUN',\n 'START_ITERATION',\n 'END_ITERATION',\n 'END_RUN',\n 'ON_STALE',\n]);\n\n/**\n * Zod schema for validating individual hook configuration\n */\nconst HookSchema = z.object({\n commands: z.array(z.string()).describe('List of bash commands to execute for this hook'),\n});\n\n/**\n * Zod schema for validating hooks configuration\n * Maps hook types to their respective configurations\n */\nconst HooksSchema = z.record(HookTypeSchema, HookSchema).optional();\n\n/**\n * Zod schema for validating JunoTaskConfig\n * Provides runtime validation with detailed error messages\n */\nexport const JunoTaskConfigSchema = z\n .object({\n // Core settings\n defaultSubagent: SubagentTypeSchema.describe('Default subagent to use for task execution'),\n\n defaultBackend: BackendTypeSchema.describe('Default backend to use for task execution'),\n\n defaultMaxIterations: z\n .number()\n .int()\n .min(1)\n .max(1000)\n .describe('Default maximum number of iterations for task execution'),\n\n defaultModel: z.string().optional().describe('Default model to use for the subagent'),\n\n defaultModels: z\n .record(SubagentTypeSchema, z.string())\n .optional()\n .describe('Optional per-subagent default model overrides'),\n\n // Project metadata\n mainTask: z.string().optional().describe('Main task objective for the project'),\n\n // Logging settings\n logLevel: LogLevelSchema.describe('Logging level for the application'),\n\n logFile: z.string().optional().describe('Path to log file (optional)'),\n\n verbose: z.preprocess(\n (val) => {\n if (val === true) return 1;\n if (val === false) return 0;\n if (typeof val === 'string') {\n const lower = val.toLowerCase().trim();\n if (lower === 'true' || lower === 'yes') return 1;\n if (lower === 'false' || lower === 'no') return 0;\n }\n return val;\n },\n z.number().int().min(0).max(2),\n ).describe('Verbosity level: 0=quiet, 1=normal+helping texts (default), 2=debug+hooks'),\n\n quiet: z.boolean().describe('Enable quiet mode (minimal output)'),\n\n // MCP settings\n mcpTimeout: z\n .number()\n .int()\n .min(1000)\n // Allow very large timeouts to satisfy real-world workflows and user tests\n // User feedback requires accepting values like 6,000,000 ms (100 minutes)\n .max(86400000) // up to 24 hours\n .describe('MCP server timeout in milliseconds'),\n\n mcpRetries: z.number().int().min(0).max(10).describe('Number of retries for MCP operations'),\n\n mcpServerPath: z\n .string()\n .optional()\n .describe('Path to MCP server executable (auto-discovered if not specified)'),\n\n mcpServerName: z\n .string()\n .optional()\n .describe('Named MCP server to connect to'),\n\n // Hook settings\n hookCommandTimeout: z\n .number()\n .int()\n .min(1000)\n .max(3600000) // up to 1 hour\n .optional()\n .describe(\n 'Timeout for individual hook commands in milliseconds (default: 300000 = 5 minutes)',\n ),\n\n // Quota/hourly limit settings\n onHourlyLimit: OnHourlyLimitSchema.describe(\n 'Behavior when Claude hourly quota limit is reached: \"wait\" to sleep until reset, \"raise\" to exit immediately',\n ),\n\n // TUI settings\n interactive: z.boolean().describe('Enable interactive mode'),\n\n headlessMode: z.boolean().describe('Enable headless mode (no TUI)'),\n\n // Paths\n workingDirectory: z.string().describe('Working directory for task execution'),\n\n sessionDirectory: z.string().describe('Directory for storing session data'),\n\n // Project environment bootstrap\n envFilePath: z\n .string()\n .optional()\n .describe(\n 'Path to the project env file loaded before execution (relative to project root or absolute)',\n ),\n\n envFileCopied: z\n .boolean()\n .optional()\n .describe('Tracks whether configured env file has been initialized from .env.juno'),\n\n // Hooks configuration\n hooks: HooksSchema.describe(\n 'Hook system configuration for executing commands at specific lifecycle events',\n ),\n\n // Skip hooks execution\n skipHooks: z.boolean().optional().describe('Skip execution of all lifecycle hooks when true'),\n })\n .strict();\n\n/**\n * Default configuration values\n * These are used as fallbacks when no other configuration is provided\n */\nexport const DEFAULT_CONFIG: JunoTaskConfig = {\n // Core settings\n defaultSubagent: 'claude',\n defaultBackend: 'shell',\n defaultMaxIterations: 1,\n defaultModels: { ...SUBAGENT_DEFAULT_MODELS },\n\n // Logging settings\n logLevel: 'info',\n verbose: 1,\n quiet: false,\n\n // MCP settings (also used by shell backend)\n mcpTimeout: 43200000, // 43200 seconds (12 hours) - default for long-running shell backend operations\n mcpRetries: 3,\n\n // Quota/hourly limit settings\n onHourlyLimit: 'raise', // Default to exit immediately when hourly limit is reached\n\n // TUI settings\n interactive: true,\n headlessMode: false,\n\n // Paths\n workingDirectory: process.cwd(),\n sessionDirectory: path.join(process.cwd(), '.juno_task'),\n\n // Project environment bootstrap\n envFilePath: '.env.juno',\n envFileCopied: false,\n\n // Hooks configuration - populated with default hooks template\n hooks: getDefaultHooks(),\n};\n\n/**\n * Global configuration file names to search for\n * Searched in order of preference (after project-specific config)\n */\nconst GLOBAL_CONFIG_FILE_NAMES = [\n 'juno-code.config.json',\n 'juno-code.config.js',\n '.juno-coderc.json',\n '.juno-coderc.js',\n 'package.json', // Will look for 'junoCode' field\n] as const;\n\n/**\n * Project-specific configuration file (highest precedence for project settings)\n */\nconst PROJECT_CONFIG_FILE = '.juno_task/config.json';\n\n/**\n * Default project env file created and loaded on startup\n */\nconst DEFAULT_PROJECT_ENV_FILE = '.env.juno';\n\n/**\n * Supported configuration file formats\n */\ntype ConfigFileFormat = 'json' | 'yaml' | 'toml' | 'js';\n\n/**\n * Configuration source types for precedence handling\n * Precedence order: cli > env > projectFile > file > defaults\n */\ntype ConfigSource = 'defaults' | 'file' | 'projectFile' | 'env' | 'cli';\n\n/**\n * Utility function to resolve paths (relative to absolute)\n *\n * @param inputPath - The path to resolve\n * @param basePath - Base path for relative resolution (defaults to cwd)\n * @returns Absolute path\n */\nfunction resolvePath(inputPath: string, basePath: string = process.cwd()): string {\n if (path.isAbsolute(inputPath)) {\n return inputPath;\n }\n return path.resolve(basePath, inputPath);\n}\n\n/**\n * Utility function to parse environment variables\n * Handles type conversion for boolean and number values\n *\n * @param value - Environment variable value\n * @returns Parsed value with appropriate type\n */\nfunction parseEnvValue(value: string): string | number | boolean {\n // Handle empty string\n if (value === '') return value;\n\n // Handle boolean values\n if (value.toLowerCase() === 'true') return true;\n if (value.toLowerCase() === 'false') return false;\n\n // Handle numeric values\n const numValue = Number(value);\n if (!isNaN(numValue) && isFinite(numValue)) {\n return numValue;\n }\n\n // Return as string\n return value;\n}\n\n/**\n * Load configuration from environment variables\n * Maps JUNO_CODE_* environment variables to config properties\n *\n * @returns Partial configuration from environment variables\n */\nfunction loadConfigFromEnv(): Partial<JunoTaskConfig> {\n const config: Partial<JunoTaskConfig> = {};\n\n for (const [envVar, configKey] of Object.entries(ENV_VAR_MAPPING) as [string, string][]) {\n const value = process.env[envVar];\n if (value !== undefined) {\n let parsed = parseEnvValue(value);\n // Normalize verbose: convert boolean to numeric level (0-2)\n if (configKey === 'verbose') {\n if (parsed === true) parsed = 1;\n else if (parsed === false) parsed = 0;\n }\n (config as any)[configKey] = parsed;\n }\n }\n\n return config;\n}\n\n/**\n * Load configuration from a JSON file\n *\n * @param filePath - Path to the JSON configuration file\n * @returns Parsed configuration object\n */\nasync function loadJsonConfig(filePath: string): Promise<Partial<JunoTaskConfig>> {\n try {\n const content = await fsPromises.readFile(filePath, 'utf-8');\n return JSON.parse(content);\n } catch (error) {\n throw new Error(`Failed to load JSON config from ${filePath}: ${error}`);\n }\n}\n\n/**\n * Load configuration from a YAML file\n *\n * @param filePath - Path to the YAML configuration file\n * @returns Parsed configuration object\n */\nasync function loadYamlConfig(filePath: string): Promise<Partial<JunoTaskConfig>> {\n try {\n const content = await fsPromises.readFile(filePath, 'utf-8');\n const parsed = yaml.load(content);\n return parsed as Partial<JunoTaskConfig>;\n } catch (error) {\n throw new Error(`Failed to load YAML config from ${filePath}: ${error}`);\n }\n}\n\n/**\n * Load configuration from package.json\n * Looks for configuration in the 'junoCode' field\n *\n * @param filePath - Path to package.json\n * @returns Parsed configuration object\n */\nasync function loadPackageJsonConfig(filePath: string): Promise<Partial<JunoTaskConfig>> {\n try {\n const content = await fsPromises.readFile(filePath, 'utf-8');\n const packageJson = JSON.parse(content);\n return packageJson.junoCode || {};\n } catch (error) {\n throw new Error(`Failed to load package.json config from ${filePath}: ${error}`);\n }\n}\n\n/**\n * Determine configuration file format based on file extension\n *\n * @param filePath - Path to the configuration file\n * @returns Configuration file format\n */\nfunction getConfigFileFormat(filePath: string): ConfigFileFormat {\n const ext = path.extname(filePath).toLowerCase();\n\n switch (ext) {\n case '.json':\n return 'json';\n case '.yaml':\n case '.yml':\n return 'yaml';\n case '.toml':\n return 'toml';\n case '.js':\n case '.mjs':\n return 'js';\n default:\n // For files like .juno-coderc (no extension), assume JSON\n return 'json';\n }\n}\n\n/**\n * Load configuration from a file\n * Automatically detects file format and uses appropriate parser\n *\n * @param filePath - Path to the configuration file\n * @returns Parsed configuration object\n */\nasync function loadConfigFromFile(filePath: string): Promise<Partial<JunoTaskConfig>> {\n const format = getConfigFileFormat(filePath);\n const resolvedPath = resolvePath(filePath);\n\n // Check if file exists\n try {\n await fsPromises.access(resolvedPath, nodeFs.constants.R_OK);\n } catch {\n throw new Error(`Configuration file not readable: ${resolvedPath}`);\n }\n\n switch (format) {\n case 'json':\n if (path.basename(filePath) === 'package.json') {\n return loadPackageJsonConfig(resolvedPath);\n }\n return loadJsonConfig(resolvedPath);\n\n case 'yaml':\n return loadYamlConfig(resolvedPath);\n\n case 'toml':\n // TOML support would require additional dependency\n throw new Error('TOML configuration files are not yet supported');\n\n case 'js':\n // JavaScript config files would require dynamic import\n throw new Error('JavaScript configuration files are not yet supported');\n\n default:\n throw new Error(`Unsupported configuration file format: ${format}`);\n }\n}\n\n/**\n * Find project-specific configuration file\n * Looks for .juno_task/config.json in the specified directory\n *\n * @param searchDir - Directory to search for project configuration file\n * @returns Path to found project config file, or null if none found\n */\nasync function findProjectConfigFile(searchDir: string = process.cwd()): Promise<string | null> {\n const filePath = path.join(searchDir, PROJECT_CONFIG_FILE);\n\n try {\n await fsPromises.access(filePath, nodeFs.constants.R_OK);\n return filePath;\n } catch {\n // File doesn't exist or isn't readable\n return null;\n }\n}\n\n/**\n * Find global configuration file in the specified directory\n * Searches for global config files in order of preference\n *\n * @param searchDir - Directory to search for global configuration files\n * @returns Path to found global config file, or null if none found\n */\nasync function findGlobalConfigFile(searchDir: string = process.cwd()): Promise<string | null> {\n for (const fileName of GLOBAL_CONFIG_FILE_NAMES) {\n const filePath = path.join(searchDir, fileName);\n\n try {\n await fsPromises.access(filePath, nodeFs.constants.R_OK);\n return filePath;\n } catch {\n // File doesn't exist or isn't readable, continue searching\n continue;\n }\n }\n\n return null;\n}\n\n/**\n * ConfigLoader class for multi-source configuration loading\n *\n * Implements configuration precedence: CLI args > Environment Variables > Project Config > Global Config Files > Profile > Defaults\n */\nexport class ConfigLoader {\n private configSources: Map<ConfigSource, Partial<JunoTaskConfig>> = new Map();\n\n /**\n * Create a new ConfigLoader instance\n *\n * @param baseDir - Base directory for relative path resolution\n */\n constructor(private baseDir: string = process.cwd()) {\n // Initialize with defaults\n this.configSources.set('defaults', DEFAULT_CONFIG);\n }\n\n /**\n * Load configuration from environment variables\n *\n * @returns This ConfigLoader instance for method chaining\n */\n fromEnvironment(): this {\n const envConfig = loadConfigFromEnv();\n this.configSources.set('env', envConfig);\n return this;\n }\n\n /**\n * Load configuration from a specific file\n *\n * @param filePath - Path to configuration file\n * @returns This ConfigLoader instance for method chaining\n */\n async fromFile(filePath: string): Promise<this> {\n try {\n const fileConfig = await loadConfigFromFile(filePath);\n this.configSources.set('file', fileConfig);\n } catch (error) {\n throw new Error(`Failed to load configuration file: ${error}`);\n }\n return this;\n }\n\n /**\n * Load configuration from project-specific config file\n * Loads from .juno_task/config.json with highest precedence for project settings\n *\n * @returns This ConfigLoader instance for method chaining\n */\n async fromProjectConfig(): Promise<this> {\n try {\n const projectConfigFile = await findProjectConfigFile(this.baseDir);\n if (projectConfigFile) {\n const fileConfig = await loadConfigFromFile(projectConfigFile);\n this.configSources.set('projectFile', fileConfig);\n }\n } catch (error) {\n throw new Error(`Failed to load project configuration file: ${error}`);\n }\n return this;\n }\n\n /**\n * Automatically discover and load configuration files\n * Searches for both project-specific and global config files in the base directory\n * Project-specific config (.juno_task/config.json) takes precedence over global configs\n *\n * @returns This ConfigLoader instance for method chaining\n */\n async autoDiscoverFile(): Promise<this> {\n // First, try to load project-specific config\n const projectConfigFile = await findProjectConfigFile(this.baseDir);\n if (projectConfigFile) {\n const fileConfig = await loadConfigFromFile(projectConfigFile);\n this.configSources.set('projectFile', fileConfig);\n }\n\n // Then, try to load global config file\n const globalConfigFile = await findGlobalConfigFile(this.baseDir);\n if (globalConfigFile) {\n const fileConfig = await loadConfigFromFile(globalConfigFile);\n this.configSources.set('file', fileConfig);\n }\n\n return this;\n }\n\n /**\n * Load configuration from CLI arguments\n *\n * @param cliConfig - Configuration object from CLI argument parsing\n * @returns This ConfigLoader instance for method chaining\n */\n fromCli(cliConfig: Partial<JunoTaskConfig>): this {\n this.configSources.set('cli', cliConfig);\n return this;\n }\n\n /**\n * Merge all configuration sources according to precedence\n * CLI args > Environment Variables > Project Config > Global Config Files > Defaults\n *\n * @returns Merged configuration object\n */\n merge(): JunoTaskConfig {\n // Start with defaults to ensure all required properties are present\n const mergedConfig = { ...DEFAULT_CONFIG };\n\n // Apply sources in order of precedence (lowest to highest)\n const sourcePrecedence: ConfigSource[] = ['file', 'projectFile', 'env', 'cli'];\n\n for (const source of sourcePrecedence) {\n const sourceConfig = this.configSources.get(source);\n if (sourceConfig) {\n Object.assign(mergedConfig, sourceConfig);\n }\n }\n\n // Resolve paths to absolute paths\n if (mergedConfig.workingDirectory) {\n mergedConfig.workingDirectory = resolvePath(mergedConfig.workingDirectory, this.baseDir);\n }\n\n if (mergedConfig.sessionDirectory) {\n mergedConfig.sessionDirectory = resolvePath(mergedConfig.sessionDirectory, this.baseDir);\n }\n\n if (mergedConfig.logFile) {\n mergedConfig.logFile = resolvePath(mergedConfig.logFile, this.baseDir);\n }\n\n if (mergedConfig.mcpServerPath) {\n mergedConfig.mcpServerPath = resolvePath(mergedConfig.mcpServerPath, this.baseDir);\n }\n\n return mergedConfig;\n }\n\n /**\n * Load and merge configuration from all sources\n * Convenience method that performs auto-discovery and returns validated config\n *\n * @param cliConfig - Optional CLI configuration\n * @returns Promise resolving to validated configuration\n */\n async loadAll(cliConfig?: Partial<JunoTaskConfig>): Promise<JunoTaskConfig> {\n // Load from environment\n this.fromEnvironment();\n\n // Auto-discover configuration file\n await this.autoDiscoverFile();\n\n // Add CLI config if provided\n if (cliConfig) {\n this.fromCli(cliConfig);\n }\n\n // Merge and return\n return this.merge();\n }\n}\n\n/**\n * Validate configuration object against schema\n *\n * @param config - Configuration object to validate\n * @returns Validated configuration object\n * @throws Error if validation fails\n */\nexport function validateConfig(config: unknown): JunoTaskConfig {\n try {\n const parsed = JunoTaskConfigSchema.parse(config);\n return parsed as JunoTaskConfig;\n } catch (error) {\n if (error instanceof z.ZodError) {\n const errorMessages = error.errors\n .map((err) => `${err.path.join('.')}: ${err.message}`)\n .join('; ');\n throw new Error(`Configuration validation failed: ${errorMessages}`);\n }\n throw error;\n }\n}\n\n/**\n * Parse dotenv-style content into key/value pairs.\n * Supports comments (#), `export KEY=VALUE`, and quoted values.\n */\nfunction parseEnvFileContent(content: string): Record<string, string> {\n const envVars: Record<string, string> = {};\n const lines = content.split(/\\r?\\n/);\n\n for (const rawLine of lines) {\n const trimmedLine = rawLine.trim();\n if (!trimmedLine || trimmedLine.startsWith('#')) {\n continue;\n }\n\n const line = trimmedLine.startsWith('export ') ? trimmedLine.slice(7).trim() : trimmedLine;\n const separatorIndex = line.indexOf('=');\n if (separatorIndex === -1) {\n continue;\n }\n\n const key = line.slice(0, separatorIndex).trim();\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) {\n continue;\n }\n\n let value = line.slice(separatorIndex + 1).trim();\n\n // Handle quoted values\n if (\n ((value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))) &&\n value.length >= 2\n ) {\n const quote = value[0];\n value = value.slice(1, -1);\n if (quote === '\"') {\n value = value\n .replace(/\\\\n/g, '\\n')\n .replace(/\\\\r/g, '\\r')\n .replace(/\\\\t/g, '\\t')\n .replace(/\\\\\"/g, '\"')\n .replace(/\\\\\\\\/g, '\\\\');\n }\n } else {\n // Strip inline comments from unquoted values (`KEY=value # comment`)\n const inlineCommentIndex = value.indexOf(' #');\n if (inlineCommentIndex >= 0) {\n value = value.slice(0, inlineCommentIndex).trimEnd();\n }\n }\n\n envVars[key] = value;\n }\n\n return envVars;\n}\n\n/**\n * Load environment variables from a dotenv-style file into process.env.\n * Variables from the file override existing process.env values.\n */\nasync function loadEnvFileIntoProcess(envFilePath: string): Promise<void> {\n try {\n const content = await fsPromises.readFile(envFilePath, 'utf-8');\n const parsed = parseEnvFileContent(content);\n\n for (const [key, value] of Object.entries(parsed)) {\n process.env[key] = value;\n }\n } catch (error) {\n console.warn(`Warning: Failed to load env file ${envFilePath}: ${error}`);\n }\n}\n\n/**\n * Ensure project env files exist and load them before config/env precedence is evaluated.\n *\n * Behavior:\n * - Always ensure `.env.juno` exists in project root.\n * - Read `.juno_task/config.json` for optional `envFilePath` and `envFileCopied`.\n * - If a custom env path is configured and not initialized yet, copy `.env.juno` once.\n * - Load `.env.juno`, then custom env file (if different) so custom values can override defaults.\n */\nasync function ensureAndLoadProjectEnv(baseDir: string): Promise<void> {\n const configPath = path.join(baseDir, PROJECT_CONFIG_FILE);\n const defaultEnvPath = resolvePath(DEFAULT_PROJECT_ENV_FILE, baseDir);\n\n // Always ensure root .env.juno exists\n await fs.ensureFile(defaultEnvPath);\n\n let existingConfig: Record<string, unknown> | null = null;\n\n if (await fs.pathExists(configPath)) {\n try {\n existingConfig = await fs.readJson(configPath);\n } catch (error) {\n console.warn(`Warning: Failed to read ${configPath} for env bootstrap: ${error}`);\n }\n }\n\n const configuredEnvPathRaw =\n existingConfig && typeof existingConfig.envFilePath === 'string' && existingConfig.envFilePath\n ? existingConfig.envFilePath\n : DEFAULT_PROJECT_ENV_FILE;\n\n const configuredEnvPath = resolvePath(configuredEnvPathRaw, baseDir);\n\n let envFileCopied =\n existingConfig && typeof existingConfig.envFileCopied === 'boolean'\n ? existingConfig.envFileCopied\n : false;\n\n let needsConfigUpdate = false;\n\n if (configuredEnvPath !== defaultEnvPath) {\n const configuredExists = await fs.pathExists(configuredEnvPath);\n\n if (!configuredExists) {\n await fs.ensureDir(path.dirname(configuredEnvPath));\n if (!envFileCopied) {\n await fsPromises.copyFile(defaultEnvPath, configuredEnvPath);\n } else {\n await fs.ensureFile(configuredEnvPath);\n }\n }\n\n if (!envFileCopied) {\n envFileCopied = true;\n needsConfigUpdate = true;\n }\n }\n\n if (\n existingConfig &&\n (needsConfigUpdate ||\n typeof existingConfig.envFilePath !== 'string' ||\n typeof existingConfig.envFileCopied !== 'boolean')\n ) {\n const updatedConfig = {\n ...existingConfig,\n envFilePath: configuredEnvPathRaw,\n envFileCopied,\n };\n await fs.writeJson(configPath, updatedConfig, { spaces: 2 });\n }\n\n // Load default env first, then custom env to allow override semantics.\n await loadEnvFileIntoProcess(defaultEnvPath);\n if (configuredEnvPath !== defaultEnvPath) {\n await loadEnvFileIntoProcess(configuredEnvPath);\n }\n}\n\n/**\n * Ensure hooks configuration exists in project config file\n *\n * This function handles auto-migration for the hooks configuration:\n * - If .juno_task/config.json doesn't exist: create it with default config including empty hooks section\n * - If it exists but has no \"hooks\" field: add hooks: {} to the file\n * - Preserve all existing configuration\n *\n * @param baseDir - Base directory where .juno_task directory should be located\n * @returns Promise that resolves when migration is complete\n */\nasync function ensureHooksConfig(baseDir: string): Promise<void> {\n try {\n const configDir = path.join(baseDir, '.juno_task');\n const configPath = path.join(configDir, 'config.json');\n\n // Ensure the .juno_task directory exists\n await fs.ensureDir(configDir);\n\n // Check if config file exists\n const configExists = await fs.pathExists(configPath);\n\n // Use default hooks template with file size monitoring commands\n const allHookTypes = getDefaultHooks();\n\n if (!configExists) {\n // Create new config file with default config including all hook types\n const defaultConfig = {\n ...DEFAULT_CONFIG,\n hooks: allHookTypes,\n };\n await fs.writeJson(configPath, defaultConfig, { spaces: 2 });\n } else {\n // Read existing config and ensure hooks field exists with all hook types\n const existingConfig = await fs.readJson(configPath);\n let needsUpdate = false;\n\n // If hooks field doesn't exist, add it with all hook types\n if (!existingConfig.hooks) {\n existingConfig.hooks = allHookTypes;\n needsUpdate = true;\n }\n\n // Migration: Add defaultModel if missing (for configs created before this feature)\n if (!existingConfig.defaultModel) {\n const subagent = existingConfig.defaultSubagent || 'claude';\n existingConfig.defaultModel =\n SUBAGENT_DEFAULT_MODELS[subagent as keyof typeof SUBAGENT_DEFAULT_MODELS] ||\n SUBAGENT_DEFAULT_MODELS.claude;\n needsUpdate = true;\n }\n\n // Migration: add per-subagent default model map when absent\n if (\n !existingConfig.defaultModels ||\n typeof existingConfig.defaultModels !== 'object' ||\n Array.isArray(existingConfig.defaultModels)\n ) {\n const baseDefaults = { ...SUBAGENT_DEFAULT_MODELS } as Record<string, string>;\n const subagent = existingConfig.defaultSubagent || 'claude';\n if (typeof existingConfig.defaultModel === 'string') {\n baseDefaults[subagent] = existingConfig.defaultModel;\n }\n existingConfig.defaultModels = baseDefaults;\n needsUpdate = true;\n }\n\n // Migration: Update defaultMaxIterations from old default (50) to new default (1)\n // Old configs created before v1.44.109 had defaultMaxIterations: 50\n if (existingConfig.defaultMaxIterations === 50) {\n existingConfig.defaultMaxIterations = DEFAULT_CONFIG.defaultMaxIterations;\n needsUpdate = true;\n }\n\n // Ensure env bootstrap keys exist in project config\n if (!existingConfig.envFilePath) {\n existingConfig.envFilePath = DEFAULT_PROJECT_ENV_FILE;\n needsUpdate = true;\n }\n\n if (typeof existingConfig.envFileCopied !== 'boolean') {\n existingConfig.envFileCopied = false;\n needsUpdate = true;\n }\n\n if (needsUpdate) {\n await fs.writeJson(configPath, existingConfig, { spaces: 2 });\n }\n }\n } catch (error) {\n // Log warning but don't block app startup\n console.warn(`Warning: Failed to ensure hooks configuration: ${error}`);\n }\n}\n\n/**\n * Load and validate configuration from all sources\n *\n * This is the main entry point for configuration loading.\n * It performs auto-discovery, merging, and validation.\n *\n * @param options - Configuration loading options\n * @param options.baseDir - Base directory for relative path resolution\n * @param options.configFile - Specific configuration file to load\n * @param options.cliConfig - CLI configuration override\n * @returns Promise resolving to validated configuration\n *\n * @example\n * ```typescript\n * // Load with auto-discovery\n * const config = await loadConfig();\n *\n * // Load with specific file\n * const config = await loadConfig({\n * configFile: './my-config.json'\n * });\n *\n * // Load with CLI overrides\n * const config = await loadConfig({\n * cliConfig: { verbose: true, logLevel: 'debug' }\n * });\n * ```\n */\nexport async function loadConfig(\n options: {\n baseDir?: string;\n configFile?: string;\n cliConfig?: Partial<JunoTaskConfig>;\n } = {},\n): Promise<JunoTaskConfig> {\n const { baseDir = process.cwd(), configFile, cliConfig } = options;\n\n // Ensure hooks configuration exists in project config (auto-migration)\n await ensureHooksConfig(baseDir);\n\n // Ensure .env.juno/custom env exists and load env vars before config env precedence is evaluated.\n await ensureAndLoadProjectEnv(baseDir);\n\n const loader = new ConfigLoader(baseDir);\n\n // Load from environment\n loader.fromEnvironment();\n\n // Load from specific file or auto-discover\n if (configFile) {\n await loader.fromFile(configFile);\n } else {\n await loader.autoDiscoverFile();\n }\n\n // Add CLI config if provided\n if (cliConfig) {\n loader.fromCli(cliConfig);\n }\n\n // Merge and validate\n const mergedConfig = loader.merge();\n return validateConfig(mergedConfig);\n}\n\n/**\n * Type export for configuration loading options\n */\nexport type ConfigLoadOptions = Parameters<typeof loadConfig>[0];\n\n/**\n * Type export for environment variable mapping\n */\nexport type EnvVarMapping = typeof ENV_VAR_MAPPING;\n","/**\n * Default hooks template configuration\n *\n * This module provides default hook commands that are shipped with juno-code.\n * These hooks are automatically configured during project initialization (init command).\n *\n * Hook Types:\n * - START_RUN: Executes at the beginning of a run (before all iterations)\n * - START_ITERATION: Executes at the start of each iteration\n * - END_ITERATION: Executes at the end of each iteration\n * - END_RUN: Executes at the end of a run (after all iterations)\n *\n * To modify default hooks:\n * 1. Update the commands in this file\n * 2. Rebuild the project (npm run build)\n * 3. New installations will use the updated defaults\n *\n * @module templates/default-hooks\n */\n\nimport type { Hooks } from '../types/index';\n\n/**\n * Default hooks configuration template\n *\n * All hook types are included so users can see available hooks without reading documentation.\n * Empty command arrays indicate hooks that are available but not configured by default.\n *\n * These hooks provide useful default behaviors:\n * - File size monitoring for CLAUDE.md, AGENTS.md, .juno_task/plan.md, .juno_task/tasks.md\n * - Alerts via juno-kanban when documentation/task files become too large\n *\n * Users can customize these hooks by editing .juno_task/config.json after initialization\n */\nexport const DEFAULT_HOOKS: Hooks = {\n // Executes once at the beginning of a run (before all iterations)\n // Use for: setup, environment checks, notifications, pre-run cleanup\n START_RUN: {\n commands: [],\n },\n\n // Executes at the start of each iteration\n // Use for: file monitoring, state checks, per-iteration setup\n START_ITERATION: {\n commands: [\n // Monitor CLAUDE.md file size\n 'file=\"CLAUDE.md\"; lines=$(wc -l < \"$file\" 2>/dev/null || echo 0); chars=$(wc -m < \"$file\" 2>/dev/null || echo 0); if [ \"$lines\" -gt 450 ] || [ \"$chars\" -gt 40000 ]; then juno-kanban \"[Critical] file $file is too large, keep it lean and useful for every run of the agent.\"; fi',\n\n // Monitor AGENTS.md file size\n 'file=\"AGENTS.md\"; lines=$(wc -l < \"$file\" 2>/dev/null || echo 0); chars=$(wc -m < \"$file\" 2>/dev/null || echo 0); if [ \"$lines\" -gt 450 ] || [ \"$chars\" -gt 40000 ]; then juno-kanban \"[Critical] file $file is too large, keep it lean and useful for every run of the agent.\"; fi',\n\n // Monitor .juno_task/plan.md file size\n 'file=\".juno_task/plan.md\"; lines=$(wc -l < \"$file\" 2>/dev/null || echo 0); chars=$(wc -m < \"$file\" 2>/dev/null || echo 0); if [ \"$lines\" -gt 450 ] || [ \"$chars\" -gt 40000 ]; then juno-kanban \"[Critical] file $file is too large, keep it lean and useful for every run of the agent.\"; fi',\n\n // Monitor .juno_task/tasks.md file size\n 'file=\".juno_task/tasks.md\"; lines=$(wc -l < \"$file\" 2>/dev/null || echo 0); chars=$(wc -m < \"$file\" 2>/dev/null || echo 0); if [ \"$lines\" -gt 450 ] || [ \"$chars\" -gt 40000 ]; then juno-kanban \"[Critical] file $file is too large, keep it lean and useful for every run of the agent.\"; fi',\n './.juno_task/scripts/cleanup_feedback.sh',\n ],\n },\n\n // Executes at the end of each iteration\n // Use for: validation, logging, per-iteration cleanup, progress tracking\n END_ITERATION: {\n commands: [],\n },\n\n // Executes once at the end of a run (after all iterations complete)\n // Use for: final cleanup, notifications, reports, post-run actions\n END_RUN: {\n commands: [],\n },\n\n // Executes when stale iteration is detected in run_until_completion.sh\n // Use for: alerts, notifications, logging when agent is not making progress\n ON_STALE: {\n commands: [\n './.juno_task/scripts/kanban.sh create \"Warning: You haven\\'t done anything on the kanban in the past run. You need to process a task, or if you find it unsuitable or unresolvable, you need to archive the task\" --status todo',\n ],\n },\n};\n\n/**\n * Get default hooks configuration\n *\n * Returns a copy of the default hooks to prevent mutation of the template.\n * This function can be used during initialization to populate the config.json file.\n *\n * @returns A copy of the default hooks configuration\n */\nexport function getDefaultHooks(): Hooks {\n return JSON.parse(JSON.stringify(DEFAULT_HOOKS));\n}\n\n/**\n * Get default hooks as formatted JSON string for config.json\n *\n * @param indent - Number of spaces for indentation (default: 2)\n * @returns Formatted JSON string of default hooks\n */\nexport function getDefaultHooksJson(indent: number = 2): string {\n return JSON.stringify(DEFAULT_HOOKS, null, indent);\n}\n","import type { JunoTaskConfig, SubagentType } from '../types/index.js';\n\nexport const SUBAGENT_DEFAULT_MODELS: Readonly<Record<SubagentType, string>> = {\n claude: ':sonnet',\n codex: ':codex',\n gemini: ':pro',\n cursor: 'auto',\n pi: ':pi',\n};\n\n/**\n * Get the built-in default model for a subagent.\n */\nexport function getDefaultModelForSubagent(subagent: SubagentType): string {\n return SUBAGENT_DEFAULT_MODELS[subagent] || SUBAGENT_DEFAULT_MODELS.claude;\n}\n\n/**\n * Check if a model string is compatible with a given subagent.\n *\n * Full model names (non-shorthand) are considered compatible because users\n * may provide provider-specific model ids.\n */\nexport function isModelCompatibleWithSubagent(model: string, subagent: SubagentType): boolean {\n if (!model.startsWith(':')) {\n return true;\n }\n\n const claudeShorthands = [':sonnet', ':haiku', ':opus'];\n const codexShorthands = [':codex', ':codex-mini', ':gpt-5', ':mini'];\n const geminiShorthands = [':pro', ':flash'];\n\n const isClaudeModel = claudeShorthands.includes(model) || model.startsWith(':claude');\n const isCodexModel = codexShorthands.includes(model) || model.startsWith(':gpt');\n const isGeminiModel = geminiShorthands.includes(model) || model.startsWith(':gemini');\n\n switch (subagent) {\n case 'claude':\n return isClaudeModel || (!isCodexModel && !isGeminiModel);\n case 'codex':\n return isCodexModel || (!isClaudeModel && !isGeminiModel);\n case 'gemini':\n return isGeminiModel || (!isClaudeModel && !isCodexModel);\n case 'cursor':\n return true;\n case 'pi':\n return true;\n default:\n return true;\n }\n}\n\n/**\n * Resolve configured model for a specific subagent.\n *\n * Priority:\n * 1) Legacy `defaultModel` when it belongs to `defaultSubagent`\n * 2) `defaultModels[subagent]`\n * 3) undefined (caller should fallback to built-in defaults)\n */\nexport function getConfiguredDefaultModelForSubagent(\n config: Pick<JunoTaskConfig, 'defaultSubagent' | 'defaultModel' | 'defaultModels'>,\n subagent: SubagentType,\n): string | undefined {\n const legacyDefaultModel =\n config.defaultSubagent === subagent &&\n typeof config.defaultModel === 'string' &&\n isModelCompatibleWithSubagent(config.defaultModel, subagent)\n ? config.defaultModel\n : undefined;\n\n if (legacyDefaultModel) {\n return legacyDefaultModel;\n }\n\n const modelFromMap = config.defaultModels?.[subagent];\n if (typeof modelFromMap === 'string' && isModelCompatibleWithSubagent(modelFromMap, subagent)) {\n return modelFromMap;\n }\n\n return undefined;\n}\n","/**\n * Core execution engine module for juno-task-ts\n *\n * This module provides the main execution orchestration engine that manages\n * the entire workflow for AI task execution, including session management,\n * backend integration, progress tracking, error handling, and cancellation.\n *\n * The implementation closely matches the Python budi-cli execution patterns,\n * including rate limit handling, iteration logic, and progress tracking.\n *\n * @module core/engine\n * @since 1.0.0\n */\n\nimport { EventEmitter } from 'node:events';\nimport type { JunoTaskConfig, SubagentType, ProgressEventType, BackendType } from '../types/index';\nimport type {\n ProgressEvent,\n ProgressCallback,\n ToolCallRequest,\n ToolCallResult,\n SessionContext,\n} from '../types/execution.js';\nimport { ExecutionError, RateLimitError } from './errors';\nimport { executeHook, type HookExecutionResult } from '../utils/hooks.js';\nimport { engineLogger } from '../cli/utils/advanced-logger.js';\nimport type { Backend } from './backend-manager.js';\nimport { type QuotaLimitInfo, formatDuration } from './backends/shell-backend.js';\n\n// =============================================================================\n// Type Definitions\n// =============================================================================\n\n/**\n * Execution request interface for starting task execution\n */\nexport interface ExecutionRequest {\n /** Unique request identifier */\n readonly requestId: string;\n\n /** Task instruction or prompt text */\n readonly instruction: string;\n\n /** Subagent to use for execution */\n readonly subagent: SubagentType;\n\n /** Backend to use for execution */\n readonly backend: BackendType;\n\n /** Working directory for execution */\n readonly workingDirectory: string;\n\n /** Maximum number of iterations (-1 for unlimited) */\n readonly maxIterations: number;\n\n /** Optional specific model to use */\n readonly model?: string;\n\n /** Optional timeout in milliseconds (overrides config) */\n readonly timeoutMs?: number;\n\n /** Session metadata */\n readonly sessionMetadata?: Record<string, unknown>;\n\n /** Custom progress callbacks */\n readonly progressCallbacks?: ProgressCallback[];\n\n /** Request priority level */\n readonly priority?: 'low' | 'normal' | 'high';\n\n /** MCP server name (for MCP backend) */\n readonly mcpServerName?: string;\n\n /** Available tools from built-in set (only works with --print mode, forwarded to shell backend) */\n readonly tools?: string[];\n\n /** Permission-based filtering of specific tool instances (forwarded to shell backend) */\n readonly allowedTools?: string[];\n\n /** Disallowed tools (forwarded to shell backend) */\n readonly disallowedTools?: string[];\n\n /** Append tools to default allowed-tools list (forwarded to shell backend) */\n readonly appendAllowedTools?: string[];\n\n /** Agents configuration (forwarded to shell backend) */\n readonly agents?: string;\n\n /** Resume a conversation by session ID (forwarded to shell backend) */\n readonly resume?: string;\n\n /** Continue the most recent conversation (forwarded to shell backend) */\n readonly continueConversation?: boolean;\n\n /** Extended thinking level (forwarded to shell backend --thinking flag) */\n readonly thinking?: string;\n\n /** Run Pi subagent in interactive live mode (forwarded to shell backend --live flag) */\n readonly live?: boolean;\n}\n\n/**\n * Execution result interface for completed executions\n */\nexport interface ExecutionResult {\n /** Request that generated this result */\n readonly request: ExecutionRequest;\n\n /** Execution status */\n readonly status: ExecutionStatus;\n\n /** Execution start time */\n readonly startTime: Date;\n\n /** Execution end time */\n readonly endTime: Date;\n\n /** Total execution duration in milliseconds */\n readonly duration: number;\n\n /** All iteration results */\n readonly iterations: readonly IterationResult[];\n\n /** Final execution statistics */\n readonly statistics: ExecutionStatistics;\n\n /** Any error that terminated execution */\n readonly error?: ExecutionError;\n\n /** Session context information */\n readonly sessionContext: SessionContext;\n\n /** All progress events captured during execution */\n readonly progressEvents: readonly ProgressEvent[];\n}\n\n/**\n * Individual iteration result\n */\nexport interface IterationResult {\n /** Iteration number (1-based) */\n readonly iterationNumber: number;\n\n /** Iteration success status */\n readonly success: boolean;\n\n /** Iteration start time */\n readonly startTime: Date;\n\n /** Iteration end time */\n readonly endTime: Date;\n\n /** Iteration duration in milliseconds */\n readonly duration: number;\n\n /** Tool call result */\n readonly toolResult: ToolCallResult;\n\n /** Iteration-specific progress events */\n readonly progressEvents: readonly ProgressEvent[];\n\n /** Any error that occurred during iteration */\n readonly error?: Error;\n}\n\n/**\n * Execution status enumeration\n */\nexport enum ExecutionStatus {\n PENDING = 'pending',\n RUNNING = 'running',\n COMPLETED = 'completed',\n FAILED = 'failed',\n CANCELLED = 'cancelled',\n TIMEOUT = 'timeout',\n RATE_LIMITED = 'rate_limited',\n}\n\n/**\n * Execution statistics for performance tracking\n */\nexport interface ExecutionStatistics {\n /** Total iterations attempted */\n totalIterations: number;\n\n /** Number of successful iterations */\n successfulIterations: number;\n\n /** Number of failed iterations */\n failedIterations: number;\n\n /** Average iteration duration in milliseconds */\n averageIterationDuration: number;\n\n /** Total tool calls made */\n totalToolCalls: number;\n\n /** Total progress events processed */\n totalProgressEvents: number;\n\n /** Rate limit encounters */\n rateLimitEncounters: number;\n\n /** Total rate limit wait time in milliseconds */\n rateLimitWaitTime: number;\n\n /** Quota limit encounters (Claude-specific) */\n quotaLimitEncounters: number;\n\n /** Total quota limit wait time in milliseconds */\n quotaLimitWaitTime: number;\n\n /** Error breakdown by type */\n errorBreakdown: Record<string, number>;\n\n /** Performance metrics */\n performanceMetrics: PerformanceMetrics;\n}\n\n/**\n * Performance metrics for detailed analysis\n */\nexport interface PerformanceMetrics {\n /** CPU usage percentage during execution */\n cpuUsage: number;\n\n /** Memory usage in bytes */\n memoryUsage: number;\n\n /** Network requests made */\n networkRequests: number;\n\n /** File system operations */\n fileSystemOperations: number;\n\n /** Throughput metrics */\n throughput: ThroughputMetrics;\n}\n\n/**\n * Throughput metrics\n */\nexport interface ThroughputMetrics {\n /** Iterations per minute */\n iterationsPerMinute: number;\n\n /** Progress events per second */\n progressEventsPerSecond: number;\n\n /** Tool calls per minute */\n toolCallsPerMinute: number;\n}\n\n/**\n * Rate limit information for handling\n */\nexport interface RateLimitInfo {\n /** Whether currently rate limited */\n readonly isRateLimited: boolean;\n\n /** Rate limit reset time */\n readonly resetTime?: Date;\n\n /** Remaining requests in current window */\n readonly remaining: number;\n\n /** Time to wait before next request in milliseconds */\n readonly waitTimeMs: number;\n\n /** Rate limit tier/category */\n readonly tier?: string;\n}\n\n/**\n * Error recovery strategy configuration\n */\nexport interface ErrorRecoveryConfig {\n /** Maximum recovery attempts per error type */\n readonly maxAttempts: Record<string, number>;\n\n /** Retry delays by error type in milliseconds */\n readonly retryDelays: Record<string, number>;\n\n /** Whether to continue on specific error types */\n readonly continueOnError: Record<string, boolean>;\n\n /** Custom recovery strategies */\n readonly customStrategies: Record<string, (error: ExecutionError) => Promise<boolean>>;\n}\n\n/**\n * Execution engine configuration\n */\nexport interface ExecutionEngineConfig {\n /** Base configuration */\n readonly config: JunoTaskConfig;\n\n /** No longer uses BackendManager; engine creates ShellBackend directly */\n\n /** Error recovery configuration */\n readonly errorRecovery: ErrorRecoveryConfig;\n\n /** Rate limit handling configuration */\n readonly rateLimitConfig: RateLimitHandlingConfig;\n\n /** Progress tracking configuration */\n readonly progressConfig: ProgressTrackingConfig;\n}\n\n/**\n * Rate limit handling configuration\n */\nexport interface RateLimitHandlingConfig {\n /** Enable automatic rate limit handling */\n readonly enabled: boolean;\n\n /** Maximum wait time for rate limits in milliseconds */\n readonly maxWaitTimeMs: number;\n\n /** Rate limit detection patterns */\n readonly detectionPatterns: readonly RegExp[];\n\n /** Custom rate limit parsers */\n readonly customParsers: readonly RateLimitParser[];\n}\n\n/**\n * Rate limit parser interface\n */\nexport interface RateLimitParser {\n /** Pattern to match rate limit messages */\n readonly pattern: RegExp;\n\n /** Parse function to extract reset time */\n readonly parse: (message: string) => Date | null;\n}\n\n/**\n * Progress tracking configuration\n */\nexport interface ProgressTrackingConfig {\n /** Enable progress tracking */\n readonly enabled: boolean;\n\n /** Buffer size for progress events */\n readonly bufferSize: number;\n\n /** Progress event filters */\n readonly filters: readonly ProgressEventFilter[];\n\n /** Custom progress processors */\n readonly processors: readonly ProgressEventProcessor[];\n}\n\n/**\n * Progress event filter\n */\nexport interface ProgressEventFilter {\n /** Filter type */\n readonly type: ProgressEventType | 'custom';\n\n /** Filter predicate */\n readonly predicate: (event: ProgressEvent) => boolean;\n}\n\n/**\n * Progress event processor\n */\nexport interface ProgressEventProcessor {\n /** Processor name */\n readonly name: string;\n\n /** Process function */\n readonly process: (event: ProgressEvent) => Promise<void>;\n}\n\n// =============================================================================\n// Default Configurations\n// =============================================================================\n\n/**\n * Default error recovery configuration\n */\nexport const DEFAULT_ERROR_RECOVERY_CONFIG: ErrorRecoveryConfig = {\n maxAttempts: {\n connection: 3,\n timeout: 2,\n rate_limit: 5,\n tool_execution: 2,\n validation: 1,\n server_not_found: 1,\n protocol: 2,\n authentication: 1,\n },\n retryDelays: {\n connection: 1000,\n timeout: 2000,\n rate_limit: 0, // Wait time determined by rate limit reset\n tool_execution: 1500,\n validation: 0, // No retry for validation errors\n server_not_found: 0, // No retry for server not found\n protocol: 1000,\n authentication: 0, // No retry for auth errors\n },\n continueOnError: {\n connection: true,\n timeout: true,\n rate_limit: true,\n tool_execution: false,\n validation: false,\n server_not_found: false,\n protocol: true,\n authentication: false,\n },\n customStrategies: {},\n};\n\n/**\n * Default rate limit handling configuration\n */\nexport const DEFAULT_RATE_LIMIT_CONFIG: RateLimitHandlingConfig = {\n enabled: true,\n maxWaitTimeMs: 3600000, // 1 hour\n detectionPatterns: [\n /resets\\s+(\\d{1,2}):?(\\d{2})?\\s*(am|pm)?/i,\n /resets\\s+(\\d{1,2})\\s*(am|pm)/i,\n /try again in (\\d+)\\s*(minutes?|hours?)/i,\n /5-hour limit reached.*resets\\s+(\\d{1,2})\\s*(am|pm)/i,\n ],\n customParsers: [],\n};\n\n/**\n * Default progress tracking configuration\n */\nexport const DEFAULT_PROGRESS_CONFIG: ProgressTrackingConfig = {\n enabled: true,\n bufferSize: 10000,\n filters: [],\n processors: [],\n};\n\n// =============================================================================\n// Main ExecutionEngine Class\n// =============================================================================\n\n/**\n * Main execution engine class for orchestrating AI task execution\n *\n * This class manages the complete execution lifecycle including:\n * - Session creation and management\n * - Iteration loop with rate limit handling\n * - Progress tracking and statistics collection\n * - Error handling with recovery strategies\n * - Cancellation and cleanup\n *\n * @example\n * ```typescript\n * const engine = createExecutionEngine(await loadConfig());\n *\n * const request: ExecutionRequest = {\n * requestId: 'req-123',\n * instruction: 'Implement a new feature',\n * subagent: 'claude',\n * workingDirectory: '/path/to/project',\n * maxIterations: 10,\n * };\n *\n * const result = await engine.execute(request);\n * ```\n */\nexport class ExecutionEngine extends EventEmitter {\n private readonly engineConfig: ExecutionEngineConfig;\n private readonly activeExecutions = new Map<string, ExecutionContext>();\n private readonly progressCallbacks: ProgressCallback[] = [];\n private readonly cleanupTasks: (() => Promise<void>)[] = [];\n private isShuttingDown = false;\n private currentBackend: Backend | null = null;\n\n /**\n * Create a new ExecutionEngine instance\n *\n * @param config - Engine configuration\n */\n constructor(config: ExecutionEngineConfig) {\n super();\n this.engineConfig = config;\n this.setupErrorHandling();\n this.setupProgressTracking();\n }\n\n // =============================================================================\n // Public API Methods\n // =============================================================================\n\n /**\n * Execute a task request with comprehensive orchestration\n *\n * @param request - Execution request parameters\n * @param abortSignal - Optional abort signal for cancellation\n * @returns Promise resolving to execution result\n */\n async execute(request: ExecutionRequest, abortSignal?: AbortSignal): Promise<ExecutionResult> {\n this.validateRequest(request);\n\n const context = this.createExecutionContext(request, abortSignal);\n this.activeExecutions.set(request.requestId, context);\n\n try {\n this.emit('execution:start', { request, context });\n\n const result = await this.executeInternal(context);\n\n this.emit('execution:complete', { request, result });\n return result;\n } catch (error) {\n const mcpError = this.wrapError(error);\n this.emit('execution:error', { request, error: mcpError });\n throw mcpError;\n } finally {\n this.activeExecutions.delete(request.requestId);\n await this.cleanupExecution(context);\n }\n }\n\n /**\n * Add a progress callback for all executions\n *\n * @param callback - Progress callback function\n * @returns Cleanup function to remove the callback\n */\n onProgress(callback: ProgressCallback): () => void {\n this.progressCallbacks.push(callback);\n return () => {\n const index = this.progressCallbacks.indexOf(callback);\n if (index !== -1) {\n this.progressCallbacks.splice(index, 1);\n }\n };\n }\n\n /**\n * Get current rate limit information\n *\n * @returns Current rate limit status\n */\n async getRateLimitInfo(): Promise<RateLimitInfo> {\n // Implementation would query backend for rate limit status\n return {\n isRateLimited: false,\n remaining: 100,\n resetTime: new Date(Date.now() + 60000), // 1 minute from now\n waitTimeMs: 0,\n };\n }\n\n /**\n * Cancel all active executions and shutdown gracefully\n *\n * @param timeoutMs - Maximum time to wait for cleanup\n */\n async shutdown(timeoutMs: number = 30000): Promise<void> {\n if (this.isShuttingDown) {\n return;\n }\n\n this.isShuttingDown = true;\n this.emit('engine:shutdown:start');\n\n try {\n // Cancel all active executions\n const cancellationPromises = Array.from(this.activeExecutions.values()).map((context) =>\n this.cancelExecution(context),\n );\n\n // Wait for cancellations with timeout\n await Promise.race([\n Promise.all(cancellationPromises),\n new Promise((_, reject) =>\n setTimeout(() => reject(new Error('Shutdown timeout')), timeoutMs),\n ),\n ]);\n\n // Clean up backend\n if (this.currentBackend) {\n await this.currentBackend.cleanup();\n this.currentBackend = null;\n }\n\n // Run cleanup tasks\n await Promise.all(this.cleanupTasks.map((task) => task()));\n\n this.emit('engine:shutdown:complete');\n } catch (error) {\n this.emit('engine:shutdown:error', error);\n throw error;\n } finally {\n this.removeAllListeners();\n }\n }\n\n /**\n * Get statistics for all executions\n *\n * @returns Aggregate execution statistics\n */\n getExecutionStatistics(): ExecutionStatistics {\n const contexts = Array.from(this.activeExecutions.values());\n\n return {\n totalIterations: contexts.reduce((sum, ctx) => sum + ctx.statistics.totalIterations, 0),\n successfulIterations: contexts.reduce(\n (sum, ctx) => sum + ctx.statistics.successfulIterations,\n 0,\n ),\n failedIterations: contexts.reduce((sum, ctx) => sum + ctx.statistics.failedIterations, 0),\n averageIterationDuration: this.calculateAverageIterationDuration(contexts),\n totalToolCalls: contexts.reduce((sum, ctx) => sum + ctx.statistics.totalToolCalls, 0),\n totalProgressEvents: contexts.reduce(\n (sum, ctx) => sum + ctx.statistics.totalProgressEvents,\n 0,\n ),\n rateLimitEncounters: contexts.reduce(\n (sum, ctx) => sum + ctx.statistics.rateLimitEncounters,\n 0,\n ),\n rateLimitWaitTime: contexts.reduce((sum, ctx) => sum + ctx.statistics.rateLimitWaitTime, 0),\n quotaLimitEncounters: contexts.reduce(\n (sum, ctx) => sum + (ctx.statistics.quotaLimitEncounters ?? 0),\n 0,\n ),\n quotaLimitWaitTime: contexts.reduce(\n (sum, ctx) => sum + (ctx.statistics.quotaLimitWaitTime ?? 0),\n 0,\n ),\n errorBreakdown: this.aggregateErrorBreakdown(contexts),\n performanceMetrics: this.calculatePerformanceMetrics(contexts),\n };\n }\n\n // =============================================================================\n // Private Implementation Methods\n // =============================================================================\n\n /**\n * Setup error handling for the engine\n */\n private setupErrorHandling(): void {\n // Backend-agnostic error handling\n process.on('uncaughtException', (error) => {\n this.emit('engine:uncaught-exception', error);\n });\n\n process.on('unhandledRejection', (reason) => {\n this.emit('engine:unhandled-rejection', reason);\n });\n }\n\n /**\n * Setup progress tracking for the engine\n */\n private setupProgressTracking(): void {\n // Progress tracking will be set up when backend is initialized\n // The backend manager will handle progress callbacks\n }\n\n /**\n * Display hook execution output to stderr at verbose level 2 (debug+hooks).\n * At level 2: shows hook name, command stdout/stderr output.\n * At level 0-1: output is suppressed (hooks still execute).\n */\n private displayHookOutput(hookResult: HookExecutionResult): void {\n if (this.engineConfig.config.verbose < 2) return;\n for (const cmdResult of hookResult.commandResults) {\n const prefix = `[hook:${hookResult.hookType}]`;\n if (cmdResult.stdout) {\n for (const line of cmdResult.stdout.split('\\n')) {\n if (line.trim()) console.error(`${prefix} ${line}`);\n }\n }\n if (cmdResult.stderr) {\n for (const line of cmdResult.stderr.split('\\n')) {\n if (line.trim()) console.error(`${prefix} ${line}`);\n }\n }\n if (!cmdResult.success) {\n console.error(`${prefix} command failed (exit ${cmdResult.exitCode}): ${cmdResult.command}`);\n }\n }\n }\n\n /**\n * Initialize backend for execution request.\n * Directly creates and configures a ShellBackend (no factory indirection).\n */\n private async initializeBackend(request: ExecutionRequest): Promise<void> {\n // Clean up existing backend if present\n if (this.currentBackend) {\n await this.currentBackend.cleanup();\n this.currentBackend = null;\n }\n\n // Create ShellBackend directly\n const { ShellBackend } = await import('./backends/shell-backend.js');\n const backend = new ShellBackend();\n\n // Configure\n (backend as any).configure({\n workingDirectory: request.workingDirectory,\n servicesPath: `${process.env.HOME || process.env.USERPROFILE}/.juno_code/services`,\n debug: this.engineConfig.config.verbose >= 2,\n timeout: request.timeoutMs || this.engineConfig.config.mcpTimeout || 43200000,\n enableJsonStreaming: true,\n outputRawJson: this.engineConfig.config.verbose >= 1,\n environment: {\n ...process.env,\n JUNO_TASK_ROOT: process.env.JUNO_TASK_ROOT || request.workingDirectory,\n },\n sessionId: request.requestId,\n });\n\n // Initialize and check availability\n await backend.initialize();\n\n const isAvailable = await backend.isAvailable();\n if (!isAvailable) {\n throw new Error(\n 'Shell backend is not available. Ensure ~/.juno_code/services/ exists and contains service scripts.',\n );\n }\n\n this.currentBackend = backend;\n\n // Set up progress tracking for the selected backend\n backend.onProgress(async (event: ProgressEvent) => {\n try {\n // Process through configured processors\n for (const processor of this.engineConfig.progressConfig.processors) {\n await processor.process(event);\n }\n\n // Notify all registered callbacks\n await Promise.all([...this.progressCallbacks.map((callback) => callback(event))]);\n\n this.emit('progress:event', event);\n } catch (error) {\n this.emit('progress:error', { event, error });\n }\n });\n\n engineLogger.debug(`Initialized ${backend.name} backend for execution`);\n }\n\n /**\n * Validate execution request parameters\n */\n private validateRequest(request: ExecutionRequest): void {\n if (!request.requestId?.trim()) {\n throw new Error('Request ID is required');\n }\n\n if (!request.instruction?.trim()) {\n throw new Error('Instruction is required');\n }\n\n if (!request.subagent?.trim()) {\n throw new Error('Subagent is required');\n }\n\n if (!request.workingDirectory?.trim()) {\n throw new Error('Working directory is required');\n }\n\n if (\n Number.isNaN(request.maxIterations) ||\n request.maxIterations < -1 ||\n request.maxIterations === 0\n ) {\n throw new Error('Max iterations must be a positive number or -1 for unlimited');\n }\n }\n\n /**\n * Create execution context for a request\n */\n private createExecutionContext(\n request: ExecutionRequest,\n abortSignal?: AbortSignal,\n ): ExecutionContext {\n const abortController = new AbortController();\n\n // Chain external abort signal if provided\n if (abortSignal) {\n abortSignal.addEventListener('abort', () => {\n abortController.abort();\n });\n }\n\n return {\n request,\n status: ExecutionStatus.PENDING,\n startTime: new Date(),\n endTime: null,\n iterations: [],\n statistics: this.createInitialStatistics(),\n progressEvents: [],\n error: null,\n abortController,\n sessionContext: this.createSessionContext(request),\n rateLimitInfo: {\n isRateLimited: false,\n remaining: 100,\n waitTimeMs: 0,\n },\n };\n }\n\n /**\n * Create initial statistics object\n */\n private createInitialStatistics(): ExecutionStatistics {\n return {\n totalIterations: 0,\n successfulIterations: 0,\n failedIterations: 0,\n averageIterationDuration: 0,\n totalToolCalls: 0,\n totalProgressEvents: 0,\n rateLimitEncounters: 0,\n rateLimitWaitTime: 0,\n quotaLimitEncounters: 0,\n quotaLimitWaitTime: 0,\n errorBreakdown: {},\n performanceMetrics: {\n cpuUsage: 0,\n memoryUsage: 0,\n networkRequests: 0,\n fileSystemOperations: 0,\n throughput: {\n iterationsPerMinute: 0,\n progressEventsPerSecond: 0,\n toolCallsPerMinute: 0,\n },\n },\n };\n }\n\n /**\n * Create session context for execution\n */\n private createSessionContext(request: ExecutionRequest): SessionContext {\n return {\n sessionId: `session-${request.requestId}`,\n startTime: new Date(),\n userId: 'system',\n metadata: {\n ...request.sessionMetadata,\n subagent: request.subagent,\n workingDirectory: request.workingDirectory,\n },\n activeToolCalls: [],\n state: 'initializing' as any,\n lastActivity: new Date(),\n };\n }\n\n /**\n * Internal execution implementation\n */\n private async executeInternal(context: ExecutionContext): Promise<ExecutionResult> {\n context.status = ExecutionStatus.RUNNING;\n context.sessionContext = { ...context.sessionContext, state: 'active' as any };\n\n // Pin JUNO_TASK_ROOT to workingDirectory so juno-kanban always resolves\n // .juno_task from the project root, not from wherever the agent cds to\n if (!process.env.JUNO_TASK_ROOT) {\n process.env.JUNO_TASK_ROOT = context.request.workingDirectory;\n }\n\n // Initialize backend for this execution request\n await this.initializeBackend(context.request);\n\n // Execute START_RUN hook\n try {\n if (this.engineConfig.config.hooks && !this.engineConfig.config.skipHooks) {\n const hookResult = await executeHook(\n 'START_RUN',\n this.engineConfig.config.hooks,\n {\n workingDirectory: context.request.workingDirectory,\n sessionId: context.sessionContext.sessionId,\n runId: context.request.requestId,\n metadata: {\n sessionId: context.sessionContext.sessionId,\n requestId: context.request.requestId,\n subagent: context.request.subagent,\n backend: context.request.backend,\n maxIterations: context.request.maxIterations,\n instruction: context.request.instruction,\n },\n },\n {\n commandTimeout: this.engineConfig.config.hookCommandTimeout,\n },\n );\n this.displayHookOutput(hookResult);\n }\n } catch (error) {\n engineLogger.warn('Hook START_RUN failed', { error });\n // Continue execution despite hook failure\n }\n\n try {\n await this.runIterationLoop(context);\n\n // Determine final status: if all iterations failed, mark execution as failed\n const hasSuccessfulIteration = context.statistics.successfulIterations > 0;\n if (hasSuccessfulIteration || context.statistics.totalIterations === 0) {\n context.status = ExecutionStatus.COMPLETED;\n context.sessionContext = { ...context.sessionContext, state: 'completed' as any };\n } else {\n context.status = ExecutionStatus.FAILED;\n context.sessionContext = { ...context.sessionContext, state: 'failed' as any };\n }\n } catch (error) {\n context.error = this.wrapError(error);\n context.status = this.determineErrorStatus(context.error);\n context.sessionContext = { ...context.sessionContext, state: 'failed' as any };\n } finally {\n context.endTime = new Date();\n }\n\n // Execute END_RUN hook\n try {\n if (this.engineConfig.config.hooks && !this.engineConfig.config.skipHooks) {\n const hookResult = await executeHook(\n 'END_RUN',\n this.engineConfig.config.hooks,\n {\n workingDirectory: context.request.workingDirectory,\n sessionId: context.sessionContext.sessionId,\n runId: context.request.requestId,\n metadata: {\n sessionId: context.sessionContext.sessionId,\n requestId: context.request.requestId,\n status: context.status,\n totalIterations: context.statistics.totalIterations,\n successfulIterations: context.statistics.successfulIterations,\n failedIterations: context.statistics.failedIterations,\n duration: context.endTime\n ? context.endTime.getTime() - context.startTime.getTime()\n : 0,\n success: context.status === ExecutionStatus.COMPLETED,\n },\n },\n {\n commandTimeout: this.engineConfig.config.hookCommandTimeout,\n },\n );\n this.displayHookOutput(hookResult);\n }\n } catch (error) {\n engineLogger.warn('Hook END_RUN failed', { error });\n // Continue execution despite hook failure\n }\n\n return this.createExecutionResult(context);\n }\n\n /**\n * Run the main iteration loop\n */\n private async runIterationLoop(context: ExecutionContext): Promise<void> {\n let iterationNumber = 1;\n\n while (!this.shouldStopIterating(context, iterationNumber)) {\n this.checkAbortSignal(context);\n\n try {\n const quotaLimitInfo = await this.executeIteration(context, iterationNumber);\n\n // Check if a quota limit was encountered\n if (quotaLimitInfo?.detected) {\n const shouldRetry = await this.handleQuotaLimit(context, quotaLimitInfo);\n if (shouldRetry) {\n // Don't increment iteration number, retry same iteration\n continue;\n }\n }\n\n iterationNumber++;\n } catch (error) {\n if (error instanceof RateLimitError) {\n await this.handleRateLimit(context, error);\n // Don't increment iteration number, retry same iteration\n continue;\n }\n\n const shouldContinue = await this.handleIterationError(context, error, iterationNumber);\n if (!shouldContinue) {\n throw error;\n }\n\n iterationNumber++;\n }\n\n // Brief delay between iterations\n await this.sleep(2000);\n }\n }\n\n /**\n * Execute a single iteration\n * @returns QuotaLimitInfo if a quota limit was detected, null otherwise\n */\n private async executeIteration(\n context: ExecutionContext,\n iterationNumber: number,\n ): Promise<QuotaLimitInfo | null> {\n const iterationStart = new Date();\n\n // Execute START_ITERATION hook\n try {\n if (this.engineConfig.config.hooks && !this.engineConfig.config.skipHooks) {\n const hookResult = await executeHook(\n 'START_ITERATION',\n this.engineConfig.config.hooks,\n {\n workingDirectory: context.request.workingDirectory,\n sessionId: context.sessionContext.sessionId,\n runId: context.request.requestId,\n iteration: iterationNumber,\n totalIterations: context.request.maxIterations,\n metadata: {\n sessionId: context.sessionContext.sessionId,\n requestId: context.request.requestId,\n iterationNumber,\n maxIterations: context.request.maxIterations,\n subagent: context.request.subagent,\n },\n },\n {\n commandTimeout: this.engineConfig.config.hookCommandTimeout,\n },\n );\n this.displayHookOutput(hookResult);\n }\n } catch (error) {\n engineLogger.warn('Hook START_ITERATION failed', { error, iterationNumber });\n // Continue execution despite hook failure\n }\n\n this.emit('iteration:start', { context, iterationNumber });\n\n const toolRequest: ToolCallRequest = {\n toolName: this.getToolNameForSubagent(context.request.subagent),\n arguments: {\n instruction: context.request.instruction,\n project_path: context.request.workingDirectory,\n ...(context.request.model !== undefined && { model: context.request.model }),\n ...(context.request.agents !== undefined && { agents: context.request.agents }),\n ...(context.request.tools !== undefined && { tools: context.request.tools }),\n ...(context.request.allowedTools !== undefined && {\n allowedTools: context.request.allowedTools,\n }),\n ...(context.request.appendAllowedTools !== undefined && {\n appendAllowedTools: context.request.appendAllowedTools,\n }),\n ...(context.request.disallowedTools !== undefined && {\n disallowedTools: context.request.disallowedTools,\n }),\n ...(context.request.resume !== undefined && { resume: context.request.resume }),\n ...(context.request.continueConversation !== undefined && {\n continueConversation: context.request.continueConversation,\n }),\n ...(context.request.thinking !== undefined && { thinking: context.request.thinking }),\n ...(context.request.live !== undefined && { live: context.request.live }),\n iteration: iterationNumber,\n },\n timeout: context.request.timeoutMs || this.engineConfig.config.mcpTimeout,\n priority: context.request.priority || 'normal',\n metadata: {\n sessionId: context.sessionContext.sessionId,\n iterationNumber,\n },\n progressCallback: async (event: ProgressEvent) => {\n context.progressEvents.push(event);\n context.statistics.totalProgressEvents++;\n await this.processProgressEvent(context, event);\n },\n };\n\n try {\n if (!this.currentBackend) {\n throw new Error('No backend initialized. Call initializeBackend() first.');\n }\n const toolResult = await this.currentBackend.execute(toolRequest);\n\n const iterationEnd = new Date();\n const duration = iterationEnd.getTime() - iterationStart.getTime();\n\n const iterationResult: IterationResult = {\n iterationNumber,\n success: toolResult.status?.toLowerCase() === 'completed',\n startTime: iterationStart,\n endTime: iterationEnd,\n duration,\n toolResult,\n progressEvents: toolResult.progressEvents,\n ...(toolResult.error !== undefined &&\n toolResult.error !== null && { error: toolResult.error }),\n };\n\n context.iterations.push(iterationResult);\n this.updateStatistics(context, iterationResult);\n\n this.emit('iteration:complete', { context, iterationResult });\n\n // Execute END_ITERATION hook for successful iteration\n try {\n if (this.engineConfig.config.hooks && !this.engineConfig.config.skipHooks) {\n const hookResult = await executeHook(\n 'END_ITERATION',\n this.engineConfig.config.hooks,\n {\n workingDirectory: context.request.workingDirectory,\n sessionId: context.sessionContext.sessionId,\n runId: context.request.requestId,\n iteration: iterationNumber,\n totalIterations: context.request.maxIterations,\n metadata: {\n sessionId: context.sessionContext.sessionId,\n requestId: context.request.requestId,\n iterationNumber,\n success: iterationResult.success,\n duration: iterationResult.duration,\n toolCallStatus: iterationResult.toolResult.status,\n },\n },\n {\n commandTimeout: this.engineConfig.config.hookCommandTimeout,\n },\n );\n this.displayHookOutput(hookResult);\n }\n } catch (error) {\n engineLogger.warn('Hook END_ITERATION failed', { error, iterationNumber });\n // Continue execution despite hook failure\n }\n\n // Check for quota limit in the result\n const quotaLimitInfo = this.extractQuotaLimitInfo(toolResult);\n return quotaLimitInfo;\n } catch (error) {\n const iterationEnd = new Date();\n const duration = iterationEnd.getTime() - iterationStart.getTime();\n const mcpError = this.wrapError(error);\n\n const iterationResult: IterationResult = {\n iterationNumber,\n success: false,\n startTime: iterationStart,\n endTime: iterationEnd,\n duration,\n toolResult: {\n content: '',\n status: 'failed' as any,\n startTime: iterationStart,\n endTime: iterationEnd,\n duration,\n error: mcpError,\n progressEvents: [],\n request: toolRequest,\n },\n progressEvents: [],\n error: mcpError,\n };\n\n context.iterations.push(iterationResult);\n this.updateStatistics(context, iterationResult);\n\n this.emit('iteration:error', { context, iterationResult });\n\n // Execute END_ITERATION hook for failed iteration\n try {\n if (this.engineConfig.config.hooks && !this.engineConfig.config.skipHooks) {\n const hookResult = await executeHook(\n 'END_ITERATION',\n this.engineConfig.config.hooks,\n {\n workingDirectory: context.request.workingDirectory,\n sessionId: context.sessionContext.sessionId,\n runId: context.request.requestId,\n iteration: iterationNumber,\n totalIterations: context.request.maxIterations,\n metadata: {\n sessionId: context.sessionContext.sessionId,\n requestId: context.request.requestId,\n iterationNumber,\n success: false,\n duration: iterationResult.duration,\n error: mcpError.message,\n errorType: mcpError.type,\n },\n },\n {\n commandTimeout: this.engineConfig.config.hookCommandTimeout,\n },\n );\n this.displayHookOutput(hookResult);\n }\n } catch (hookError) {\n engineLogger.warn('Hook END_ITERATION failed', { error: hookError, iterationNumber });\n // Continue execution despite hook failure\n }\n\n throw error;\n }\n }\n\n /**\n * Handle rate limit errors with automatic retry\n */\n private async handleRateLimit(context: ExecutionContext, error: RateLimitError): Promise<void> {\n if (!this.engineConfig.rateLimitConfig.enabled) {\n throw error;\n }\n\n context.statistics.rateLimitEncounters++;\n\n const waitTimeMs = this.calculateRateLimitWaitTime(error);\n if (waitTimeMs > this.engineConfig.rateLimitConfig.maxWaitTimeMs) {\n throw new Error(\n `Rate limit wait time (${waitTimeMs}ms) exceeds maximum allowed (${this.engineConfig.rateLimitConfig.maxWaitTimeMs}ms)`,\n );\n }\n\n context.statistics.rateLimitWaitTime += waitTimeMs;\n context.rateLimitInfo = {\n isRateLimited: true,\n ...(error.resetTime !== undefined && { resetTime: error.resetTime }),\n remaining: error.remaining || 0,\n waitTimeMs,\n ...(error.tier !== undefined && { tier: error.tier }),\n };\n\n this.emit('rate-limit:start', { context, error, waitTimeMs });\n\n await this.sleep(waitTimeMs);\n\n context.rateLimitInfo = {\n isRateLimited: false,\n remaining: 100,\n waitTimeMs: 0,\n };\n\n this.emit('rate-limit:end', { context });\n }\n\n /**\n * Calculate wait time for rate limit reset\n */\n private calculateRateLimitWaitTime(error: RateLimitError): number {\n if (error.resetTime) {\n const now = new Date();\n const waitTime = error.resetTime.getTime() - now.getTime();\n return Math.max(0, waitTime);\n }\n\n // Default wait time if no reset time provided\n return 60000; // 1 minute\n }\n\n /**\n * Handle Claude quota limit with automatic sleep and retry\n * @returns true if we should retry the iteration, false otherwise\n */\n private async handleQuotaLimit(\n context: ExecutionContext,\n quotaInfo: QuotaLimitInfo,\n ): Promise<boolean> {\n if (!quotaInfo.detected || !quotaInfo.sleepDurationMs) {\n return false;\n }\n\n context.statistics.quotaLimitEncounters++;\n\n // Check the onHourlyLimit configuration setting\n // Priority: config.json < ENV < Flag (all handled by the config loader)\n const onHourlyLimit = this.engineConfig.config.onHourlyLimit || 'raise';\n\n // If set to 'raise', exit immediately instead of waiting\n if (onHourlyLimit === 'raise') {\n const resetTimeStr = quotaInfo.resetTime\n ? quotaInfo.resetTime.toLocaleTimeString('en-US', {\n hour: 'numeric',\n minute: '2-digit',\n hour12: true,\n timeZoneName: 'short',\n })\n : 'unknown';\n\n const sourceLabel = quotaInfo.source === 'codex' ? 'Codex' : 'Claude';\n\n engineLogger.info(`╔════════════════════════════════════════════════════════════════╗`);\n engineLogger.info(\n `║ ${sourceLabel} Quota Limit Reached${' '.repeat(44 - sourceLabel.length - ' Quota Limit Reached'.length)}║`,\n );\n engineLogger.info(`╠════════════════════════════════════════════════════════════════╣`);\n engineLogger.info(`║ Quota resets at: ${resetTimeStr.padEnd(44)}║`);\n engineLogger.info(`║ Behavior: raise (exit immediately) ║`);\n engineLogger.info(`╠════════════════════════════════════════════════════════════════╣`);\n engineLogger.info(`║ To auto-wait instead, use: --on-hourly-limit wait ║`);\n engineLogger.info(`║ Or set: JUNO_CODE_ON_HOURLY_LIMIT=wait ║`);\n engineLogger.info(`║ Or in config.json: { \"onHourlyLimit\": \"wait\" } ║`);\n engineLogger.info(`╚════════════════════════════════════════════════════════════════╝`);\n\n this.emit('quota-limit:raise', { context, quotaInfo });\n\n // Return false to NOT retry, which will cause the iteration loop to continue\n // but since this is an error condition, we need to throw to actually exit\n throw new Error(\n `${sourceLabel} quota limit reached. Quota resets at ${resetTimeStr}. Use --on-hourly-limit wait to auto-retry.`,\n );\n }\n\n // onHourlyLimit === 'wait' - proceed with waiting behavior\n const waitTimeMs = quotaInfo.sleepDurationMs;\n\n // Cap the wait time at 12 hours to prevent excessive waits\n const maxWaitTimeMs = 12 * 60 * 60 * 1000; // 12 hours\n if (waitTimeMs > maxWaitTimeMs) {\n engineLogger.warn(\n `Quota limit wait time (${formatDuration(waitTimeMs)}) exceeds maximum allowed (12 hours). Will not auto-retry.`,\n );\n return false;\n }\n\n context.statistics.quotaLimitWaitTime += waitTimeMs;\n\n // Format the reset time for user display\n const resetTimeStr = quotaInfo.resetTime\n ? quotaInfo.resetTime.toLocaleTimeString('en-US', {\n hour: 'numeric',\n minute: '2-digit',\n hour12: true,\n timeZoneName: 'short',\n })\n : 'unknown';\n\n const durationStr = formatDuration(waitTimeMs);\n\n // Log user-friendly message\n const waitSourceLabel = quotaInfo.source === 'codex' ? 'Codex' : 'Claude';\n\n engineLogger.info(`╔════════════════════════════════════════════════════════════════╗`);\n engineLogger.info(\n `║ ${waitSourceLabel} Quota Limit Reached${' '.repeat(44 - waitSourceLabel.length - ' Quota Limit Reached'.length)}║`,\n );\n engineLogger.info(`╠════════════════════════════════════════════════════════════════╣`);\n engineLogger.info(`║ Quota resets at: ${resetTimeStr.padEnd(44)}║`);\n engineLogger.info(`║ Sleeping for: ${durationStr.padEnd(44)}║`);\n if (quotaInfo.timezone) {\n engineLogger.info(`║ Timezone: ${quotaInfo.timezone.padEnd(44)}║`);\n }\n engineLogger.info(`╚════════════════════════════════════════════════════════════════╝`);\n\n this.emit('quota-limit:start', { context, quotaInfo, waitTimeMs });\n\n // Sleep with periodic progress updates\n await this.sleepWithProgress(waitTimeMs, (remaining) => {\n const remainingStr = formatDuration(remaining);\n engineLogger.info(`[Quota Wait] ${remainingStr} remaining until retry...`);\n });\n\n this.emit('quota-limit:end', { context });\n\n engineLogger.info(`Quota limit wait complete. Resuming execution...`);\n\n return true;\n }\n\n /**\n * Sleep with periodic progress updates\n */\n private async sleepWithProgress(\n totalMs: number,\n onProgress: (remainingMs: number) => void,\n ): Promise<void> {\n const updateIntervalMs = 60000; // Update every minute\n let remaining = totalMs;\n\n while (remaining > 0) {\n const sleepTime = Math.min(remaining, updateIntervalMs);\n await this.sleep(sleepTime);\n remaining -= sleepTime;\n\n if (remaining > 0) {\n onProgress(remaining);\n }\n }\n }\n\n /**\n * Check if tool result indicates a quota limit error\n */\n private extractQuotaLimitInfo(toolResult: ToolCallResult): QuotaLimitInfo | null {\n // Check metadata first (most reliable)\n const metadataQuotaInfo = (toolResult.metadata as any)?.quotaLimitInfo;\n if (metadataQuotaInfo?.detected) {\n return metadataQuotaInfo;\n }\n\n // Try to parse from content if metadata doesn't have it\n try {\n const content =\n typeof toolResult.content === 'string'\n ? JSON.parse(toolResult.content)\n : toolResult.content;\n\n if (content?.quota_limit?.detected) {\n return content.quota_limit;\n }\n } catch {\n // Ignore parse errors\n }\n\n return null;\n }\n\n /**\n * Handle iteration errors with recovery strategies\n */\n private async handleIterationError(\n context: ExecutionContext,\n error: unknown,\n iterationNumber: number,\n ): Promise<boolean> {\n const mcpError = this.wrapError(error);\n const errorType = mcpError.type;\n\n context.statistics.errorBreakdown[errorType] =\n (context.statistics.errorBreakdown[errorType] || 0) + 1;\n\n // Check if we should continue on this error type\n const shouldContinue = this.engineConfig.errorRecovery.continueOnError[errorType] ?? false;\n if (!shouldContinue) {\n return false;\n }\n\n // Attempt recovery if strategy exists\n const customStrategy = this.engineConfig.errorRecovery.customStrategies[errorType];\n if (customStrategy) {\n try {\n const recovered = await customStrategy(mcpError);\n if (recovered) {\n this.emit('error:recovered', { context, error: mcpError, iterationNumber });\n return true;\n }\n } catch (recoveryError) {\n this.emit('error:recovery-failed', {\n context,\n error: mcpError,\n recoveryError,\n iterationNumber,\n });\n }\n }\n\n // Apply retry delay if configured\n const retryDelay = this.engineConfig.errorRecovery.retryDelays[errorType] || 0;\n if (retryDelay > 0) {\n await this.sleep(retryDelay);\n }\n\n this.emit('error:continuing', { context, error: mcpError, iterationNumber });\n return true;\n }\n\n /**\n * Process individual progress events\n */\n private async processProgressEvent(\n context: ExecutionContext,\n event: ProgressEvent,\n ): Promise<void> {\n // Apply filters\n for (const filter of this.engineConfig.progressConfig.filters) {\n if (!filter.predicate(event)) {\n return;\n }\n }\n\n // Update session activity\n context.sessionContext = {\n ...context.sessionContext,\n lastActivity: new Date(),\n };\n\n this.emit('progress:processed', { context, event });\n }\n\n /**\n * Update execution statistics\n */\n private updateStatistics(context: ExecutionContext, iteration: IterationResult): void {\n const stats = context.statistics;\n\n stats.totalIterations++;\n stats.totalToolCalls++;\n\n if (iteration.success) {\n stats.successfulIterations++;\n } else {\n stats.failedIterations++;\n }\n\n // Update average iteration duration\n const totalDuration =\n stats.averageIterationDuration * (stats.totalIterations - 1) + iteration.duration;\n stats.averageIterationDuration = totalDuration / stats.totalIterations;\n\n // Update performance metrics\n this.updatePerformanceMetrics(context);\n }\n\n /**\n * Update performance metrics\n */\n private updatePerformanceMetrics(context: ExecutionContext): void {\n const metrics = context.statistics.performanceMetrics;\n\n // Get current resource usage\n const memUsage = process.memoryUsage();\n metrics.memoryUsage = memUsage.heapUsed;\n\n // Calculate throughput\n const duration = Date.now() - context.startTime.getTime();\n const durationMinutes = duration / (1000 * 60);\n\n if (durationMinutes > 0) {\n metrics.throughput.iterationsPerMinute = context.statistics.totalIterations / durationMinutes;\n metrics.throughput.toolCallsPerMinute = context.statistics.totalToolCalls / durationMinutes;\n metrics.throughput.progressEventsPerSecond =\n context.statistics.totalProgressEvents / (duration / 1000);\n }\n }\n\n /**\n * Check if iteration loop should stop\n */\n private shouldStopIterating(context: ExecutionContext, iterationNumber: number): boolean {\n // Check abort signal\n if (context.abortController.signal.aborted) {\n return true;\n }\n\n // Check max iterations\n if (context.request.maxIterations !== -1 && iterationNumber > context.request.maxIterations) {\n return true;\n }\n\n // Check for shutdown\n if (this.isShuttingDown) {\n return true;\n }\n\n return false;\n }\n\n /**\n * Check abort signal and throw if aborted\n */\n private checkAbortSignal(context: ExecutionContext): void {\n if (context.abortController.signal.aborted) {\n throw new Error('Execution aborted');\n }\n }\n\n /**\n * Get tool name for subagent\n */\n private getToolNameForSubagent(subagent: SubagentType): string {\n const mapping: Record<SubagentType, string> = {\n claude: 'claude_subagent',\n cursor: 'cursor_subagent',\n codex: 'codex_subagent',\n gemini: 'gemini_subagent',\n pi: 'pi_subagent',\n };\n\n return mapping[subagent] || 'claude_subagent';\n }\n\n /**\n * Wrap unknown errors as execution errors\n */\n private wrapError(error: unknown): ExecutionError {\n if (error instanceof ExecutionError) {\n return error;\n }\n\n // Classify common transport/socket failures as connection errors so the loop can continue\n const msg = error instanceof Error ? `${error.name}: ${error.message}` : String(error);\n const lower = msg.toLowerCase();\n const isConnectionLike = [\n 'epipe',\n 'broken pipe',\n 'econnreset',\n 'socket hang up',\n 'err_socket_closed',\n 'connection reset by peer',\n ].some((token) => lower.includes(token));\n\n if (isConnectionLike) {\n return {\n type: 'connection',\n message: msg,\n timestamp: new Date(),\n code: 'MCP_CONNECTION_LOST' as any,\n } as any;\n }\n\n // Fallback: treat as tool execution error\n return {\n type: 'tool_execution',\n message: msg,\n timestamp: new Date(),\n } as any;\n }\n\n /**\n * Determine execution status from error\n */\n private determineErrorStatus(error: ExecutionError): ExecutionStatus {\n switch (error.type) {\n case 'rate_limit':\n return ExecutionStatus.RATE_LIMITED;\n case 'timeout':\n return ExecutionStatus.TIMEOUT;\n default:\n return ExecutionStatus.FAILED;\n }\n }\n\n /**\n * Create final execution result\n */\n private createExecutionResult(context: ExecutionContext): ExecutionResult {\n const endTime = context.endTime || new Date();\n return {\n request: context.request,\n status: context.status,\n startTime: context.startTime,\n endTime,\n duration: endTime.getTime() - context.startTime.getTime(),\n iterations: context.iterations,\n statistics: context.statistics,\n ...(context.error !== undefined && context.error !== null && { error: context.error }),\n sessionContext: context.sessionContext,\n progressEvents: context.progressEvents,\n };\n }\n\n /**\n * Cancel an execution\n */\n private async cancelExecution(context: ExecutionContext): Promise<void> {\n context.abortController.abort();\n context.status = ExecutionStatus.CANCELLED;\n this.emit('execution:cancelled', { context });\n }\n\n /**\n * Cleanup execution resources\n */\n private async cleanupExecution(context: ExecutionContext): Promise<void> {\n // Cleanup would happen here\n this.emit('execution:cleanup', { context });\n }\n\n /**\n * Calculate average iteration duration across contexts\n */\n private calculateAverageIterationDuration(contexts: ExecutionContext[]): number {\n if (contexts.length === 0) return 0;\n\n const totalDuration = contexts.reduce(\n (sum, ctx) => sum + ctx.statistics.averageIterationDuration * ctx.statistics.totalIterations,\n 0,\n );\n const totalIterations = contexts.reduce((sum, ctx) => sum + ctx.statistics.totalIterations, 0);\n\n return totalIterations > 0 ? totalDuration / totalIterations : 0;\n }\n\n /**\n * Aggregate error breakdown across contexts\n */\n private aggregateErrorBreakdown(contexts: ExecutionContext[]): Record<string, number> {\n const breakdown: Record<string, number> = {};\n\n for (const context of contexts) {\n for (const [errorType, count] of Object.entries(context.statistics.errorBreakdown)) {\n breakdown[errorType] = (breakdown[errorType] || 0) + count;\n }\n }\n\n return breakdown;\n }\n\n /**\n * Calculate performance metrics across contexts\n */\n private calculatePerformanceMetrics(contexts: ExecutionContext[]): PerformanceMetrics {\n if (contexts.length === 0) {\n return {\n cpuUsage: 0,\n memoryUsage: 0,\n networkRequests: 0,\n fileSystemOperations: 0,\n throughput: {\n iterationsPerMinute: 0,\n progressEventsPerSecond: 0,\n toolCallsPerMinute: 0,\n },\n };\n }\n\n // Aggregate metrics from all contexts\n const avgMetrics = contexts.reduce(\n (acc, ctx) => ({\n cpuUsage: acc.cpuUsage + ctx.statistics.performanceMetrics.cpuUsage,\n memoryUsage: acc.memoryUsage + ctx.statistics.performanceMetrics.memoryUsage,\n networkRequests: acc.networkRequests + ctx.statistics.performanceMetrics.networkRequests,\n fileSystemOperations:\n acc.fileSystemOperations + ctx.statistics.performanceMetrics.fileSystemOperations,\n throughput: {\n iterationsPerMinute:\n acc.throughput.iterationsPerMinute +\n ctx.statistics.performanceMetrics.throughput.iterationsPerMinute,\n progressEventsPerSecond:\n acc.throughput.progressEventsPerSecond +\n ctx.statistics.performanceMetrics.throughput.progressEventsPerSecond,\n toolCallsPerMinute:\n acc.throughput.toolCallsPerMinute +\n ctx.statistics.performanceMetrics.throughput.toolCallsPerMinute,\n },\n }),\n {\n cpuUsage: 0,\n memoryUsage: 0,\n networkRequests: 0,\n fileSystemOperations: 0,\n throughput: {\n iterationsPerMinute: 0,\n progressEventsPerSecond: 0,\n toolCallsPerMinute: 0,\n },\n },\n );\n\n // Average the metrics\n const count = contexts.length;\n return {\n cpuUsage: avgMetrics.cpuUsage / count,\n memoryUsage: avgMetrics.memoryUsage / count,\n networkRequests: avgMetrics.networkRequests / count,\n fileSystemOperations: avgMetrics.fileSystemOperations / count,\n throughput: {\n iterationsPerMinute: avgMetrics.throughput.iterationsPerMinute / count,\n progressEventsPerSecond: avgMetrics.throughput.progressEventsPerSecond / count,\n toolCallsPerMinute: avgMetrics.throughput.toolCallsPerMinute / count,\n },\n };\n }\n\n /**\n * Sleep utility for delays\n */\n private async sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n\n// =============================================================================\n// Internal Types\n// =============================================================================\n\n/**\n * Internal execution context\n */\ninterface ExecutionContext {\n request: ExecutionRequest;\n status: ExecutionStatus;\n startTime: Date;\n endTime: Date | null;\n iterations: IterationResult[];\n statistics: ExecutionStatistics;\n progressEvents: ProgressEvent[];\n error: ExecutionError | null;\n abortController: AbortController;\n sessionContext: SessionContext;\n rateLimitInfo: RateLimitInfo;\n}\n\n// =============================================================================\n// Factory Functions\n// =============================================================================\n\n/**\n * Create an execution engine with default configuration\n *\n * @param config - Base juno-task configuration\n * @returns Configured execution engine\n */\nexport function createExecutionEngine(config: JunoTaskConfig): ExecutionEngine {\n return new ExecutionEngine({\n config,\n errorRecovery: DEFAULT_ERROR_RECOVERY_CONFIG,\n rateLimitConfig: DEFAULT_RATE_LIMIT_CONFIG,\n progressConfig: DEFAULT_PROGRESS_CONFIG,\n });\n}\n\n/**\n * Create an execution request with defaults\n *\n * @param options - Request options\n * @returns Execution request\n */\nexport function createExecutionRequest(options: {\n instruction: string;\n subagent?: SubagentType;\n backend?: BackendType;\n workingDirectory?: string;\n maxIterations?: number;\n model?: string;\n agents?: string;\n tools?: string[];\n allowedTools?: string[];\n appendAllowedTools?: string[];\n disallowedTools?: string[];\n requestId?: string;\n mcpServerName?: string;\n resume?: string;\n continueConversation?: boolean;\n thinking?: string;\n live?: boolean;\n}): ExecutionRequest {\n const result: ExecutionRequest = {\n requestId: options.requestId || `req-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,\n instruction: options.instruction,\n subagent: options.subagent || 'claude',\n backend: options.backend || 'shell',\n workingDirectory: options.workingDirectory || process.cwd(),\n maxIterations: options.maxIterations ?? 1,\n };\n\n if (options.model !== undefined) {\n (result as any).model = options.model;\n }\n\n if (options.agents !== undefined) {\n (result as any).agents = options.agents;\n }\n\n if (options.tools !== undefined) {\n (result as any).tools = options.tools;\n }\n\n if (options.allowedTools !== undefined) {\n (result as any).allowedTools = options.allowedTools;\n }\n\n if (options.appendAllowedTools !== undefined) {\n (result as any).appendAllowedTools = options.appendAllowedTools;\n }\n\n if (options.disallowedTools !== undefined) {\n (result as any).disallowedTools = options.disallowedTools;\n }\n\n if (options.mcpServerName !== undefined) {\n (result as any).mcpServerName = options.mcpServerName;\n }\n\n if (options.resume !== undefined) {\n (result as any).resume = options.resume;\n }\n\n if (options.continueConversation !== undefined) {\n (result as any).continueConversation = options.continueConversation;\n }\n\n if (options.thinking !== undefined) {\n (result as any).thinking = options.thinking;\n }\n\n if (options.live !== undefined) {\n (result as any).live = options.live;\n }\n\n return result;\n}\n","/**\n * Hook execution utility module for juno-task-ts\n *\n * Provides robust hook execution functionality with comprehensive logging,\n * error handling, and execution context tracking.\n *\n * @module utils/hooks\n */\n\nimport { execa } from 'execa';\nimport { logger, LogContext } from '../cli/utils/advanced-logger.js';\n\n/**\n * Supported hook types for lifecycle execution\n */\nexport type HookType = 'START_RUN' | 'START_ITERATION' | 'END_ITERATION' | 'END_RUN' | 'ON_STALE';\n\n/**\n * Hook configuration interface\n */\nexport interface Hook {\n /** List of bash commands to execute for this hook */\n commands: string[];\n}\n\n/**\n * Complete hooks configuration mapping hook types to their configurations\n */\nexport interface HooksConfig {\n [key: string]: Hook;\n}\n\n/**\n * Execution context for hooks - provides information about the current execution state\n */\nexport interface HookExecutionContext {\n /** Current iteration number (for iteration-based hooks) */\n iteration?: number;\n /** Session ID for tracking */\n sessionId?: string;\n /** Working directory for command execution */\n workingDirectory?: string;\n /** Additional metadata */\n metadata?: Record<string, any>;\n /** Run ID for tracking across hooks */\n runId?: string;\n /** Total iterations planned */\n totalIterations?: number;\n}\n\n/**\n * Result of a single command execution within a hook\n */\nexport interface CommandExecutionResult {\n /** The command that was executed */\n command: string;\n /** Exit code (0 for success) */\n exitCode: number;\n /** Standard output */\n stdout: string;\n /** Standard error output */\n stderr: string;\n /** Execution duration in milliseconds */\n duration: number;\n /** Whether the command succeeded */\n success: boolean;\n /** Error if execution failed */\n error?: Error;\n}\n\n/**\n * Result of executing all commands in a hook\n */\nexport interface HookExecutionResult {\n /** Hook type that was executed */\n hookType: HookType;\n /** Total execution duration for all commands */\n totalDuration: number;\n /** Results for each command */\n commandResults: CommandExecutionResult[];\n /** Overall success (true if all commands succeeded) */\n success: boolean;\n /** Number of commands executed */\n commandsExecuted: number;\n /** Number of commands that failed */\n commandsFailed: number;\n}\n\n/**\n * Hook execution options\n */\nexport interface HookExecutionOptions {\n /** Maximum timeout per command in milliseconds (default: 300000 = 5 minutes) */\n commandTimeout?: number | undefined;\n /** Environment variables to pass to commands */\n env?: Record<string, string> | undefined;\n /** Whether to continue executing commands if one fails (default: true) */\n continueOnError?: boolean | undefined;\n /** Custom logger context (default: 'SYSTEM') */\n logContext?: LogContext | undefined;\n}\n\n/**\n * Create a context-specific logger for hook execution\n */\nconst hookLogger = logger.child(LogContext.SYSTEM);\n\n/**\n * Execute a specific hook type with the provided context\n *\n * This is the main entry point for hook execution. It handles:\n * - Hook existence validation\n * - Sequential command execution\n * - Comprehensive logging with execution context\n * - Robust error handling (log but don't throw)\n * - Performance tracking\n *\n * @param hookType - The type of hook to execute\n * @param hooks - The complete hooks configuration\n * @param context - Execution context with iteration, session info, etc.\n * @param options - Additional execution options\n * @returns Promise that resolves when all commands complete (never throws)\n *\n * @example\n * ```typescript\n * const hooks = {\n * START_ITERATION: {\n * commands: ['echo \"Starting iteration $ITERATION\"', 'npm test']\n * }\n * };\n *\n * const context = {\n * iteration: 1,\n * sessionId: 'session-123',\n * workingDirectory: '/path/to/project'\n * };\n *\n * await executeHook('START_ITERATION', hooks, context);\n * ```\n */\nexport async function executeHook(\n hookType: HookType,\n hooks: HooksConfig,\n context: HookExecutionContext = {},\n options: HookExecutionOptions = {},\n): Promise<HookExecutionResult> {\n const startTime = Date.now();\n const {\n commandTimeout = 300000, // 5 minutes default (increased from 30s to support long-running hook scripts)\n env = {},\n continueOnError = true,\n logContext = LogContext.SYSTEM,\n } = options;\n\n // Create context-specific logger\n const contextLogger = logger.child(logContext);\n\n contextLogger.debug(`Starting hook execution: ${hookType}`, {\n context,\n workingDirectory: context.workingDirectory || process.cwd(),\n commandTimeout,\n continueOnError,\n });\n\n // Check if hook exists\n const hook = hooks[hookType];\n if (!hook) {\n contextLogger.debug(`Hook ${hookType} not defined - skipping execution`);\n return {\n hookType,\n totalDuration: Date.now() - startTime,\n commandResults: [],\n success: true,\n commandsExecuted: 0,\n commandsFailed: 0,\n };\n }\n\n // Check if hook has commands\n if (!hook.commands || hook.commands.length === 0) {\n contextLogger.debug(`Hook ${hookType} has no commands - skipping execution`);\n return {\n hookType,\n totalDuration: Date.now() - startTime,\n commandResults: [],\n success: true,\n commandsExecuted: 0,\n commandsFailed: 0,\n };\n }\n\n contextLogger.debug(`Executing ${hook.commands.length} commands for hook ${hookType}`);\n\n const commandResults: CommandExecutionResult[] = [];\n let commandsFailed = 0;\n\n // Execute each command sequentially\n for (let i = 0; i < hook.commands.length; i++) {\n const command = hook.commands[i]!;\n const commandStartTime = Date.now();\n\n contextLogger.debug(`Executing command ${i + 1}/${hook.commands.length}: ${command}`, {\n commandIndex: i,\n totalCommands: hook.commands.length,\n });\n\n try {\n // Prepare environment variables with context\n const execEnv = {\n ...process.env,\n ...env,\n // Add context as environment variables\n HOOK_TYPE: hookType,\n ITERATION: context.iteration?.toString() || '',\n SESSION_ID: context.sessionId || '',\n RUN_ID: context.runId || '',\n TOTAL_ITERATIONS: context.totalIterations?.toString() || '',\n // Add any metadata as prefixed environment variables\n ...Object.fromEntries(\n Object.entries(context.metadata || {}).map(([key, value]) => [\n `JUNO_${key.toUpperCase()}`,\n String(value),\n ]),\n ),\n };\n\n // Execute command with timeout and proper working directory\n //\n // CRITICAL: Using `input: ''` to properly close stdin\n //\n // History of stdin handling issues:\n // - Issue #40: Added stdin: 'ignore' - fixed blocking but broke internal pipes\n // - Issue #41: Removed stdin: 'ignore', used default 'pipe' - allowed internal\n // pipes to work but caused commands to hang indefinitely when subprocess\n // tried to read stdin (because the stdin pipe was never closed)\n // - Issue #42 (current): Commands like `juno-kanban ... | grep -q \"...\"` would\n // hang for 5 minutes (timeout) because the shell's stdin pipe was never closed,\n // causing subprocesses to block waiting for EOF on stdin.\n //\n // Solution: Use `input: ''` which:\n // 1. Provides empty input to the subprocess\n // 2. Properly closes stdin (sends EOF)\n // 3. Allows internal pipes to work (shell manages its own pipes)\n // 4. Prevents commands from hanging waiting for stdin\n //\n // The key insight: `input: ''` tells execa to write an empty string to stdin\n // and then close it, which signals EOF to the subprocess. This is different\n // from `stdin: 'pipe'` (default) which leaves the pipe open indefinitely.\n const result = await execa(command, {\n shell: true,\n timeout: commandTimeout,\n cwd: context.workingDirectory || process.cwd(),\n env: execEnv,\n // Capture both stdout and stderr\n all: true,\n reject: false, // Don't throw on non-zero exit codes\n // Use input: '' to provide empty stdin and properly close it (sends EOF)\n // This prevents commands from hanging waiting for stdin while still\n // allowing internal pipe operations to work correctly\n input: '',\n });\n\n const duration = Date.now() - commandStartTime;\n const success = result.exitCode === 0;\n\n const commandResult: CommandExecutionResult = {\n command,\n exitCode: result.exitCode ?? -1,\n stdout: result.stdout || '',\n stderr: result.stderr || '',\n duration,\n success,\n };\n\n commandResults.push(commandResult);\n\n if (success) {\n contextLogger.debug(`Command completed successfully`, {\n command,\n exitCode: result.exitCode,\n duration,\n stdout: result.stdout ? result.stdout.substring(0, 500) : undefined, // Truncate for logging\n });\n\n // Log stdout if present\n if (result.stdout) {\n contextLogger.debug(`Command stdout:`, { stdout: result.stdout });\n }\n } else {\n commandsFailed++;\n contextLogger.error(`Command failed`, {\n command,\n exitCode: result.exitCode,\n duration,\n stderr: result.stderr,\n stdout: result.stdout,\n });\n\n // Log stderr if present\n if (result.stderr) {\n contextLogger.error(`Command stderr:`, { stderr: result.stderr });\n }\n\n // If we shouldn't continue on error, break the loop\n if (!continueOnError) {\n contextLogger.warn(\n `Stopping hook execution due to command failure (continueOnError=false)`,\n );\n break;\n }\n }\n } catch (error) {\n const duration = Date.now() - commandStartTime;\n commandsFailed++;\n\n let errorMessage = 'Unknown error';\n let isTimeout = false;\n\n if (error instanceof Error) {\n errorMessage = error.message;\n // Check for execa-specific timeout property\n isTimeout = 'timedOut' in error ? Boolean((error as any).timedOut) : false;\n }\n\n const commandResult: CommandExecutionResult = {\n command,\n exitCode: -1,\n stdout: '',\n stderr: errorMessage,\n duration,\n success: false,\n error: error as Error,\n };\n\n commandResults.push(commandResult);\n\n if (isTimeout) {\n contextLogger.error(`Command timed out after ${commandTimeout}ms`, {\n command,\n timeout: commandTimeout,\n duration,\n error: errorMessage,\n });\n } else {\n contextLogger.error(`Command execution failed`, {\n command,\n duration,\n error: errorMessage,\n });\n }\n\n // If we shouldn't continue on error, break the loop\n if (!continueOnError) {\n contextLogger.warn(\n `Stopping hook execution due to command failure (continueOnError=false)`,\n );\n break;\n }\n }\n }\n\n const totalDuration = Date.now() - startTime;\n const success = commandsFailed === 0;\n const commandsExecuted = commandResults.length;\n\n const result: HookExecutionResult = {\n hookType,\n totalDuration,\n commandResults,\n success,\n commandsExecuted,\n commandsFailed,\n };\n\n contextLogger.debug(`Hook execution completed`, {\n hookType,\n totalDuration,\n commandsExecuted,\n commandsFailed,\n success,\n });\n\n return result;\n}\n\n/**\n * Execute multiple hooks in sequence\n *\n * Convenience function for executing multiple hooks with the same context.\n * Each hook is executed independently - failure of one hook does not stop\n * execution of subsequent hooks.\n *\n * @param hookTypes - Array of hook types to execute\n * @param hooks - The complete hooks configuration\n * @param context - Execution context\n * @param options - Execution options\n * @returns Promise resolving to array of hook execution results\n */\nexport async function executeHooks(\n hookTypes: HookType[],\n hooks: HooksConfig,\n context: HookExecutionContext = {},\n options: HookExecutionOptions = {},\n): Promise<HookExecutionResult[]> {\n const results: HookExecutionResult[] = [];\n\n hookLogger.debug(`Starting batch hook execution`, {\n hookTypes,\n context,\n });\n\n for (const hookType of hookTypes) {\n const result = await executeHook(hookType, hooks, context, options);\n results.push(result);\n }\n\n const totalSuccess = results.every((r) => r.success);\n const totalCommands = results.reduce((sum, r) => sum + r.commandsExecuted, 0);\n const totalFailed = results.reduce((sum, r) => sum + r.commandsFailed, 0);\n\n hookLogger.debug(`Batch hook execution completed`, {\n hookTypes,\n totalHooks: results.length,\n totalCommands,\n totalFailed,\n success: totalSuccess,\n });\n\n return results;\n}\n\n/**\n * Validate hooks configuration\n *\n * Checks that all hook configurations are valid and provides warnings\n * for common issues.\n *\n * @param hooks - Hooks configuration to validate\n * @returns Validation result with any issues found\n */\nexport function validateHooksConfig(hooks: HooksConfig): {\n valid: boolean;\n issues: string[];\n warnings: string[];\n} {\n const issues: string[] = [];\n const warnings: string[] = [];\n\n const validHookTypes: HookType[] = [\n 'START_RUN',\n 'START_ITERATION',\n 'END_ITERATION',\n 'END_RUN',\n 'ON_STALE',\n ];\n\n for (const [hookType, hook] of Object.entries(hooks)) {\n // Check if hook type is valid\n if (!validHookTypes.includes(hookType as HookType)) {\n warnings.push(\n `Unknown hook type: ${hookType}. Valid types are: ${validHookTypes.join(', ')}`,\n );\n }\n\n // Check if hook has commands array\n if (!hook.commands) {\n issues.push(`Hook ${hookType} is missing 'commands' array`);\n continue;\n }\n\n if (!Array.isArray(hook.commands)) {\n issues.push(`Hook ${hookType} 'commands' must be an array`);\n continue;\n }\n\n // Check if commands are strings\n for (let i = 0; i < hook.commands.length; i++) {\n const command = hook.commands[i];\n if (typeof command !== 'string') {\n issues.push(`Hook ${hookType} command ${i} must be a string, got ${typeof command}`);\n } else if (command.trim() === '') {\n warnings.push(`Hook ${hookType} command ${i} is empty`);\n }\n }\n\n // Warn about potentially dangerous commands\n const dangerousPatterns = [/rm\\s+-rf\\s+\\//, /sudo\\s+rm/, /format\\s+c:/i, /del\\s+\\/s/i];\n\n for (const command of hook.commands) {\n if (typeof command === 'string') {\n for (const pattern of dangerousPatterns) {\n if (pattern.test(command)) {\n warnings.push(`Hook ${hookType} contains potentially dangerous command: ${command}`);\n }\n }\n }\n }\n }\n\n return {\n valid: issues.length === 0,\n issues,\n warnings,\n };\n}\n\n/**\n * Default export for convenience\n */\nexport default {\n executeHook,\n executeHooks,\n validateHooksConfig,\n};\n","/**\n * Core session management module for juno-code\n * @module core/session\n */\nimport * as path from 'node:path';\nimport * as fs from 'node:fs';\nimport { v4 as uuidv4 } from 'uuid';\nimport type { JunoTaskConfig, SessionStatus, SubagentType } from '../types/index';\n\n/** Session metadata */\nexport interface SessionInfo {\n id: string;\n name?: string;\n status: SessionStatus;\n subagent: SubagentType;\n createdAt: Date;\n updatedAt: Date;\n completedAt?: Date;\n workingDirectory: string;\n config: Partial<JunoTaskConfig>;\n tags: string[];\n metadata: Record<string, any>;\n}\n\n/** Session statistics - essential counters only */\nexport interface SessionStatistics {\n duration: number;\n iterations: number;\n toolCalls: number;\n errorCount: number;\n}\n\n/** Complete session state */\nexport interface Session {\n info: SessionInfo;\n context: { workingDirectory: string; config: JunoTaskConfig };\n statistics: SessionStatistics;\n history: SessionHistoryEntry[];\n result?: { success: boolean; output?: string; error?: string; finalState?: any };\n}\n\n/** History entry for conversation tracking */\nexport interface SessionHistoryEntry {\n id: string;\n timestamp: Date;\n type: 'prompt' | 'response' | 'tool_call' | 'error' | 'system';\n content: string;\n data?: any;\n duration?: number;\n iteration?: number;\n}\n\n/** Persistence layer abstraction */\nexport interface SessionStorage {\n saveSession(session: Session): Promise<void>;\n loadSession(sessionId: string): Promise<Session | null>;\n listSessions(filter?: SessionListFilter): Promise<SessionInfo[]>;\n removeSession(sessionId: string): Promise<void>;\n sessionExists(sessionId: string): Promise<boolean>;\n cleanup(options: CleanupOptions): Promise<void>;\n}\n\n/** Filter criteria for listing sessions */\nexport interface SessionListFilter {\n status?: SessionStatus[];\n subagent?: SubagentType[];\n dateRange?: { start?: Date; end?: Date };\n tags?: string[];\n limit?: number;\n offset?: number;\n sortBy?: 'createdAt' | 'updatedAt' | 'name';\n sortOrder?: 'asc' | 'desc';\n}\n\n/** Options for storage cleanup */\nexport interface CleanupOptions {\n removeEmpty?: boolean;\n removeOlderThanDays?: number;\n removeStatus?: SessionStatus[];\n dryRun?: boolean;\n}\n\n/** File-based session storage implementation */\nexport class FileSessionStorage implements SessionStorage {\n private readonly baseDir: string;\n private readonly sessionsDir: string;\n\n constructor(baseDir: string) {\n this.baseDir = path.resolve(baseDir);\n this.sessionsDir = path.join(this.baseDir, 'sessions');\n }\n\n async initialize(): Promise<void> {\n await fs.promises.mkdir(this.sessionsDir, { recursive: true });\n }\n\n private getSessionPath(sessionId: string): string {\n return path.join(this.sessionsDir, `${sessionId}.json`);\n }\n\n async saveSession(session: Session): Promise<void> {\n await this.initialize();\n const sessionPath = this.getSessionPath(session.info.id);\n const serializable = {\n ...session,\n info: {\n ...session.info,\n createdAt: session.info.createdAt.toISOString(),\n updatedAt: session.info.updatedAt.toISOString(),\n completedAt: session.info.completedAt?.toISOString(),\n },\n history: session.history.map((entry) => ({\n ...entry,\n timestamp: entry.timestamp.toISOString(),\n })),\n };\n await fs.promises.writeFile(sessionPath, JSON.stringify(serializable, null, 2), 'utf-8');\n }\n\n async loadSession(sessionId: string): Promise<Session | null> {\n const sessionPath = this.getSessionPath(sessionId);\n try {\n const data = await fs.promises.readFile(sessionPath, 'utf-8');\n const parsed = JSON.parse(data);\n return {\n ...parsed,\n info: {\n ...parsed.info,\n createdAt: new Date(parsed.info.createdAt),\n updatedAt: new Date(parsed.info.updatedAt),\n completedAt: parsed.info.completedAt ? new Date(parsed.info.completedAt) : undefined,\n },\n history: parsed.history.map((entry: any) => ({\n ...entry,\n timestamp: new Date(entry.timestamp),\n })),\n };\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;\n throw new Error(`Failed to load session ${sessionId}: ${error}`);\n }\n }\n\n async listSessions(filter?: SessionListFilter): Promise<SessionInfo[]> {\n await this.initialize();\n try {\n const files = await fs.promises.readdir(this.sessionsDir);\n const sessionFiles = files.filter((file) => file.endsWith('.json'));\n const sessions: SessionInfo[] = [];\n for (const file of sessionFiles) {\n try {\n const session = await this.loadSession(path.basename(file, '.json'));\n if (session) sessions.push(session.info);\n } catch (error) {\n console.warn(`Failed to load session from ${file}: ${error}`);\n }\n }\n\n let filtered = sessions;\n if (filter) {\n if (filter.status) filtered = filtered.filter((s) => filter.status!.includes(s.status));\n if (filter.subagent)\n filtered = filtered.filter((s) => filter.subagent!.includes(s.subagent));\n if (filter.dateRange) {\n if (filter.dateRange.start)\n filtered = filtered.filter((s) => s.createdAt >= filter.dateRange!.start!);\n if (filter.dateRange.end)\n filtered = filtered.filter((s) => s.createdAt <= filter.dateRange!.end!);\n }\n if (filter.tags && filter.tags.length > 0)\n filtered = filtered.filter((s) => filter.tags!.some((tag) => s.tags.includes(tag)));\n\n const sortBy = filter.sortBy || 'updatedAt';\n const sortOrder = filter.sortOrder || 'desc';\n filtered.sort((a, b) => {\n const aVal = a[sortBy],\n bVal = b[sortBy];\n if (aVal === undefined && bVal === undefined) return 0;\n if (aVal === undefined) return 1;\n if (bVal === undefined) return -1;\n if (aVal < bVal) return sortOrder === 'asc' ? -1 : 1;\n if (aVal > bVal) return sortOrder === 'asc' ? 1 : -1;\n return 0;\n });\n if (filter.offset) filtered = filtered.slice(filter.offset);\n if (filter.limit) filtered = filtered.slice(0, filter.limit);\n }\n return filtered;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [];\n throw error;\n }\n }\n\n async removeSession(sessionId: string): Promise<void> {\n try {\n await fs.promises.unlink(this.getSessionPath(sessionId));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT')\n throw new Error(`Failed to remove session ${sessionId}: ${error}`);\n }\n }\n\n async sessionExists(sessionId: string): Promise<boolean> {\n try {\n await fs.promises.access(this.getSessionPath(sessionId), fs.constants.F_OK);\n return true;\n } catch {\n return false;\n }\n }\n\n async cleanup(options: CleanupOptions): Promise<void> {\n await this.initialize();\n const files = await fs.promises.readdir(this.sessionsDir);\n const sessionFiles = files.filter((f) => f.endsWith('.json'));\n\n for (const file of sessionFiles) {\n const sessionId = path.basename(file, '.json');\n let shouldRemove = false;\n let session: Session | null = null;\n\n try {\n session = await this.loadSession(sessionId);\n } catch {\n // Corrupted/unreadable file — treat as removable when removeEmpty is set\n if (options.removeEmpty) shouldRemove = true;\n }\n\n if (session) {\n if (options.removeOlderThanDays) {\n const cutoff = new Date();\n cutoff.setDate(cutoff.getDate() - options.removeOlderThanDays);\n if (session.info.createdAt < cutoff) shouldRemove = true;\n }\n if (options.removeStatus && options.removeStatus.includes(session.info.status))\n shouldRemove = true;\n if (options.removeEmpty && session.history.length === 0 && !session.result)\n shouldRemove = true;\n }\n\n if (shouldRemove && !options.dryRun) await this.removeSession(sessionId);\n }\n }\n}\n\n/** Session manager - plain class for session lifecycle management */\nexport class SessionManager {\n private storage: SessionStorage;\n private activeSessions: Map<string, Session> = new Map();\n\n constructor(storage: SessionStorage) {\n this.storage = storage;\n }\n\n async createSession(options: {\n name?: string;\n subagent: SubagentType;\n config: JunoTaskConfig;\n tags?: string[];\n metadata?: Record<string, any>;\n }): Promise<Session> {\n const sessionId = uuidv4();\n const now = new Date();\n const session: Session = {\n info: {\n id: sessionId,\n ...(options.name !== undefined && { name: options.name }),\n status: 'running',\n subagent: options.subagent,\n createdAt: now,\n updatedAt: now,\n workingDirectory: options.config.workingDirectory,\n config: { ...options.config },\n tags: options.tags || [],\n metadata: options.metadata || {},\n },\n context: {\n workingDirectory: options.config.workingDirectory,\n config: { ...options.config },\n },\n statistics: { duration: 0, iterations: 0, toolCalls: 0, errorCount: 0 },\n history: [],\n };\n this.activeSessions.set(sessionId, session);\n await this.storage.saveSession(session);\n return session;\n }\n\n async updateSession(\n sessionId: string,\n updates: {\n status?: SessionStatus;\n name?: string;\n tags?: string[];\n metadata?: Record<string, any>;\n statistics?: Partial<SessionStatistics>;\n result?: Session['result'];\n },\n ): Promise<void> {\n let session = this.activeSessions.get(sessionId);\n if (!session) {\n const loaded = await this.storage.loadSession(sessionId);\n session = loaded || undefined;\n if (!session) throw new Error(`Session ${sessionId} not found`);\n }\n if (updates.status) session.info.status = updates.status;\n if (updates.name) session.info.name = updates.name;\n if (updates.tags) session.info.tags = updates.tags;\n if (updates.metadata) session.info.metadata = { ...session.info.metadata, ...updates.metadata };\n if (updates.statistics) session.statistics = { ...session.statistics, ...updates.statistics };\n if (updates.result) session.result = updates.result;\n session.info.updatedAt = new Date();\n this.activeSessions.set(sessionId, session);\n await this.storage.saveSession(session);\n }\n\n async completeSession(\n sessionId: string,\n result: {\n success: boolean;\n output?: string;\n error?: string;\n finalState?: any;\n },\n ): Promise<void> {\n const now = new Date();\n await this.updateSession(sessionId, {\n status: result.success ? 'completed' : 'failed',\n result,\n });\n const session = await this.getSession(sessionId);\n if (session) {\n session.info.completedAt = now;\n session.statistics.duration = now.getTime() - session.info.createdAt.getTime();\n await this.storage.saveSession(session);\n this.activeSessions.delete(sessionId);\n }\n }\n\n async cancelSession(sessionId: string): Promise<void> {\n await this.updateSession(sessionId, { status: 'cancelled' });\n this.activeSessions.delete(sessionId);\n }\n\n async getSession(sessionId: string): Promise<Session | null> {\n return this.activeSessions.get(sessionId) || (await this.storage.loadSession(sessionId));\n }\n\n async listSessions(filter?: SessionListFilter): Promise<SessionInfo[]> {\n return await this.storage.listSessions(filter);\n }\n\n async removeSession(sessionId: string): Promise<void> {\n await this.storage.removeSession(sessionId);\n this.activeSessions.delete(sessionId);\n }\n\n async cleanupSessions(options: CleanupOptions): Promise<void> {\n await this.storage.cleanup(options);\n }\n\n async addHistoryEntry(\n sessionId: string,\n entry: Omit<SessionHistoryEntry, 'id' | 'timestamp'>,\n ): Promise<void> {\n const session = await this.getSession(sessionId);\n if (!session) throw new Error(`Session ${sessionId} not found`);\n session.history.push({ id: uuidv4(), timestamp: new Date(), ...entry });\n await this.storage.saveSession(session);\n }\n\n async updateStatistics(sessionId: string, stats: Partial<SessionStatistics>): Promise<void> {\n await this.updateSession(sessionId, { statistics: stats });\n }\n\n async recordToolCall(\n sessionId: string,\n toolCall: {\n name: string;\n duration: number;\n success: boolean;\n },\n ): Promise<void> {\n const session = await this.getSession(sessionId);\n if (!session) return;\n session.statistics.toolCalls++;\n if (!toolCall.success) session.statistics.errorCount++;\n await this.storage.saveSession(session);\n }\n\n async getSessionContext(\n sessionId: string,\n options: {\n includeHistory?: boolean;\n includeStats?: boolean;\n maxHistoryEntries?: number;\n } = {},\n ): Promise<string> {\n const session = await this.getSession(sessionId);\n if (!session) return `Session ${sessionId}: Not found`;\n\n const lines = [\n `Session ${sessionId} Context:`,\n `Status: ${session.info.status}`,\n `Subagent: ${session.info.subagent}`,\n `Created: ${session.info.createdAt.toISOString()}`,\n `Working Directory: ${session.context.workingDirectory}`,\n ];\n if (session.info.tags.length > 0) lines.push(`Tags: ${session.info.tags.join(', ')}`);\n if (options.includeStats) {\n lines.push('', 'Statistics:');\n lines.push(` Iterations: ${session.statistics.iterations}`);\n lines.push(` Tool Calls: ${session.statistics.toolCalls}`);\n lines.push(` Duration: ${session.statistics.duration}ms`);\n }\n if (options.includeHistory && session.history?.length > 0) {\n lines.push('', 'Recent History:');\n const recent = session.history.slice(-(options.maxHistoryEntries || 5));\n for (const e of recent) {\n const time = e.timestamp?.toISOString()?.split('T')[1]?.split('.')[0] || 'unknown';\n lines.push(` [${time}] ${e.type}: ${e.content.substring(0, 100)}...`);\n }\n }\n return lines.join('\\n');\n }\n\n async getSessionSummary(sessionId: string): Promise<{\n info: SessionInfo;\n statistics: SessionStatistics;\n summary: {\n totalDuration: string;\n iterationsPerMinute: number;\n toolCallsPerIteration: number;\n errorRate: number;\n };\n } | null> {\n const session = await this.getSession(sessionId);\n if (!session) return null;\n const mins = session.statistics.duration / 60_000;\n const ipm = mins > 0 ? session.statistics.iterations / mins : 0;\n const tcpi =\n session.statistics.iterations > 0\n ? session.statistics.toolCalls / session.statistics.iterations\n : 0;\n const er =\n session.statistics.toolCalls > 0\n ? session.statistics.errorCount / session.statistics.toolCalls\n : 0;\n return {\n info: session.info,\n statistics: session.statistics,\n summary: {\n totalDuration: this.formatDuration(session.statistics.duration),\n iterationsPerMinute: Number(ipm.toFixed(2)),\n toolCallsPerIteration: Number(tcpi.toFixed(2)),\n errorRate: Number(er.toFixed(3)),\n },\n };\n }\n\n private formatDuration(ms: number): string {\n const s = Math.floor(ms / 1000);\n const m = Math.floor(s / 60);\n const h = Math.floor(m / 60);\n if (h > 0) return `${h}h ${m % 60}m ${s % 60}s`;\n if (m > 0) return `${m}m ${s % 60}s`;\n return `${s}s`;\n }\n}\n\n/** Create a session manager with file storage */\nexport async function createSessionManager(config: JunoTaskConfig): Promise<SessionManager> {\n const storage = new FileSessionStorage(config.sessionDirectory);\n await storage.initialize();\n return new SessionManager(storage);\n}\n","/**\n * Environment Utilities Module for juno-task-ts\n *\n * Provides comprehensive environment variable handling and detection utilities\n * for the juno-task-ts CLI tool. This module includes environment detection,\n * terminal capabilities, platform information, configuration directories,\n * and MCP server path detection.\n *\n * @module utils/environment\n */\n\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport * as process from 'node:process';\nimport { promises as fs } from 'node:fs';\n// Conditional import for execSync to improve tree shaking\n// import { execSync } from 'node:child_process';\n\n// ============================================================================\n// Types and Interfaces\n// ============================================================================\n\n/**\n * Color support levels for terminal output\n */\nexport type ColorSupport = 'none' | 'basic' | '256' | 'truecolor';\n\n/**\n * Node.js environment types\n */\nexport type NodeEnvironment = 'development' | 'production' | 'test';\n\n/**\n * Operating system platforms\n */\nexport type Platform = 'win32' | 'darwin' | 'linux' | 'freebsd' | 'openbsd' | 'sunos' | 'aix';\n\n/**\n * System architectures\n */\nexport type Architecture =\n | 'arm'\n | 'arm64'\n | 'ia32'\n | 'mips'\n | 'mipsel'\n | 'ppc'\n | 'ppc64'\n | 's390'\n | 's390x'\n | 'x64';\n\n/**\n * Shell types\n */\nexport type ShellType = 'bash' | 'zsh' | 'fish' | 'cmd' | 'powershell' | 'unknown';\n\n/**\n * Process information interface\n */\nexport interface ProcessInfo {\n pid: number;\n ppid: number;\n platform: Platform;\n arch: Architecture;\n nodeVersion: string;\n uptime: number;\n cwd: string;\n execPath: string;\n argv: string[];\n env: Record<string, string | undefined>;\n}\n\n/**\n * Memory usage information\n */\nexport interface MemoryUsage {\n rss: number;\n heapTotal: number;\n heapUsed: number;\n external: number;\n arrayBuffers: number;\n}\n\n/**\n * CPU usage information\n */\nexport interface CpuUsage {\n user: number;\n system: number;\n}\n\n/**\n * MCP server environment configuration\n */\nexport interface MCPServerEnvironment {\n PATH: string;\n NODE_ENV: string;\n [key: string]: string;\n}\n\n// ============================================================================\n// Environment Detection\n// ============================================================================\n\n/**\n * Detect if running in a headless/CI environment where interactive prompts should be avoided.\n * Based on the Python implementation patterns from budi-cli.\n *\n * @returns True if running in headless/CI environment\n *\n * @example\n * ```typescript\n * if (isHeadlessEnvironment()) {\n * console.log('Using non-interactive mode');\n * }\n * ```\n */\nexport function isHeadlessEnvironment(): boolean {\n // Check for CI environment indicators (matches Python implementation)\n const ciIndicators = [\n 'CI',\n 'CONTINUOUS_INTEGRATION',\n 'GITHUB_ACTIONS',\n 'GITLAB_CI',\n 'JENKINS_URL',\n 'TRAVIS',\n 'CIRCLECI',\n 'PYTEST_CURRENT_TEST', // Pytest test runner\n 'JUNO_TASK_HEADLESS', // Our custom flag for headless testing\n 'NODE_ENV', // Additional Node.js specific\n ];\n\n for (const indicator of ciIndicators) {\n if (process.env[indicator]) {\n return true;\n }\n }\n\n // Check if stdin/stdout are connected to a terminal\n if (!process.stdin.isTTY || !process.stdout.isTTY) {\n return true;\n }\n\n return false;\n}\n\n/**\n * Detect if running in a continuous integration environment.\n *\n * @returns True if running in CI environment\n *\n * @example\n * ```typescript\n * if (isCIEnvironment()) {\n * console.log('Running in CI environment');\n * }\n * ```\n */\nexport function isCIEnvironment(): boolean {\n const ciIndicators = [\n 'CI',\n 'CONTINUOUS_INTEGRATION',\n 'GITHUB_ACTIONS',\n 'GITLAB_CI',\n 'JENKINS_URL',\n 'TRAVIS',\n 'CIRCLECI',\n 'BUILDKITE',\n 'AZURE_PIPELINES',\n 'TEAMCITY_VERSION',\n ];\n\n return ciIndicators.some((indicator) => Boolean(process.env[indicator]));\n}\n\n/**\n * Check if terminal supports interactive input/output.\n *\n * @returns True if terminal supports interaction\n *\n * @example\n * ```typescript\n * if (isInteractiveTerminal()) {\n * // Show interactive prompts\n * }\n * ```\n */\nexport function isInteractiveTerminal(): boolean {\n return Boolean(process.stdin.isTTY && process.stdout.isTTY && !isHeadlessEnvironment());\n}\n\n/**\n * Detect if running in development mode.\n *\n * @returns True if in development mode\n *\n * @example\n * ```typescript\n * if (isDevelopmentMode()) {\n * console.log('Debug logging enabled');\n * }\n * ```\n */\nexport function isDevelopmentMode(): boolean {\n const nodeEnv = getNodeEnvironment();\n return nodeEnv === 'development' || Boolean(process.env.DEBUG);\n}\n\n/**\n * Get Node.js environment type.\n *\n * @returns The Node.js environment type\n *\n * @example\n * ```typescript\n * const env = getNodeEnvironment();\n * console.log(`Running in ${env} mode`);\n * ```\n */\nexport function getNodeEnvironment(): NodeEnvironment {\n const env = process.env.NODE_ENV?.toLowerCase();\n\n if (env === 'production') return 'production';\n if (env === 'test') return 'test';\n return 'development';\n}\n\n// ============================================================================\n// Environment Variable Utilities\n// ============================================================================\n\n/**\n * Get environment variable with optional type conversion.\n *\n * @param key - Environment variable name\n * @param defaultValue - Default value if variable is not set\n * @returns Environment variable value or default\n *\n * @example\n * ```typescript\n * const port = getEnvVar('PORT', '3000');\n * const timeout = getEnvVar('TIMEOUT', '30');\n * ```\n */\nexport function getEnvVar(key: string, defaultValue?: string): string | undefined {\n return process.env[key] ?? defaultValue;\n}\n\n/**\n * Get environment variable with fallback value.\n *\n * @param key - Environment variable name\n * @param defaultValue - Default value if variable is not set\n * @returns Environment variable value or default\n *\n * @example\n * ```typescript\n * const logLevel = getEnvVarWithDefault('LOG_LEVEL', 'info');\n * ```\n */\nexport function getEnvVarWithDefault(key: string, defaultValue: string): string {\n return process.env[key] ?? defaultValue;\n}\n\n/**\n * Set environment variable safely.\n *\n * @param key - Environment variable name\n * @param value - Value to set\n *\n * @example\n * ```typescript\n * setEnvVar('DEBUG', 'true');\n * ```\n */\nexport function setEnvVar(key: string, value: string): void {\n process.env[key] = value;\n}\n\n/**\n * Parse boolean value from environment variable string.\n *\n * @param value - Environment variable value\n * @param defaultValue - Default boolean value\n * @returns Parsed boolean value\n *\n * @example\n * ```typescript\n * const isVerbose = parseEnvBoolean(process.env.VERBOSE, false);\n * const isEnabled = parseEnvBoolean('true'); // returns true\n * ```\n */\nexport function parseEnvBoolean(value: string | undefined, defaultValue: boolean = false): boolean {\n if (!value) return defaultValue;\n\n const normalized = value.toLowerCase().trim();\n return ['true', '1', 'yes', 'on', 'enabled'].includes(normalized);\n}\n\n/**\n * Parse number value from environment variable string.\n *\n * @param value - Environment variable value\n * @param defaultValue - Default number value\n * @returns Parsed number value\n *\n * @example\n * ```typescript\n * const port = parseEnvNumber(process.env.PORT, 3000);\n * const timeout = parseEnvNumber('30'); // returns 30\n * ```\n */\nexport function parseEnvNumber(value: string | undefined, defaultValue: number = 0): number {\n if (!value) return defaultValue;\n\n const parsed = Number(value);\n return isNaN(parsed) ? defaultValue : parsed;\n}\n\n/**\n * Parse array from delimited environment variable string.\n *\n * @param value - Environment variable value\n * @param delimiter - Delimiter to split on\n * @param defaultValue - Default array value\n * @returns Parsed array\n *\n * @example\n * ```typescript\n * const paths = parseEnvArray(process.env.SEARCH_PATHS, ':', []);\n * const hosts = parseEnvArray('host1,host2,host3', ','); // returns ['host1', 'host2', 'host3']\n * ```\n */\nexport function parseEnvArray(\n value: string | undefined,\n delimiter: string = ',',\n defaultValue: string[] = [],\n): string[] {\n if (!value) return defaultValue;\n\n return value\n .split(delimiter)\n .map((item) => item.trim())\n .filter(Boolean);\n}\n\n// ============================================================================\n// Terminal Detection\n// ============================================================================\n\n/**\n * Get terminal width for formatting output.\n *\n * @returns Terminal width in columns\n *\n * @example\n * ```typescript\n * const width = getTerminalWidth();\n * console.log(`Terminal width: ${width} columns`);\n * ```\n */\nexport function getTerminalWidth(): number {\n return process.stdout.columns || 80;\n}\n\n/**\n * Get terminal height for formatting output.\n *\n * @returns Terminal height in rows\n *\n * @example\n * ```typescript\n * const height = getTerminalHeight();\n * console.log(`Terminal height: ${height} rows`);\n * ```\n */\nexport function getTerminalHeight(): number {\n return process.stdout.rows || 24;\n}\n\n/**\n * Check if terminal supports color output.\n *\n * @returns True if terminal supports colors\n *\n * @example\n * ```typescript\n * if (supportsColor()) {\n * console.log('\\x1b[32mGreen text\\x1b[0m');\n * }\n * ```\n */\nexport function supportsColor(): boolean {\n // Check for explicit color support flags\n if (process.env.FORCE_COLOR) {\n return true;\n }\n\n if (process.env.NO_COLOR || process.env.NODE_DISABLE_COLORS) {\n return false;\n }\n\n // Check if we're in a TTY\n if (!process.stdout.isTTY) {\n return false;\n }\n\n // Check TERM environment variable\n const term = process.env.TERM;\n if (!term || term === 'dumb') {\n return false;\n }\n\n // Check for common color-supporting terminals\n const colorTerms = ['color', 'ansi', 'truecolor', '256color', 'xterm'];\n return colorTerms.some((colorTerm) => term.includes(colorTerm));\n}\n\n/**\n * Get color capability level of the terminal.\n *\n * @returns Color support level\n *\n * @example\n * ```typescript\n * const colorSupport = getColorSupport();\n * if (colorSupport === 'truecolor') {\n * // Use RGB colors\n * }\n * ```\n */\nexport function getColorSupport(): ColorSupport {\n if (!supportsColor()) {\n return 'none';\n }\n\n const term = process.env.TERM || '';\n const colorTerm = process.env.COLORTERM || '';\n\n // Check for truecolor support\n if (colorTerm === 'truecolor' || term.includes('truecolor')) {\n return 'truecolor';\n }\n\n // Check for 256 color support\n if (term.includes('256') || term.includes('256color')) {\n return '256';\n }\n\n // Default to basic color support\n return 'basic';\n}\n\n/**\n * Detect if running inside a Docker container.\n *\n * @returns True if running in Docker\n *\n * @example\n * ```typescript\n * if (isInDocker()) {\n * console.log('Running in Docker container');\n * }\n * ```\n */\nexport function isInDocker(): boolean {\n try {\n // Check for .dockerenv file\n require('node:fs').accessSync('/.dockerenv');\n return true;\n } catch {\n // Check cgroup for docker\n try {\n const cgroup = require('node:fs').readFileSync('/proc/1/cgroup', 'utf8');\n return cgroup.includes('docker') || cgroup.includes('containerd');\n } catch {\n return false;\n }\n }\n}\n\n// ============================================================================\n// Platform Detection\n// ============================================================================\n\n/**\n * Get operating system platform information.\n *\n * @returns Platform information\n *\n * @example\n * ```typescript\n * const platform = getPlatform();\n * console.log(`Running on ${platform}`);\n * ```\n */\nexport function getPlatform(): Platform {\n return os.platform() as Platform;\n}\n\n/**\n * Get system architecture information.\n *\n * @returns System architecture\n *\n * @example\n * ```typescript\n * const arch = getArchitecture();\n * console.log(`System architecture: ${arch}`);\n * ```\n */\nexport function getArchitecture(): Architecture {\n return os.arch() as Architecture;\n}\n\n/**\n * Detect user's shell (bash, zsh, fish, etc.).\n *\n * @returns Detected shell type\n *\n * @example\n * ```typescript\n * const shell = getShell();\n * console.log(`User shell: ${shell}`);\n * ```\n */\nexport function getShell(): ShellType {\n const shell = process.env.SHELL || process.env.ComSpec || '';\n const shellName = path.basename(shell).toLowerCase();\n\n if (shellName.includes('bash')) return 'bash';\n if (shellName.includes('zsh')) return 'zsh';\n if (shellName.includes('fish')) return 'fish';\n if (shellName.includes('cmd')) return 'cmd';\n if (shellName.includes('powershell') || shellName.includes('pwsh')) return 'powershell';\n\n return 'unknown';\n}\n\n/**\n * Get user home directory path.\n *\n * @returns User home directory path\n *\n * @example\n * ```typescript\n * const home = getHomeDirectory();\n * console.log(`Home directory: ${home}`);\n * ```\n */\nexport function getHomeDirectory(): string {\n return os.homedir();\n}\n\n/**\n * Get system temporary directory path.\n *\n * @returns System temp directory path\n *\n * @example\n * ```typescript\n * const temp = getTempDirectory();\n * console.log(`Temp directory: ${temp}`);\n * ```\n */\nexport function getTempDirectory(): string {\n return os.tmpdir();\n}\n\n// ============================================================================\n// Configuration Directories\n// ============================================================================\n\n/**\n * Get user configuration directory path.\n * Follows XDG Base Directory specification on Unix systems.\n *\n * @param appName - Application name for subdirectory\n * @returns Configuration directory path\n *\n * @example\n * ```typescript\n * const configDir = getConfigDirectory('juno-task');\n * // Returns: ~/.config/juno-task (Linux), ~/Library/Application Support/juno-task (macOS), etc.\n * ```\n */\nexport function getConfigDirectory(appName: string = 'juno-task'): string {\n const platform = getPlatform();\n const home = getHomeDirectory();\n\n switch (platform) {\n case 'win32':\n return path.join(process.env.APPDATA || path.join(home, 'AppData', 'Roaming'), appName);\n case 'darwin':\n return path.join(home, 'Library', 'Application Support', appName);\n default:\n return path.join(process.env.XDG_CONFIG_HOME || path.join(home, '.config'), appName);\n }\n}\n\n/**\n * Get user data directory path.\n *\n * @param appName - Application name for subdirectory\n * @returns Data directory path\n *\n * @example\n * ```typescript\n * const dataDir = getDataDirectory('juno-task');\n * ```\n */\nexport function getDataDirectory(appName: string = 'juno-task'): string {\n const platform = getPlatform();\n const home = getHomeDirectory();\n\n switch (platform) {\n case 'win32':\n return path.join(process.env.LOCALAPPDATA || path.join(home, 'AppData', 'Local'), appName);\n case 'darwin':\n return path.join(home, 'Library', 'Application Support', appName);\n default:\n return path.join(process.env.XDG_DATA_HOME || path.join(home, '.local', 'share'), appName);\n }\n}\n\n/**\n * Get user cache directory path.\n *\n * @param appName - Application name for subdirectory\n * @returns Cache directory path\n *\n * @example\n * ```typescript\n * const cacheDir = getCacheDirectory('juno-task');\n * ```\n */\nexport function getCacheDirectory(appName: string = 'juno-task'): string {\n const platform = getPlatform();\n const home = getHomeDirectory();\n\n switch (platform) {\n case 'win32':\n return path.join(process.env.TEMP || path.join(home, 'AppData', 'Local', 'Temp'), appName);\n case 'darwin':\n return path.join(home, 'Library', 'Caches', appName);\n default:\n return path.join(process.env.XDG_CACHE_HOME || path.join(home, '.cache'), appName);\n }\n}\n\n/**\n * Create directory if it doesn't exist.\n *\n * @param dirPath - Directory path to create\n * @returns Promise that resolves when directory is created\n *\n * @example\n * ```typescript\n * await createDirectoryIfNotExists('/path/to/config');\n * ```\n */\nexport async function createDirectoryIfNotExists(dirPath: string): Promise<void> {\n try {\n await fs.mkdir(dirPath, { recursive: true });\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') {\n throw error;\n }\n }\n}\n\n// ============================================================================\n// Process Information\n// ============================================================================\n\n/**\n * Get current process information.\n *\n * @returns Process information object\n *\n * @example\n * ```typescript\n * const info = getProcessInfo();\n * console.log(`Process ID: ${info.pid}`);\n * ```\n */\nexport function getProcessInfo(): ProcessInfo {\n return {\n pid: process.pid,\n ppid: process.ppid || 0,\n platform: getPlatform(),\n arch: getArchitecture(),\n nodeVersion: process.version,\n uptime: process.uptime(),\n cwd: process.cwd(),\n execPath: process.execPath,\n argv: process.argv,\n env: process.env as Record<string, string | undefined>,\n };\n}\n\n/**\n * Check if running with root/administrator privileges.\n *\n * @returns True if running as root\n *\n * @example\n * ```typescript\n * if (isRunningAsRoot()) {\n * console.warn('Running with elevated privileges');\n * }\n * ```\n */\nexport function isRunningAsRoot(): boolean {\n const platform = getPlatform();\n\n if (platform === 'win32') {\n // On Windows, check if user is in Administrators group\n try {\n // Dynamic import to improve tree shaking\n const { execSync } = require('node:child_process');\n execSync('net session', { stdio: 'ignore' });\n return true;\n } catch {\n return false;\n }\n } else {\n // On Unix-like systems, check UID\n return process.getuid?.() === 0;\n }\n}\n\n/**\n * Get process memory usage information.\n *\n * @returns Memory usage information\n *\n * @example\n * ```typescript\n * const memory = getMemoryUsage();\n * console.log(`Heap used: ${(memory.heapUsed / 1024 / 1024).toFixed(2)} MB`);\n * ```\n */\nexport function getMemoryUsage(): MemoryUsage {\n return process.memoryUsage();\n}\n\n/**\n * Get CPU usage information.\n *\n * @returns CPU usage information\n *\n * @example\n * ```typescript\n * const cpu = getCpuUsage();\n * console.log(`User CPU time: ${cpu.user}μs`);\n * ```\n */\nexport function getCpuUsage(): CpuUsage {\n return process.cpuUsage();\n}\n\n// ============================================================================\n// MCP Server Path Detection\n// ============================================================================\n\n/**\n * Auto-discover MCP server location.\n * Searches common installation paths and PATH environment variable.\n *\n * @param serverName - MCP server executable name\n * @returns Promise that resolves to server path or null if not found\n *\n * @example\n * ```typescript\n * const serverPath = await findMCPServerPath('mcp-server');\n * if (serverPath) {\n * console.log(`Found MCP server at: ${serverPath}`);\n * }\n * ```\n */\nexport async function findMCPServerPath(serverName: string = 'mcp-server'): Promise<string | null> {\n const platform = getPlatform();\n const searchPaths: string[] = [];\n\n // Add PATH directories\n const pathEnv = process.env.PATH || '';\n searchPaths.push(...pathEnv.split(path.delimiter));\n\n // Add platform-specific common paths\n if (platform === 'win32') {\n searchPaths.push(\n 'C:\\\\Program Files\\\\MCP\\\\bin',\n 'C:\\\\Program Files (x86)\\\\MCP\\\\bin',\n path.join(process.env.LOCALAPPDATA || '', 'Programs', 'MCP', 'bin'),\n );\n } else {\n searchPaths.push(\n '/usr/local/bin',\n '/usr/bin',\n '/opt/mcp/bin',\n path.join(getHomeDirectory(), '.local', 'bin'),\n path.join(getHomeDirectory(), 'bin'),\n );\n }\n\n // Add executable extension on Windows\n const executable = platform === 'win32' ? `${serverName}.exe` : serverName;\n\n // Search for the executable\n for (const searchPath of searchPaths) {\n if (!searchPath) continue;\n\n const fullPath = path.join(searchPath, executable);\n try {\n await fs.access(fullPath, fs.constants.F_OK | fs.constants.X_OK);\n return fullPath;\n } catch {\n // Continue searching\n }\n }\n\n return null;\n}\n\n/**\n * Verify MCP server path is executable.\n *\n * @param serverPath - Path to MCP server executable\n * @returns Promise that resolves to true if valid and executable\n *\n * @example\n * ```typescript\n * const isValid = await validateMCPServerPath('/usr/local/bin/mcp-server');\n * if (isValid) {\n * console.log('MCP server is valid and executable');\n * }\n * ```\n */\nexport async function validateMCPServerPath(serverPath: string): Promise<boolean> {\n try {\n const stats = await fs.stat(serverPath);\n if (!stats.isFile()) {\n return false;\n }\n\n // Check if file is executable\n await fs.access(serverPath, fs.constants.X_OK);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Get environment configuration for MCP server.\n *\n * @param additionalEnv - Additional environment variables\n * @returns MCP server environment configuration\n *\n * @example\n * ```typescript\n * const env = getMCPServerEnvironment({ DEBUG: 'true' });\n * console.log('MCP server environment:', env);\n * ```\n */\nexport function getMCPServerEnvironment(\n additionalEnv: Record<string, string> = {},\n): MCPServerEnvironment {\n const baseEnv = {\n PATH: process.env.PATH || '',\n NODE_ENV: getNodeEnvironment(),\n HOME: getHomeDirectory(),\n TMPDIR: getTempDirectory(),\n };\n\n return {\n ...baseEnv,\n ...additionalEnv,\n };\n}\n","/**\n * Validation Utilities Module for juno-code\n *\n * Provides Zod-based validation for configuration values.\n *\n * @module utils/validation\n */\n\nimport { z } from 'zod';\nimport type { SubagentType, LogLevel, JunoTaskConfig } from '../types/index';\nimport { JunoTaskConfigSchema, validateConfig as coreValidateConfig } from '../core/config';\nimport { SUBAGENT_ALIASES } from '../cli/types';\n\n// ============================================================================\n// Zod Schemas\n// ============================================================================\n\n/**\n * Schema for validating subagent types with alias support\n */\nexport const SubagentSchema = z\n .string()\n .transform((value) => {\n if (['claude', 'cursor', 'codex', 'gemini', 'pi'].includes(value)) {\n return value as SubagentType;\n }\n\n const normalized = SUBAGENT_ALIASES[value];\n if (normalized) {\n return normalized;\n }\n\n throw new z.ZodError([\n {\n code: z.ZodIssueCode.invalid_enum_value,\n options: ['claude', 'cursor', 'codex', 'gemini', 'pi'],\n received: value,\n path: [],\n message: `Invalid subagent: ${value}. Valid options: claude, cursor, codex, gemini, pi`,\n },\n ]);\n })\n .refine(\n (value): value is SubagentType => ['claude', 'cursor', 'codex', 'gemini', 'pi'].includes(value),\n {\n message: 'Invalid subagent type',\n },\n );\n\n/**\n * Schema for validating log levels\n */\nexport const LogLevelSchema = z.enum(['error', 'warn', 'info', 'debug', 'trace'], {\n errorMap: (_issue, ctx) => ({\n message: `Invalid log level: ${ctx.data}. Valid options: error, warn, info, debug, trace`,\n }),\n});\n\n/**\n * Schema for validating session status\n */\nexport const SessionStatusSchema = z.enum(['running', 'completed', 'failed', 'cancelled'], {\n errorMap: (_issue, ctx) => ({\n message: `Invalid session status: ${ctx.data}. Valid options: running, completed, failed, cancelled`,\n }),\n});\n\n/**\n * Schema for validating iteration counts\n */\nexport const IterationsSchema = z\n .number()\n .int('Iterations must be an integer')\n .refine(\n (value) => value === -1 || value > 0,\n 'Iterations must be a positive integer or -1 for infinite',\n )\n .transform((value) => (value === -1 ? Infinity : value));\n\n/**\n * Schema for validating model names (subagent-specific)\n */\nexport const ModelSchema = z\n .string()\n .min(1, 'Model name cannot be empty')\n .refine((model) => {\n return /^[a-zA-Z0-9._-]+$/.test(model);\n }, 'Model name contains invalid characters');\n\n/**\n * Schema for runtime configuration validation\n */\nexport const ConfigValidationSchema = JunoTaskConfigSchema;\n\n// ============================================================================\n// Core Validation Functions\n// ============================================================================\n\n/**\n * Validate and normalize subagent names including aliases\n */\nexport function validateSubagent(subagent: string): SubagentType {\n return SubagentSchema.parse(subagent);\n}\n\n/**\n * Validate model names for specific subagents\n */\nexport function validateModel(model: string, _subagent?: SubagentType): string {\n return ModelSchema.parse(model);\n}\n\n/**\n * Validate iteration counts (positive integers or -1 for infinite)\n */\nexport function validateIterations(iterations: number): number {\n return IterationsSchema.parse(iterations);\n}\n\n/**\n * Validate log level strings\n */\nexport function validateLogLevel(logLevel: string): LogLevel {\n return LogLevelSchema.parse(logLevel);\n}\n\n// ============================================================================\n// Configuration Validation\n// ============================================================================\n\n/**\n * Complete configuration validation\n * Delegates to the core config validation.\n */\nexport function validateConfig(config: unknown): JunoTaskConfig {\n return coreValidateConfig(config);\n}\n\n/**\n * Environment variable validation\n */\nexport function validateEnvironmentVars(\n envVars: Record<string, string | undefined>,\n): Partial<JunoTaskConfig> {\n const config: Partial<JunoTaskConfig> = {};\n const errors: string[] = [];\n\n Object.entries(envVars).forEach(([key, value]) => {\n if (!key.startsWith('JUNO_TASK_') || value === undefined) {\n return;\n }\n\n try {\n switch (key) {\n case 'JUNO_TASK_DEFAULT_SUBAGENT':\n config.defaultSubagent = validateSubagent(value);\n break;\n case 'JUNO_TASK_LOG_LEVEL':\n config.logLevel = validateLogLevel(value);\n break;\n case 'JUNO_TASK_DEFAULT_MAX_ITERATIONS':\n config.defaultMaxIterations = validateIterations(parseInt(value, 10));\n break;\n case 'JUNO_TASK_VERBOSE': {\n const lower = value.toLowerCase();\n if (lower === 'true' || lower === 'yes') config.verbose = 1;\n else if (lower === 'false' || lower === 'no') config.verbose = 0;\n else { const n = Number(value); config.verbose = !isNaN(n) && n >= 0 && n <= 2 ? Math.floor(n) : 1; }\n break;\n }\n case 'JUNO_TASK_QUIET':\n config.quiet = value.toLowerCase() === 'true';\n break;\n case 'JUNO_TASK_INTERACTIVE':\n config.interactive = value.toLowerCase() === 'true';\n break;\n case 'JUNO_TASK_HEADLESS_MODE':\n config.headlessMode = value.toLowerCase() === 'true';\n break;\n }\n } catch (error) {\n if (error instanceof Error) {\n errors.push(`${key}: ${error.message}`);\n }\n }\n });\n\n if (errors.length > 0) {\n throw new Error(`Environment variable validation failed:\\n${errors.join('\\n')}`);\n }\n\n return config;\n}\n\n// ============================================================================\n// Type Re-exports\n// ============================================================================\n\nexport type { SubagentType, SessionStatus, LogLevel, JunoTaskConfig } from '../types/index';\n","/**\n * CLI Types Module for juno-code\n *\n * TypeScript interfaces and types for the CLI framework,\n * supporting commands, options, error handling, and constants.\n */\n\nimport type { SubagentType, SessionStatus, LogLevel, BackendType } from '../types/index';\n\n// ============================================================================\n// Command Structure Types\n// ============================================================================\n\n/**\n * Interface for usage examples\n */\nexport interface CommandExample {\n /** Full command example */\n command: string;\n /** Description of what the example does */\n description: string;\n}\n\n// ============================================================================\n// CLI Options Types\n// ============================================================================\n\n/**\n * Global CLI options available to all commands\n */\nexport interface GlobalCLIOptions {\n /** Verbosity level: 0=quiet, 1=normal+helping texts (default), 2=debug+hooks. Accepts number, boolean, or string */\n verbose?: number;\n /** Quiet mode: suppress agent messages and hook output (alias: --silent) */\n quiet?: boolean;\n /** Alias for --quiet */\n silent?: boolean;\n /** Configuration file path (.json, .toml, pyproject.toml) */\n config?: string;\n /** Log file path (auto-generated if not specified) */\n logFile?: string;\n /** Disable colored output */\n noColor?: boolean;\n /** Log level for output */\n logLevel?: LogLevel;\n /** Enable concurrent feedback collection during execution */\n enableFeedback?: boolean;\n /** Behavior when Claude hourly quota limit is reached: \"wait\" to sleep until reset, \"raise\" to exit immediately */\n onHourlyLimit?: 'wait' | 'raise';\n /** Skip execution of all lifecycle hooks */\n hooks?: boolean;\n}\n\n/**\n * Main execution command options\n */\nexport interface MainCommandOptions extends GlobalCLIOptions {\n /** Subagent to use (optional; falls back to config/defaults) */\n subagent?: SubagentType;\n /** Prompt input (file path or inline text). Commander sets to `true` when -p flag used without argument (e.g. heredoc) */\n prompt?: string | true;\n /** Prompt file path (alternative to -p \"$(cat file)\") */\n promptFile?: string;\n /** Working directory */\n cwd?: string;\n /** Maximum iterations (-1 for unlimited) */\n maxIterations?: number;\n /** Model to use (subagent-specific) */\n model?: string;\n /** Agents configuration (forwarded to shell backend --agents flag) */\n agents?: string;\n /** Available tools from built-in set (only works with --print mode, forwarded to shell backend --tools flag) */\n tools?: string[];\n /** Permission-based filtering of specific tool instances (forwarded to shell backend --allowedTools flag) */\n allowedTools?: string[];\n /** Disallowed tools for Claude (forwarded to shell backend --disallowed-tool flag) */\n disallowedTools?: string[];\n /** Append tools to default allowed-tools list (mutually exclusive with --allowed-tools, forwarded to shell backend --appendAllowedTools flag) */\n appendAllowedTools?: string[];\n /** Backend type (shell) */\n backend?: 'shell';\n /** Interactive mode for typing prompts */\n interactive?: boolean;\n /** Run Pi subagent in interactive live TUI mode (pi-only) */\n live?: boolean;\n /** Launch interactive prompt editor */\n interactivePrompt?: boolean;\n /** Resume a conversation by session ID (shell backend only) */\n resume?: string;\n /** Continue the most recent conversation (shell backend only) */\n continue?: boolean;\n /** Load last persisted session+settings snapshot and auto-populate resume/options */\n continueFromLatest?: boolean;\n /** Extended thinking level (forwarded to shell backend --thinking flag, pi subagent) */\n thinking?: string;\n}\n\n/**\n * Init command options\n */\nexport interface InitCommandOptions extends GlobalCLIOptions {\n /** Target directory */\n directory?: string;\n /** Force overwrite existing files */\n force?: boolean;\n /** Main task description */\n task?: string;\n /** Preferred subagent */\n subagent?: SubagentType;\n /** Repository URL */\n gitUrl?: string;\n /** Force interactive mode for guided setup */\n interactive?: boolean;\n /** Template variant to use */\n template?: string;\n /** Custom template variables */\n variables?: Record<string, string>;\n}\n\n/**\n * Start command options\n */\nexport interface StartCommandOptions extends GlobalCLIOptions {\n /** Subagent to use (optional override of config default) */\n subagent?: SubagentType;\n /** Backend type (shell) */\n backend?: BackendType;\n /** Maximum iterations */\n maxIterations?: number;\n /** Model to use */\n model?: string;\n /** Agents configuration (forwarded to shell backend --agents flag) */\n agents?: string;\n /** Available tools from built-in set (only works with --print mode, forwarded to shell backend --tools flag) */\n tools?: string[];\n /** Permission-based filtering of specific tool instances (forwarded to shell backend --allowedTools flag) */\n allowedTools?: string[];\n /** Disallowed tools for Claude (forwarded to shell backend --disallowed-tool flag) */\n disallowedTools?: string[];\n /** Append tools to default allowed-tools list (mutually exclusive with --allowed-tools, forwarded to shell backend --appendAllowedTools flag) */\n appendAllowedTools?: string[];\n /** Resume a conversation by session ID (shell backend only) */\n resume?: string;\n /** Continue the most recent conversation (shell backend only) */\n continue?: boolean;\n /** Project directory */\n directory?: string;\n /** Display performance metrics summary after execution */\n showMetrics?: boolean;\n /** Show interactive performance dashboard after execution */\n showDashboard?: boolean;\n /** Display performance trends from historical data */\n showTrends?: boolean;\n /** Save performance metrics to file */\n saveMetrics?: boolean | string;\n /** Custom path for metrics file */\n metricsFile?: string;\n /** Enable concurrent feedback collection during execution */\n enableFeedback?: boolean;\n /** Validate configuration and exit without executing */\n dryRun?: boolean;\n}\n\n/**\n * Feedback command options\n */\nexport interface FeedbackCommandOptions extends GlobalCLIOptions {\n /** Custom USER_FEEDBACK.md file path */\n file?: string;\n /** Interactive multiline input */\n interactive?: boolean;\n /** Issue description */\n issue?: string;\n /** Test criteria or success factors */\n test?: string;\n /** Test criteria alias */\n testCriteria?: string;\n}\n\n/**\n * Session list command options\n */\nexport interface SessionListOptions extends GlobalCLIOptions {\n /** Maximum sessions to show */\n limit?: number;\n /** Filter by subagent */\n subagent?: SubagentType;\n /** Filter by status */\n status?: SessionStatus[];\n}\n\n/**\n * Session info command options\n */\nexport interface SessionInfoOptions extends GlobalCLIOptions {\n /** Show detailed information (inherits verbosity level from GlobalCLIOptions) */\n}\n\n/**\n * Session remove command options\n */\nexport interface SessionRemoveOptions extends GlobalCLIOptions {\n /** Skip confirmation prompt */\n force?: boolean;\n}\n\n/**\n * Session clean command options\n */\nexport interface SessionCleanOptions extends GlobalCLIOptions {\n /** Remove sessions older than N days */\n days?: number;\n /** Remove only empty log files */\n empty?: boolean;\n /** Skip confirmation prompt */\n force?: boolean;\n}\n\n/**\n * Setup-git command options\n */\nexport interface SetupGitOptions extends GlobalCLIOptions {\n /** Show current upstream URL configuration */\n show?: boolean;\n /** Remove upstream URL configuration */\n remove?: boolean;\n}\n\n/**\n * Test command options\n */\nexport interface TestCommandOptions extends GlobalCLIOptions {\n /** Test type to generate/run */\n type?: 'unit' | 'integration' | 'e2e' | 'performance' | 'all';\n /** AI subagent for test generation */\n subagent?: SubagentType;\n /** AI intelligence level */\n intelligence?: 'basic' | 'smart' | 'comprehensive';\n /** Generate tests using AI */\n generate?: boolean;\n /** Execute tests */\n run?: boolean;\n /** Generate coverage report */\n coverage?: boolean | string;\n /** Analyze test quality and coverage */\n analyze?: boolean;\n /** Analysis quality level */\n quality?: 'basic' | 'thorough' | 'exhaustive';\n /** Generate improvement suggestions */\n suggestions?: boolean;\n /** Generate test report */\n report?: boolean | string;\n /** Report format */\n format?: 'json' | 'html' | 'markdown' | 'console';\n /** Test template to use */\n template?: string;\n /** Testing framework */\n framework?: 'vitest' | 'jest' | 'mocha' | 'custom';\n /** Watch mode for continuous testing */\n watch?: boolean;\n /** Test reporters (comma-separated) */\n reporters?: string[];\n}\n\n// ============================================================================\n// Parsed Arguments Types\n// ============================================================================\n\n/**\n * Parsed command line arguments\n */\nexport interface ParsedArgs {\n /** Command name */\n command: string;\n /** Subcommand name (if applicable) */\n subcommand?: string;\n /** Positional arguments */\n args: string[];\n /** Parsed options */\n options: Record<string, any>;\n /** Unknown options (for validation) */\n unknown: string[];\n}\n\n/**\n * Option validation result\n */\nexport interface OptionValidationResult {\n /** Whether validation passed */\n valid: boolean;\n /** Validation error messages */\n errors: string[];\n /** Validation warnings */\n warnings: string[];\n /** Normalized/coerced option values */\n normalizedOptions: Record<string, any>;\n}\n\n// ============================================================================\n// Error Types\n// ============================================================================\n\n/**\n * Base CLI error class\n */\nexport abstract class CLIError extends Error {\n /** Error code for programmatic handling */\n abstract code: string;\n /** Whether error should show help */\n showHelp: boolean = false;\n /** Suggested solutions */\n suggestions: string[] = [];\n\n constructor(message: string, showHelp: boolean = false) {\n super(message);\n this.name = this.constructor.name;\n this.showHelp = showHelp;\n }\n}\n\n/**\n * Validation error (user input issues)\n */\nexport class ValidationError extends CLIError {\n code = 'VALIDATION_ERROR';\n\n constructor(message: string, suggestions: string[] = []) {\n super(message, true);\n this.suggestions = suggestions;\n }\n}\n\n/**\n * Configuration error (config file/setup issues)\n */\nexport class ConfigurationError extends CLIError {\n code = 'CONFIGURATION_ERROR';\n\n constructor(message: string, suggestions: string[] = []) {\n super(message, false);\n this.suggestions = suggestions;\n }\n}\n\n/**\n * Runtime error (file system operations, process failures, etc.)\n */\nexport class RuntimeError extends CLIError {\n code = 'RUNTIME_ERROR';\n\n constructor(message: string, path?: string) {\n super(path ? `${message}: ${path}` : message);\n this.suggestions = [\n 'Check file/directory permissions',\n 'Verify path exists and is accessible',\n 'Use absolute paths to avoid ambiguity',\n ];\n }\n}\n\n// ============================================================================\n// Environment Variables\n// ============================================================================\n\n/**\n * Environment variable mappings for CLI options\n * Uses JUNO_CODE_* prefix exclusively (legacy JUNO_TASK_* removed)\n */\nexport const ENVIRONMENT_MAPPINGS = {\n // Core options\n JUNO_CODE_SUBAGENT: 'subagent',\n JUNO_CODE_AGENT: 'backend',\n JUNO_CODE_BACKEND: 'backend',\n JUNO_CODE_PROMPT: 'prompt',\n JUNO_CODE_CWD: 'cwd',\n JUNO_CODE_MAX_ITERATIONS: 'maxIterations',\n JUNO_CODE_MODEL: 'model',\n JUNO_CODE_LOG_FILE: 'logFile',\n JUNO_CODE_VERBOSE: 'verbose',\n JUNO_CODE_QUIET: 'quiet',\n JUNO_CODE_INTERACTIVE: 'interactive',\n JUNO_CODE_CONFIG: 'config',\n\n // MCP options\n JUNO_CODE_MCP_SERVER_PATH: 'mcpServerPath',\n JUNO_CODE_MCP_TIMEOUT: 'mcpTimeout',\n JUNO_CODE_MCP_RETRIES: 'mcpRetries',\n\n // Session options\n JUNO_CODE_SESSION_DIR: 'sessionDir',\n JUNO_CODE_LOG_LEVEL: 'logLevel',\n\n // Template options\n JUNO_CODE_TEMPLATE: 'template',\n JUNO_CODE_FORCE: 'force',\n\n // Git options\n JUNO_CODE_GIT_URL: 'gitUrl',\n\n // UI options\n JUNO_CODE_NO_COLOR: 'noColor',\n JUNO_CODE_HEADLESS: 'headless',\n\n // Feedback options\n JUNO_CODE_ENABLE_FEEDBACK: 'enableFeedback',\n\n // Special aliases\n JUNO_INTERACTIVE_FEEDBACK_MODE: 'enableFeedback', // Alias for enableFeedback\n} as const;\n\n/**\n * Type for environment variable keys\n */\nexport type EnvironmentVariable = keyof typeof ENVIRONMENT_MAPPINGS;\n\n/**\n * Type for CLI option keys\n */\nexport type CLIOptionKey = (typeof ENVIRONMENT_MAPPINGS)[EnvironmentVariable];\n\n// ============================================================================\n// Configuration Types\n// ============================================================================\n\n/**\n * Initialization data for project setup\n */\nexport interface InitializationData {\n /** Main task description */\n task: string;\n /** Preferred subagent */\n subagent: SubagentType;\n /** Repository URL (optional) */\n gitUrl?: string;\n /** Template variables */\n variables: Record<string, string>;\n /** Template variant */\n template: string;\n /** Additional metadata */\n metadata?: {\n author?: string;\n description?: string;\n tags?: string[];\n };\n}\n\n/**\n * Command execution result\n */\nexport interface CommandExecutionResult {\n /** Whether command succeeded */\n success: boolean;\n /** Exit code */\n exitCode: number;\n /** Execution time in milliseconds */\n duration: number;\n /** Output messages */\n output: string[];\n /** Error messages */\n errors: string[];\n}\n\n// ============================================================================\n// Type Guards\n// ============================================================================\n\n/**\n * Type guard for CLI errors\n */\nexport function isCLIError(error: unknown): error is CLIError {\n return error instanceof CLIError;\n}\n\n/**\n * Type guard for validation errors\n */\nexport function isValidationError(error: unknown): error is ValidationError {\n return error instanceof ValidationError;\n}\n\n/**\n * Type guard for configuration errors\n */\nexport function isConfigurationError(error: unknown): error is ConfigurationError {\n return error instanceof ConfigurationError;\n}\n\n/**\n * Type guard for runtime errors\n */\nexport function isRuntimeError(error: unknown): error is RuntimeError {\n return error instanceof RuntimeError;\n}\n\n// ============================================================================\n// Constants\n// ============================================================================\n\n/**\n * Supported subagent aliases\n */\nexport const SUBAGENT_ALIASES: Record<string, SubagentType> = {\n 'claude-code': 'claude',\n claude_code: 'claude',\n 'gemini-cli': 'gemini',\n 'cursor-agent': 'cursor',\n 'pi-agent': 'pi',\n};\n\n/**\n * Command categories for help organization\n */\nexport const COMMAND_CATEGORIES = {\n EXECUTION: ['juno-code', 'start'],\n PROJECT: ['init', 'setup-git'],\n TESTING: ['test'],\n SESSION: ['session'],\n FEEDBACK: ['feedback'],\n} as const;\n\n/**\n * Exit codes for different error types\n */\nexport const EXIT_CODES = {\n SUCCESS: 0,\n VALIDATION_ERROR: 1,\n CONFIGURATION_ERROR: 2,\n COMMAND_NOT_FOUND: 3,\n RUNTIME_ERROR: 5,\n UNEXPECTED_ERROR: 99,\n} as const;\n\nexport type ExitCode = (typeof EXIT_CODES)[keyof typeof EXIT_CODES];\n","/**\n * Core type definitions for juno-code\n */\n\n// Subagent types\nexport type SubagentType = 'claude' | 'cursor' | 'codex' | 'gemini' | 'pi';\n\n// Backend types for execution\nexport type BackendType = 'shell';\n\n// Session status\nexport type SessionStatus = 'running' | 'completed' | 'failed' | 'cancelled';\n\n// Log levels\nexport type LogLevel = 'error' | 'warn' | 'info' | 'debug' | 'trace';\n\n// On hourly limit behavior\nexport type OnHourlyLimit = 'wait' | 'raise';\n\n// Hook types\nexport type HookType = 'START_RUN' | 'START_ITERATION' | 'END_ITERATION' | 'END_RUN' | 'ON_STALE';\n\n// Hook configuration\nexport interface Hook {\n commands: string[];\n}\n\n// Hooks configuration mapping\nexport type Hooks = Record<HookType, Hook>;\n\n// Progress event types\nexport type ProgressEventType = 'tool_start' | 'tool_result' | 'thinking' | 'error' | 'info';\n\n// Base configuration interface\nexport interface JunoTaskConfig {\n // Core settings\n defaultSubagent: SubagentType;\n defaultMaxIterations: number;\n defaultModel?: string;\n /** Optional per-subagent default model overrides */\n defaultModels?: Partial<Record<SubagentType, string>>;\n defaultBackend: BackendType;\n\n // Project metadata\n mainTask?: string;\n\n // Logging settings\n logLevel: LogLevel;\n logFile?: string;\n /** Verbosity level: 0=quiet, 1=normal+helping texts (default), 2=debug+hooks */\n verbose: number;\n quiet: boolean;\n\n // MCP settings\n mcpTimeout: number;\n mcpRetries: number;\n mcpServerPath?: string;\n mcpServerName?: string;\n\n // Hook settings\n hookCommandTimeout?: number;\n\n // Quota/hourly limit settings\n onHourlyLimit: OnHourlyLimit;\n\n // TUI settings\n interactive: boolean;\n headlessMode: boolean;\n\n // Paths\n workingDirectory: string;\n sessionDirectory: string;\n\n // Project environment bootstrap\n /** Path to project env file loaded on startup (relative to workingDirectory or absolute) */\n envFilePath?: string;\n /** Tracks whether the configured env file has been initialized from .env.juno */\n envFileCopied?: boolean;\n\n // Hooks configuration\n hooks?: Hooks;\n\n // Skip hooks execution\n skipHooks?: boolean;\n}\n\n// Global declarations for build-time constants\ndeclare global {\n const __VERSION__: string;\n const __DEV__: boolean;\n}\n"]}