nexus-agents 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +27 -0
- package/dist/chunk-3VJOPTVX.js +13142 -0
- package/dist/chunk-3VJOPTVX.js.map +1 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +86 -0
- package/dist/cli.js.map +1 -0
- package/dist/index.d.ts +8526 -0
- package/dist/index.js +551 -0
- package/dist/index.js.map +1 -0
- package/dist/workflows/templates/bug-fix.yaml +109 -0
- package/dist/workflows/templates/code-review.yaml +84 -0
- package/dist/workflows/templates/documentation-update.yaml +91 -0
- package/dist/workflows/templates/feature-implementation.yaml +124 -0
- package/package.json +71 -0
- package/src/workflows/templates/bug-fix.yaml +109 -0
- package/src/workflows/templates/code-review.yaml +84 -0
- package/src/workflows/templates/documentation-update.yaml +91 -0
- package/src/workflows/templates/feature-implementation.yaml +124 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/result.ts","../src/core/errors.ts","../src/core/logger.ts","../src/core/types/model.ts","../src/core/types/agent.ts","../src/core/types/workflow.ts","../src/config/schemas.ts","../src/adapters/factory.ts","../src/adapters/rate-limiter.ts","../src/adapters/retry.ts","../src/adapters/base-adapter.ts","../src/adapters/stream-operators.ts","../src/adapters/streaming.ts","../src/adapters/claude-adapter.ts","../src/adapters/openai-adapter.ts","../src/adapters/openai-types.ts","../src/adapters/openai-mappers.ts","../src/adapters/ollama-adapter.ts","../src/adapters/gemini-adapter.ts","../src/adapters/gemini-types.ts","../src/agents/agent-schemas.ts","../src/agents/base-agent.ts","../src/agents/simple-agent.ts","../src/agents/tech-lead-types.ts","../src/agents/tech-lead-decomposition.ts","../src/agents/tech-lead-expert-selection.ts","../src/agents/tech-lead-helpers.ts","../src/agents/tech-lead.ts","../src/agents/state-machine.ts","../src/agents/context-manager.ts","../src/agents/context-pruner.ts","../src/agents/experts/expert-types.ts","../src/agents/experts/code-expert.ts","../src/agents/experts/expert-prompts.ts","../src/agents/experts/security-expert-helpers.ts","../src/agents/experts/security-expert.ts","../src/agents/experts/architecture-expert-helpers.ts","../src/agents/experts/architecture-expert.ts","../src/agents/experts/testing-expert-helpers.ts","../src/agents/experts/testing-expert.ts","../src/agents/experts/documentation-expert-helpers.ts","../src/agents/experts/documentation-expert.ts","../src/agents/experts/expert-config.ts","../src/agents/experts/expert-factory.ts","../src/agents/experts/expert-registry.ts","../src/agents/experts/task-analyzer-types.ts","../src/agents/experts/task-analyzer-keywords.ts","../src/agents/experts/task-analyzer.ts","../src/agents/experts/expert-selector.ts","../src/agents/experts/expert-defaults.ts","../src/agents/collaboration/collaboration-schemas.ts","../src/agents/collaboration/session-helpers.ts","../src/agents/collaboration/collaboration-session.ts","../src/agents/collaboration/protocol-helpers.ts","../src/agents/collaboration/review-protocol.ts","../src/agents/collaboration/consensus-protocol.ts","../src/agents/collaboration/collaboration-protocol.ts","../src/agents/collaboration/aggregator-helpers.ts","../src/agents/collaboration/result-aggregator.ts","../src/workflows/workflow-parser.ts","../src/workflows/workflow-types.ts","../src/workflows/dependency-graph.ts","../src/workflows/task-queue.ts","../src/workflows/execution-planner.ts","../src/workflows/parallel-executor.ts","../src/workflows/template-types.ts","../src/workflows/template-loader.ts","../src/workflows/template-registry.ts","../src/workflows/execution-context.ts","../src/workflows/expression-resolver.ts","../src/workflows/step-executor.ts","../src/mcp/server.ts","../src/mcp/middleware/validation.ts","../src/mcp/middleware/rate-limiter.ts","../src/mcp/middleware/logging.ts","../src/mcp/tools/create-expert.ts","../src/mcp/tools/run-workflow.ts","../src/mcp/tools/orchestrate.ts","../src/mcp/tools/index.ts","../src/mcp/index.ts","../src/index.ts"],"sourcesContent":["/**\n * @nexus-agents/core - Result Pattern\n *\n * Type-safe Result pattern for handling fallible operations without exceptions.\n * Inspired by Rust's Result<T, E> type.\n */\n\n/**\n * A discriminated union representing either success (Ok) or failure (Err).\n * @template T - The success value type\n * @template E - The error value type\n */\nexport type Result<T, E> =\n | { readonly ok: true; readonly value: T }\n | { readonly ok: false; readonly error: E };\n\n/**\n * Creates a successful Result containing the given value.\n * @template T - The success value type\n * @param value - The success value\n * @returns A Result in the Ok state\n */\nexport function ok<T>(value: T): Result<T, never> {\n return { ok: true, value };\n}\n\n/**\n * Creates a failed Result containing the given error.\n * @template E - The error value type\n * @param error - The error value\n * @returns A Result in the Err state\n */\nexport function err<E>(error: E): Result<never, E> {\n return { ok: false, error };\n}\n\n/**\n * Type guard to check if a Result is in the Ok state.\n * @template T - The success value type\n * @template E - The error value type\n * @param result - The Result to check\n * @returns True if the Result is Ok\n */\nexport function isOk<T, E>(\n result: Result<T, E>\n): result is { readonly ok: true; readonly value: T } {\n return result.ok;\n}\n\n/**\n * Type guard to check if a Result is in the Err state.\n * @template T - The success value type\n * @template E - The error value type\n * @param result - The Result to check\n * @returns True if the Result is Err\n */\nexport function isErr<T, E>(\n result: Result<T, E>\n): result is { readonly ok: false; readonly error: E } {\n return !result.ok;\n}\n\n/**\n * Transforms the success value of a Result using the provided function.\n * @template T - The original success value type\n * @template U - The transformed success value type\n * @template E - The error value type\n * @param result - The Result to transform\n * @param fn - The transformation function\n * @returns A new Result with the transformed value\n */\nexport function map<T, U, E>(result: Result<T, E>, fn: (value: T) => U): Result<U, E> {\n if (result.ok) {\n return ok(fn(result.value));\n }\n return result;\n}\n\n/**\n * Transforms the error value of a Result using the provided function.\n * @template T - The success value type\n * @template E - The original error value type\n * @template F - The transformed error value type\n * @param result - The Result to transform\n * @param fn - The transformation function\n * @returns A new Result with the transformed error\n */\nexport function mapErr<T, E, F>(result: Result<T, E>, fn: (error: E) => F): Result<T, F> {\n if (!result.ok) {\n return err(fn(result.error));\n }\n return result;\n}\n\n/**\n * Extracts the success value from a Result.\n * @template T - The success value type\n * @template E - The error value type\n * @param result - The Result to unwrap\n * @returns The success value\n * @throws Throws an Error wrapping the error value if the Result is Err\n */\nexport function unwrap<T, E>(result: Result<T, E>): T {\n if (result.ok) {\n return result.value;\n }\n if (result.error instanceof Error) {\n throw result.error;\n }\n throw new Error(String(result.error));\n}\n\n/**\n * Extracts the success value from a Result, or returns a default value.\n * @template T - The success value type\n * @template E - The error value type\n * @param result - The Result to unwrap\n * @param defaultValue - The default value to return if Err\n * @returns The success value or the default value\n */\nexport function unwrapOr<T, E>(result: Result<T, E>, defaultValue: T): T {\n if (result.ok) {\n return result.value;\n }\n return defaultValue;\n}\n","/**\n * @nexus-agents/core - Error Hierarchy\n *\n * Structured error classes for consistent error handling across the codebase.\n */\n\n/**\n * Error codes for all Nexus Agents errors.\n */\nexport const ErrorCode = {\n // Validation errors\n VALIDATION_ERROR: 'VALIDATION_ERROR',\n INVALID_INPUT: 'INVALID_INPUT',\n MISSING_REQUIRED: 'MISSING_REQUIRED',\n SCHEMA_ERROR: 'SCHEMA_ERROR',\n\n // Configuration errors\n CONFIG_ERROR: 'CONFIG_ERROR',\n CONFIG_NOT_FOUND: 'CONFIG_NOT_FOUND',\n CONFIG_INVALID: 'CONFIG_INVALID',\n\n // Model errors\n MODEL_ERROR: 'MODEL_ERROR',\n MODEL_UNAVAILABLE: 'MODEL_UNAVAILABLE',\n MODEL_RATE_LIMITED: 'MODEL_RATE_LIMITED',\n MODEL_TIMEOUT: 'MODEL_TIMEOUT',\n\n // Agent errors\n AGENT_ERROR: 'AGENT_ERROR',\n AGENT_NOT_FOUND: 'AGENT_NOT_FOUND',\n AGENT_EXECUTION_FAILED: 'AGENT_EXECUTION_FAILED',\n\n // Workflow errors\n WORKFLOW_ERROR: 'WORKFLOW_ERROR',\n WORKFLOW_NOT_FOUND: 'WORKFLOW_NOT_FOUND',\n WORKFLOW_PARSE_ERROR: 'WORKFLOW_PARSE_ERROR',\n WORKFLOW_EXECUTION_FAILED: 'WORKFLOW_EXECUTION_FAILED',\n\n // Security errors\n SECURITY_ERROR: 'SECURITY_ERROR',\n PATH_TRAVERSAL: 'PATH_TRAVERSAL',\n UNAUTHORIZED: 'UNAUTHORIZED',\n\n // System errors\n TIMEOUT_ERROR: 'TIMEOUT_ERROR',\n RATE_LIMIT_ERROR: 'RATE_LIMIT_ERROR',\n INTERNAL_ERROR: 'INTERNAL_ERROR',\n} as const;\n\nexport type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode];\n\n/**\n * Serialized error format for JSON output.\n */\nexport interface SerializedError {\n name: string;\n code: ErrorCode;\n message: string;\n context?: Record<string, unknown>;\n cause?: SerializedError;\n stack?: string;\n}\n\n/**\n * Options for creating a NexusError.\n */\nexport interface NexusErrorOptions {\n code: ErrorCode;\n cause?: Error;\n context?: Record<string, unknown>;\n}\n\n/**\n * Base error class for all Nexus Agents errors.\n */\nexport class NexusError extends Error {\n readonly code: ErrorCode;\n readonly context: Record<string, unknown> | undefined;\n override readonly cause: Error | undefined;\n\n constructor(message: string, options: NexusErrorOptions) {\n super(message);\n this.name = 'NexusError';\n this.code = options.code;\n this.cause = options.cause;\n this.context = options.context;\n if (typeof Error.captureStackTrace === 'function') {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n\n /**\n * Serializes the error to a JSON-safe object.\n */\n toJSON(): SerializedError {\n const result: SerializedError = {\n name: this.name,\n code: this.code,\n message: this.message,\n };\n if (this.context !== undefined) {\n result.context = this.context;\n }\n if (this.cause instanceof NexusError) {\n result.cause = this.cause.toJSON();\n }\n if (this.stack !== undefined) {\n result.stack = this.stack;\n }\n return result;\n }\n}\n\n/**\n * Validation error for invalid inputs or schema violations.\n */\nexport class ValidationError extends NexusError {\n constructor(message: string, options?: Partial<Omit<NexusErrorOptions, 'code'>>) {\n super(message, { code: ErrorCode.VALIDATION_ERROR, ...options });\n this.name = 'ValidationError';\n }\n}\n\n/**\n * Configuration error for missing or invalid configuration.\n */\nexport class ConfigError extends NexusError {\n constructor(message: string, options?: Partial<Omit<NexusErrorOptions, 'code'>>) {\n super(message, { code: ErrorCode.CONFIG_ERROR, ...options });\n this.name = 'ConfigError';\n }\n}\n\n/**\n * Model error for model adapter failures.\n */\nexport class ModelError extends NexusError {\n constructor(message: string, options?: Partial<Omit<NexusErrorOptions, 'code'>>) {\n super(message, { code: ErrorCode.MODEL_ERROR, ...options });\n this.name = 'ModelError';\n }\n}\n\n/**\n * Agent error for agent execution failures.\n */\nexport class AgentError extends NexusError {\n constructor(message: string, options?: Partial<Omit<NexusErrorOptions, 'code'>>) {\n super(message, { code: ErrorCode.AGENT_ERROR, ...options });\n this.name = 'AgentError';\n }\n}\n\n/**\n * Workflow error for workflow parsing or execution failures.\n */\nexport class WorkflowError extends NexusError {\n constructor(message: string, options?: Partial<Omit<NexusErrorOptions, 'code'>>) {\n super(message, { code: ErrorCode.WORKFLOW_ERROR, ...options });\n this.name = 'WorkflowError';\n }\n}\n\n/**\n * Security error for security violations.\n */\nexport class SecurityError extends NexusError {\n constructor(message: string, options?: Partial<Omit<NexusErrorOptions, 'code'>>) {\n super(message, { code: ErrorCode.SECURITY_ERROR, ...options });\n this.name = 'SecurityError';\n }\n}\n\n/**\n * Timeout error for operation timeouts.\n */\nexport class TimeoutError extends NexusError {\n constructor(message: string, options?: Partial<Omit<NexusErrorOptions, 'code'>>) {\n super(message, { code: ErrorCode.TIMEOUT_ERROR, ...options });\n this.name = 'TimeoutError';\n }\n}\n\n/**\n * Rate limit error for rate limiting violations.\n */\nexport class RateLimitError extends NexusError {\n constructor(message: string, options?: Partial<Omit<NexusErrorOptions, 'code'>>) {\n super(message, { code: ErrorCode.RATE_LIMIT_ERROR, ...options });\n this.name = 'RateLimitError';\n }\n}\n","/**\n * @nexus-agents/core - Structured Logger\n *\n * JSON-structured logging with secret sanitization.\n */\n\n/** Log levels in order of severity */\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\n/** Log context/metadata */\nexport interface LogContext {\n [key: string]: unknown;\n}\n\n/** Structured log entry */\nexport interface LogEntry {\n timestamp: string;\n level: LogLevel;\n message: string;\n context?: LogContext;\n error?: {\n name: string;\n message: string;\n stack?: string;\n };\n}\n\n/** Logger interface */\nexport interface ILogger {\n debug(message: string, context?: LogContext): void;\n info(message: string, context?: LogContext): void;\n warn(message: string, context?: LogContext): void;\n error(message: string, error?: Error, context?: LogContext): void;\n child(context: LogContext): ILogger;\n setLevel(level: LogLevel): void;\n}\n\n/** Patterns to sanitize from logs */\nconst SECRET_PATTERNS = [\n /sk-[a-zA-Z0-9-_]{20,}/g,\n /Bearer [a-zA-Z0-9-_.]+/g,\n /password[\"']?\\s*[:=]\\s*[\"']?[^\"'\\s]+/gi,\n /api[_-]?key[\"']?\\s*[:=]\\s*[\"']?[^\"'\\s]+/gi,\n /secret[\"']?\\s*[:=]\\s*[\"']?[^\"'\\s]+/gi,\n /token[\"']?\\s*[:=]\\s*[\"']?[^\"'\\s]+/gi,\n];\n\nconst LEVEL_PRIORITY: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n};\n\n/**\n * Sanitizes a string by redacting known secret patterns.\n */\nexport function sanitize(text: string): string {\n let result = text;\n for (const pattern of SECRET_PATTERNS) {\n result = result.replace(pattern, '[REDACTED]');\n }\n return result;\n}\n\nfunction formatTimestamp(date: Date): string {\n const formatter = new Intl.DateTimeFormat('en-US', {\n timeZone: 'America/New_York',\n timeZoneName: 'shortOffset',\n });\n const parts = formatter.formatToParts(date);\n const offset = parts.find((p) => p.type === 'timeZoneName')?.value ?? '-05:00';\n const base = date.toLocaleString('sv-SE', {\n timeZone: 'America/New_York',\n hour12: false,\n });\n return base.replace(' ', 'T') + offset.replace('GMT', '');\n}\n\ninterface ErrorEntry {\n name: string;\n message: string;\n stack?: string;\n}\n\nfunction formatError(error: Error): ErrorEntry {\n const entry: ErrorEntry = {\n name: error.name,\n message: sanitize(error.message),\n };\n if (error.stack !== undefined) {\n entry.stack = error.stack;\n }\n return entry;\n}\n\nfunction formatEntry(\n level: LogLevel,\n message: string,\n context: LogContext,\n entryContext?: LogContext,\n error?: Error\n): LogEntry {\n const entry: LogEntry = {\n timestamp: formatTimestamp(new Date()),\n level,\n message: sanitize(message),\n };\n const merged = { ...context, ...entryContext };\n if (Object.keys(merged).length > 0) {\n entry.context = merged;\n }\n if (error !== undefined) {\n entry.error = formatError(error);\n }\n return entry;\n}\n\nfunction writeLog(level: LogLevel, entry: LogEntry): void {\n const output = JSON.stringify(entry) + '\\n';\n if (level === 'debug' || level === 'info') {\n process.stdout.write(output);\n } else {\n process.stderr.write(output);\n }\n}\n\n/**\n * Creates a structured JSON logger.\n */\nexport function createLogger(baseContext?: LogContext): ILogger {\n let currentLevel: LogLevel = 'info';\n const context = baseContext ?? {};\n\n function shouldLog(level: LogLevel): boolean {\n return LEVEL_PRIORITY[level] >= LEVEL_PRIORITY[currentLevel];\n }\n\n function log(level: LogLevel, msg: string, ctx?: LogContext, e?: Error): void {\n if (shouldLog(level)) {\n writeLog(level, formatEntry(level, msg, context, ctx, e));\n }\n }\n\n return {\n debug: (msg, ctx): void => {\n log('debug', msg, ctx);\n },\n info: (msg, ctx): void => {\n log('info', msg, ctx);\n },\n warn: (msg, ctx): void => {\n log('warn', msg, ctx);\n },\n error: (msg, e, ctx): void => {\n log('error', msg, ctx, e);\n },\n child: (childCtx): ILogger => createLogger({ ...context, ...childCtx }),\n setLevel: (level): void => {\n currentLevel = level;\n },\n };\n}\n\n/** Default logger instance */\nexport const logger = createLogger();\n","/**\n * @nexus-agents/core - Model Adapter Types\n *\n * Unified interface for all model adapters (Claude, OpenAI, Gemini, Ollama).\n */\n\nimport type { Result } from '../result.js';\nimport type { ConfigError, ModelError } from '../errors.js';\n\n/**\n * Model capabilities supported by adapters.\n */\nexport const ModelCapability = {\n COMPLETION: 'completion',\n STREAMING: 'streaming',\n TOOL_USE: 'tool_use',\n VISION: 'vision',\n EXTENDED_THINKING: 'extended_thinking',\n} as const;\n\nexport type ModelCapability = (typeof ModelCapability)[keyof typeof ModelCapability];\n\n/**\n * Message role in a conversation.\n */\nexport type MessageRole = 'user' | 'assistant' | 'system';\n\n/**\n * Content block types in messages and responses.\n */\nexport type ContentBlock =\n | { type: 'text'; text: string }\n | { type: 'tool_use'; id: string; name: string; input: unknown }\n | { type: 'tool_result'; tool_use_id: string; content: string; is_error?: boolean }\n | { type: 'image'; source: { type: 'base64'; media_type: string; data: string } };\n\n/**\n * Message in a conversation.\n */\nexport interface Message {\n role: MessageRole;\n content: string | ContentBlock[];\n}\n\n/**\n * Tool definition for function calling.\n */\nexport interface ToolDefinition {\n name: string;\n description: string;\n inputSchema: Record<string, unknown>;\n}\n\n/**\n * Response format specification.\n */\nexport type ResponseFormat =\n | { type: 'text' }\n | { type: 'json_object' }\n | { type: 'json_schema'; schema: Record<string, unknown> };\n\n/**\n * Request to complete a conversation.\n */\nexport interface CompletionRequest {\n /** Conversation messages */\n messages: Message[];\n /** System prompt (if not included in messages) */\n systemPrompt?: string;\n /** Sampling temperature (0.0 - 1.0) */\n temperature?: number;\n /** Maximum tokens to generate */\n maxTokens?: number;\n /** Tools available for the model */\n tools?: ToolDefinition[];\n /** Expected response format */\n responseFormat?: ResponseFormat;\n /** Stop sequences */\n stop?: string[];\n}\n\n/**\n * Token usage statistics.\n */\nexport interface TokenUsage {\n inputTokens: number;\n outputTokens: number;\n totalTokens: number;\n}\n\n/**\n * Reason the model stopped generating.\n */\nexport type StopReason = 'end_turn' | 'max_tokens' | 'stop_sequence' | 'tool_use';\n\n/**\n * Response from a completion request.\n */\nexport interface CompletionResponse {\n /** Response content blocks */\n content: ContentBlock[];\n /** Token usage statistics */\n usage: TokenUsage;\n /** Reason generation stopped */\n stopReason: StopReason;\n /** Model that generated the response */\n model: string;\n}\n\n/**\n * Chunk from a streaming response.\n */\nexport type StreamChunk =\n | { type: 'content_block_start'; index: number; contentBlock: ContentBlock }\n | { type: 'content_block_delta'; index: number; delta: { type: 'text_delta'; text: string } }\n | { type: 'content_block_stop'; index: number }\n | { type: 'message_start'; message: { model: string } }\n | { type: 'message_delta'; delta: { stop_reason: StopReason }; usage: TokenUsage }\n | { type: 'message_stop' };\n\n/**\n * Unified interface for all model adapters.\n */\nexport interface IModelAdapter {\n /** Provider identifier (e.g., 'anthropic', 'openai') */\n readonly providerId: string;\n\n /** Model identifier (e.g., 'claude-sonnet-4', 'gpt-4o') */\n readonly modelId: string;\n\n /** Capabilities this model supports */\n readonly capabilities: readonly ModelCapability[];\n\n /**\n * Send a completion request.\n * @param request - The completion request\n * @returns Result with response or ModelError\n */\n complete(request: CompletionRequest): Promise<Result<CompletionResponse, ModelError>>;\n\n /**\n * Stream a completion request.\n * @param request - The completion request\n * @yields StreamChunk objects as they arrive\n */\n stream(request: CompletionRequest): AsyncIterable<StreamChunk>;\n\n /**\n * Count tokens in text.\n * @param text - Text to count tokens for\n * @returns Approximate token count\n */\n countTokens(text: string): Promise<number>;\n\n /**\n * Validate adapter configuration.\n * @returns Ok if valid, ConfigError if invalid\n */\n validateConfig(): Result<void, ConfigError>;\n}\n","/**\n * @nexus-agents/core - Agent Types\n *\n * Base interface for all agents (TechLead, Experts, dynamic agents).\n */\n\nimport type { Result } from '../result.js';\nimport type { AgentError } from '../errors.js';\n\n/**\n * Agent state in the lifecycle.\n */\nexport type AgentState = 'idle' | 'thinking' | 'acting' | 'waiting' | 'error';\n\n/**\n * Predefined agent roles.\n */\nexport type AgentRole =\n | 'tech_lead'\n | 'code_expert'\n | 'architecture_expert'\n | 'security_expert'\n | 'documentation_expert'\n | 'testing_expert'\n | 'custom';\n\n/**\n * Agent capabilities.\n */\nexport const AgentCapability = {\n TASK_EXECUTION: 'task_execution',\n DELEGATION: 'delegation',\n COLLABORATION: 'collaboration',\n TOOL_USE: 'tool_use',\n CODE_GENERATION: 'code_generation',\n CODE_REVIEW: 'code_review',\n RESEARCH: 'research',\n} as const;\n\nexport type AgentCapability = (typeof AgentCapability)[keyof typeof AgentCapability];\n\n/**\n * Task context and constraints.\n */\nexport interface TaskContext {\n /** Working directory or scope */\n workingDirectory?: string;\n /** Relevant files */\n files?: string[];\n /** Previous messages in conversation */\n history?: TaskHistoryItem[];\n /** Additional metadata */\n metadata?: Record<string, unknown>;\n}\n\nexport interface TaskHistoryItem {\n role: 'user' | 'assistant' | 'system';\n content: string;\n timestamp: string;\n}\n\n/**\n * Constraints on task execution.\n */\nexport interface TaskConstraints {\n /** Maximum execution time in ms */\n maxDuration?: number;\n /** Maximum tokens to use */\n maxTokens?: number;\n /** Required output format */\n outputFormat?: 'text' | 'json' | 'markdown';\n /** Allowed tools */\n allowedTools?: string[];\n}\n\n/**\n * Task to be executed by an agent.\n */\nexport interface Task {\n /** Unique task identifier */\n id: string;\n /** Task description */\n description: string;\n /** Task context */\n context: TaskContext;\n /** Optional constraints */\n constraints?: TaskConstraints;\n /** Priority (higher = more urgent) */\n priority?: number;\n}\n\n/**\n * Metadata about task execution.\n */\nexport interface ResultMetadata {\n /** Execution duration in ms */\n durationMs: number;\n /** Tokens used */\n tokensUsed: number;\n /** Tools invoked */\n toolsUsed: string[];\n /** Model used */\n model: string;\n}\n\n/**\n * Result of task execution.\n */\nexport interface TaskResult {\n /** Task that was executed */\n taskId: string;\n /** Result output */\n output: unknown;\n /** Execution metadata */\n metadata: ResultMetadata;\n}\n\n/**\n * Inter-agent message types.\n */\nexport type AgentMessageType = 'task' | 'result' | 'query' | 'feedback' | 'status';\n\n/**\n * Message between agents.\n */\nexport interface AgentMessage {\n /** Unique message identifier */\n id: string;\n /** Sender agent ID */\n from: string;\n /** Recipient agent ID */\n to: string;\n /** Message type */\n type: AgentMessageType;\n /** Message payload */\n payload: unknown;\n /** Timestamp */\n timestamp: string;\n}\n\n/**\n * Response to an agent message.\n */\nexport interface AgentResponse {\n /** Original message ID */\n messageId: string;\n /** Response status */\n status: 'accepted' | 'rejected' | 'completed' | 'failed';\n /** Response data */\n data?: unknown;\n /** Error message if failed */\n error?: string;\n}\n\n/**\n * Context provided during agent initialization.\n */\nexport interface AgentContext {\n /** Agent configuration */\n config: AgentConfig;\n /** Available tools */\n tools?: string[];\n /** Shared memory/state */\n sharedState?: Record<string, unknown>;\n}\n\n/**\n * Agent configuration.\n */\nexport interface AgentConfig {\n /** Model to use */\n modelId: string;\n /** Temperature for generation */\n temperature?: number;\n /** System prompt */\n systemPrompt?: string;\n /** Maximum context tokens */\n maxContextTokens?: number;\n}\n\n/**\n * Base interface for all agents.\n */\nexport interface IAgent {\n /** Unique agent identifier */\n readonly id: string;\n\n /** Agent role */\n readonly role: AgentRole;\n\n /** Current state */\n readonly state: AgentState;\n\n /** Agent capabilities */\n readonly capabilities: readonly AgentCapability[];\n\n /**\n * Execute a task.\n * @param task - Task to execute\n * @returns Result with TaskResult or AgentError\n */\n execute(task: Task): Promise<Result<TaskResult, AgentError>>;\n\n /**\n * Handle an inter-agent message.\n * @param msg - Message to handle\n * @returns Result with AgentResponse or AgentError\n */\n handleMessage(msg: AgentMessage): Promise<Result<AgentResponse, AgentError>>;\n\n /**\n * Initialize the agent with context.\n * @param ctx - Agent context\n * @returns Result with void or AgentError\n */\n initialize(ctx: AgentContext): Promise<Result<void, AgentError>>;\n\n /**\n * Cleanup agent resources.\n */\n cleanup(): Promise<void>;\n}\n","/**\n * @nexus-agents/core - Workflow Types\n *\n * Interface for workflow execution engine.\n */\n\nimport type { Result } from '../result.js';\nimport type { WorkflowError } from '../errors.js';\nimport type { AgentRole } from './agent.js';\n\n/**\n * Workflow input definition.\n */\nexport interface InputDefinition {\n /** Input name */\n name: string;\n /** Input type */\n type: 'string' | 'number' | 'boolean' | 'object' | 'array';\n /** Description */\n description?: string;\n /** Whether required */\n required?: boolean;\n /** Default value */\n default?: unknown;\n}\n\n/**\n * Single step in a workflow.\n */\nexport interface WorkflowStep {\n /** Unique step identifier */\n id: string;\n /** Agent role to execute this step */\n agent: AgentRole;\n /** Action to perform */\n action: string;\n /** Inputs for the step */\n inputs: Record<string, unknown>;\n /** Step dependencies (wait for these to complete) */\n dependsOn?: string[];\n /** Execute in parallel with dependencies */\n parallel?: boolean;\n /** Number of retry attempts */\n retries?: number;\n /** Timeout in ms */\n timeout?: number;\n /** Condition for execution */\n condition?: string;\n}\n\n/**\n * Workflow definition (loaded from template).\n */\nexport interface WorkflowDefinition {\n /** Workflow name */\n name: string;\n /** Version */\n version: string;\n /** Description */\n description?: string;\n /** Input definitions */\n inputs: InputDefinition[];\n /** Workflow steps */\n steps: WorkflowStep[];\n /** Global timeout in ms */\n timeout?: number;\n}\n\n/**\n * Result of step execution.\n */\nexport interface StepResult {\n /** Step ID */\n stepId: string;\n /** Step output */\n output: unknown;\n /** Duration in ms */\n durationMs: number;\n /** Status */\n status: 'success' | 'failed' | 'skipped';\n /** Error message if failed */\n error?: string;\n}\n\n/**\n * Result of workflow execution.\n */\nexport interface WorkflowResult {\n /** Execution ID */\n executionId: string;\n /** Workflow name */\n workflowName: string;\n /** Step results */\n stepResults: StepResult[];\n /** Final output */\n output: unknown;\n /** Total duration in ms */\n totalDurationMs: number;\n}\n\n/**\n * Workflow execution status.\n */\nexport type ExecutionStatus =\n | { state: 'pending' }\n | { state: 'running'; currentStep: string; progress: number }\n | { state: 'completed'; result: WorkflowResult }\n | { state: 'failed'; error: string; failedStep?: string }\n | { state: 'cancelled'; cancelledAt: string };\n\n/**\n * Workflow template metadata.\n */\nexport interface WorkflowTemplate {\n /** Template name */\n name: string;\n /** Version */\n version: string;\n /** Description */\n description?: string;\n /** File path */\n path: string;\n /** Category */\n category?: string;\n}\n\n/**\n * Parse error for workflow templates.\n */\nexport class ParseError extends Error {\n readonly line: number | undefined;\n readonly column: number | undefined;\n\n constructor(message: string, options?: { line?: number; column?: number }) {\n super(message);\n this.name = 'ParseError';\n this.line = options?.line;\n this.column = options?.column;\n }\n}\n\n/**\n * Workflow engine interface.\n */\nexport interface IWorkflowEngine {\n /**\n * Load workflow template from file.\n * @param path - Path to template file\n * @returns Result with WorkflowDefinition or ParseError\n */\n loadTemplate(path: string): Promise<Result<WorkflowDefinition, ParseError>>;\n\n /**\n * Execute a workflow with inputs.\n * @param workflow - Workflow definition\n * @param inputs - Input values\n * @returns Result with WorkflowResult or WorkflowError\n */\n execute(\n workflow: WorkflowDefinition,\n inputs: Record<string, unknown>\n ): Promise<Result<WorkflowResult, WorkflowError>>;\n\n /**\n * Get execution status.\n * @param executionId - Execution ID to check\n * @returns Current execution status\n */\n getStatus(executionId: string): ExecutionStatus;\n\n /**\n * Cancel a running workflow.\n * @param executionId - Execution ID to cancel\n * @returns Result with void or WorkflowError\n */\n cancel(executionId: string): Promise<Result<void, WorkflowError>>;\n\n /**\n * List available workflow templates.\n * @returns Array of available templates\n */\n listTemplates(): Promise<WorkflowTemplate[]>;\n}\n","/**\n * @nexus-agents/config - Configuration Schemas\n *\n * Zod schemas for all configuration types.\n */\n\nimport { z } from 'zod';\n\n/**\n * Logging configuration schema.\n */\nexport const LoggingConfigSchema = z.object({\n level: z.enum(['debug', 'info', 'warn', 'error']).default('info'),\n format: z.enum(['json', 'pretty']).default('json'),\n destination: z.enum(['stdout', 'stderr', 'file']).default('stdout'),\n filePath: z.string().optional(),\n});\n\nexport type LoggingConfig = z.infer<typeof LoggingConfigSchema>;\n\n/**\n * Provider configuration schema.\n */\nexport const ProviderConfigSchema = z.object({\n apiKey: z.string().optional(),\n baseUrl: z.string().url().optional(),\n timeout: z.number().positive().default(30000),\n maxRetries: z.number().nonnegative().default(3),\n});\n\nexport type ProviderConfig = z.infer<typeof ProviderConfigSchema>;\n\n/**\n * Model tier configuration.\n */\nexport const ModelTiersSchema = z.object({\n fast: z.array(z.string()).min(1),\n balanced: z.array(z.string()).min(1),\n powerful: z.array(z.string()).min(1),\n});\n\nexport type ModelTiers = z.infer<typeof ModelTiersSchema>;\n\n/**\n * Model configuration schema.\n */\nexport const ModelConfigSchema = z.object({\n default: z.string(),\n tiers: ModelTiersSchema,\n providers: z.record(ProviderConfigSchema).optional(),\n});\n\nexport type ModelConfig = z.infer<typeof ModelConfigSchema>;\n\n/**\n * Expert configuration schema.\n */\nexport const ExpertDefinitionSchema = z.object({\n prompt: z.string().min(1),\n tier: z.enum(['fast', 'balanced', 'powerful']).default('balanced'),\n temperature: z.number().min(0).max(1).default(0.3),\n tools: z.array(z.string()).optional(),\n});\n\nexport type ExpertDefinition = z.infer<typeof ExpertDefinitionSchema>;\n\n/**\n * Expert configuration schema.\n */\nexport const ExpertConfigSchema = z.object({\n builtin: z.boolean().default(true),\n custom: z.record(ExpertDefinitionSchema).optional(),\n});\n\nexport type ExpertConfig = z.infer<typeof ExpertConfigSchema>;\n\n/**\n * Workflow configuration schema.\n */\nexport const WorkflowConfigSchema = z.object({\n templatesDir: z.string().default('./workflows'),\n timeout: z.number().positive().default(300000),\n maxParallel: z.number().positive().default(5),\n});\n\nexport type WorkflowConfig = z.infer<typeof WorkflowConfigSchema>;\n\n/**\n * Security configuration schema.\n */\nexport const SecurityConfigSchema = z.object({\n allowedPaths: z.array(z.string()).default(['./']),\n blockedPatterns: z.array(z.string()).default([]),\n rateLimit: z\n .object({\n enabled: z.boolean().default(true),\n requestsPerMinute: z.number().positive().default(60),\n })\n .default({}),\n secretsFile: z.string().optional(),\n});\n\nexport type SecurityConfig = z.infer<typeof SecurityConfigSchema>;\n\n/**\n * Complete application configuration schema.\n */\nexport const AppConfigSchema = z.object({\n models: ModelConfigSchema,\n experts: ExpertConfigSchema.optional(),\n workflows: WorkflowConfigSchema.optional(),\n security: SecurityConfigSchema.optional(),\n logging: LoggingConfigSchema.optional(),\n});\n\nexport type AppConfig = z.infer<typeof AppConfigSchema>;\n\n/**\n * Default configuration values.\n */\nexport const defaultConfig: Partial<AppConfig> = {\n models: {\n default: 'claude-sonnet-4',\n tiers: {\n fast: ['claude-haiku-3', 'gpt-4o-mini'],\n balanced: ['claude-sonnet-4', 'gpt-4o'],\n powerful: ['claude-opus-4', 'o1-pro'],\n },\n },\n logging: {\n level: 'info',\n format: 'json',\n destination: 'stdout',\n },\n};\n","/**\n * @nexus-agents/adapters - Adapter Factory\n *\n * Registry-based factory for creating model adapters.\n * Provides a centralized way to register and create adapters for different providers.\n */\n\nimport { z } from 'zod';\nimport type { Result, IModelAdapter } from '../core/index.js';\nimport { ConfigError, err, ok } from '../core/index.js';\n\n/**\n * Zod schema for adapter configuration.\n * Validates configuration before creating adapters.\n */\nexport const AdapterConfigSchema = z.object({\n /** Provider identifier (e.g., 'anthropic', 'openai') */\n providerId: z.string().min(1, 'Provider ID is required'),\n /** Model identifier (e.g., 'claude-sonnet-4', 'gpt-4o') */\n modelId: z.string().min(1, 'Model ID is required'),\n /** API key for authentication (optional, may come from environment) */\n apiKey: z.string().optional(),\n /** Base URL for the API (optional, uses provider default) */\n baseUrl: z.string().url('Base URL must be a valid URL').optional(),\n /** Request timeout in milliseconds */\n timeout: z.number().positive('Timeout must be positive').optional(),\n /** Maximum number of retries for failed requests */\n maxRetries: z.number().int('Max retries must be an integer').min(0).optional(),\n});\n\n/**\n * Adapter configuration type inferred from schema.\n */\nexport type AdapterConfig = z.infer<typeof AdapterConfigSchema>;\n\n/**\n * Factory function type for creating adapters.\n * Each provider registers a creator function that produces adapters.\n *\n * @param config - The validated adapter configuration\n * @returns A configured model adapter instance\n */\nexport type AdapterCreator = (config: AdapterConfig) => IModelAdapter;\n\n/**\n * Options for registering an adapter provider.\n */\nexport interface RegisterOptions {\n /** Whether to allow overwriting an existing provider */\n allowOverwrite?: boolean;\n}\n\n/**\n * Factory for creating and managing model adapters.\n *\n * Implements the registry pattern to allow dynamic registration of adapter\n * creators for different model providers. This enables a plugin-style\n * architecture where new providers can be added without modifying core code.\n *\n * @example\n * ```typescript\n * const factory = new AdapterFactory();\n *\n * // Register a provider\n * factory.register('anthropic', (config) => new ClaudeAdapter(config));\n *\n * // Create an adapter\n * const result = factory.create({\n * providerId: 'anthropic',\n * modelId: 'claude-sonnet-4'\n * });\n *\n * if (result.ok) {\n * const adapter = result.value;\n * // Use adapter...\n * }\n * ```\n */\nexport class AdapterFactory {\n /**\n * Registry mapping provider IDs to their creator functions.\n */\n private readonly registry: Map<string, AdapterCreator> = new Map();\n\n /**\n * Registers an adapter creator for a provider.\n *\n * @param providerId - Unique identifier for the provider (e.g., 'anthropic')\n * @param creator - Factory function that creates adapters for this provider\n * @param options - Registration options\n * @returns Result indicating success or failure\n *\n * @example\n * ```typescript\n * const result = factory.register('anthropic', (config) => new ClaudeAdapter(config));\n * if (!result.ok) {\n * console.error('Registration failed:', result.error.message);\n * }\n * ```\n */\n register(\n providerId: string,\n creator: AdapterCreator,\n options: RegisterOptions = {}\n ): Result<void, ConfigError> {\n const { allowOverwrite = false } = options;\n\n if (!providerId || providerId.trim() === '') {\n return err(\n new ConfigError('Provider ID cannot be empty', {\n context: { providerId },\n })\n );\n }\n\n if (this.registry.has(providerId) && !allowOverwrite) {\n return err(\n new ConfigError(`Provider '${providerId}' is already registered`, {\n context: { providerId, existingProviders: this.listProviders() },\n })\n );\n }\n\n this.registry.set(providerId, creator);\n return ok(undefined);\n }\n\n /**\n * Unregisters an adapter creator for a provider.\n *\n * @param providerId - The provider ID to unregister\n * @returns Result indicating whether the provider was removed\n */\n unregister(providerId: string): Result<boolean, ConfigError> {\n if (!providerId || providerId.trim() === '') {\n return err(\n new ConfigError('Provider ID cannot be empty', {\n context: { providerId },\n })\n );\n }\n\n const deleted = this.registry.delete(providerId);\n return ok(deleted);\n }\n\n /**\n * Creates an adapter instance for the specified configuration.\n *\n * Validates the configuration against the schema, looks up the provider\n * in the registry, and invokes the creator function to produce an adapter.\n *\n * @param config - Adapter configuration specifying provider and settings\n * @returns Result containing the adapter or a ConfigError\n *\n * @example\n * ```typescript\n * const result = factory.create({\n * providerId: 'anthropic',\n * modelId: 'claude-sonnet-4',\n * timeout: 30000,\n * maxRetries: 3\n * });\n *\n * if (result.ok) {\n * const response = await result.value.complete(request);\n * } else {\n * console.error('Failed to create adapter:', result.error.message);\n * }\n * ```\n */\n create(config: AdapterConfig): Result<IModelAdapter, ConfigError> {\n // Validate configuration\n const validationResult = this.validateConfig(config);\n if (!validationResult.ok) {\n return validationResult;\n }\n const validConfig = validationResult.value;\n\n // Look up provider\n const creator = this.registry.get(validConfig.providerId);\n if (creator === undefined) {\n return err(\n new ConfigError(`Provider '${validConfig.providerId}' is not registered`, {\n context: {\n providerId: validConfig.providerId,\n availableProviders: this.listProviders(),\n },\n })\n );\n }\n\n // Create adapter\n return this.invokeCreator(creator, validConfig);\n }\n\n /**\n * Validates adapter configuration against the schema.\n */\n private validateConfig(config: AdapterConfig): Result<AdapterConfig, ConfigError> {\n const result = AdapterConfigSchema.safeParse(config);\n if (!result.success) {\n const issues = result.error.issues\n .map((issue) => `${issue.path.join('.')}: ${issue.message}`)\n .join('; ');\n return err(\n new ConfigError(`Invalid adapter configuration: ${issues}`, {\n context: {\n config: this.sanitizeConfig(config),\n validationErrors: result.error.issues,\n },\n })\n );\n }\n return ok(result.data);\n }\n\n /**\n * Invokes the creator function to create an adapter.\n */\n private invokeCreator(\n creator: AdapterCreator,\n config: AdapterConfig\n ): Result<IModelAdapter, ConfigError> {\n try {\n return ok(creator(config));\n } catch (error) {\n return this.handleCreatorError(error, config);\n }\n }\n\n /**\n * Handles errors thrown by adapter creator functions.\n */\n private handleCreatorError(error: unknown, config: AdapterConfig): Result<never, ConfigError> {\n const message = error instanceof Error ? error.message : String(error);\n const baseOptions = {\n context: { providerId: config.providerId, modelId: config.modelId },\n };\n if (error instanceof Error) {\n return err(\n new ConfigError(`Failed to create adapter: ${message}`, {\n ...baseOptions,\n cause: error,\n })\n );\n }\n return err(new ConfigError(`Failed to create adapter: ${message}`, baseOptions));\n }\n\n /**\n * Checks if a provider is registered.\n *\n * @param providerId - The provider ID to check\n * @returns True if the provider is registered\n */\n hasProvider(providerId: string): boolean {\n return this.registry.has(providerId);\n }\n\n /**\n * Returns a list of all registered provider IDs.\n *\n * @returns Array of provider identifiers\n */\n listProviders(): string[] {\n return Array.from(this.registry.keys());\n }\n\n /**\n * Returns the number of registered providers.\n *\n * @returns Count of registered providers\n */\n get size(): number {\n return this.registry.size;\n }\n\n /**\n * Clears all registered providers.\n * Useful for testing or resetting the factory state.\n */\n clear(): void {\n this.registry.clear();\n }\n\n /**\n * Sanitizes configuration for logging by removing sensitive fields.\n *\n * @param config - Configuration to sanitize\n * @returns Sanitized configuration safe for logging\n */\n private sanitizeConfig(config: AdapterConfig): Record<string, unknown> {\n const sanitized: Record<string, unknown> = { ...config };\n if (config.apiKey !== undefined) {\n sanitized['apiKey'] = '[REDACTED]';\n }\n return sanitized;\n }\n}\n\n/**\n * Default global adapter factory instance.\n * Use this for convenience when a single factory suffices.\n */\nexport const defaultFactory = new AdapterFactory();\n","/**\n * @nexus-agents/adapters - Token Bucket Rate Limiter\n *\n * A rate limiter implementation using the token bucket algorithm.\n * Tokens are added to the bucket at a fixed rate up to a maximum capacity.\n * Each operation consumes tokens; operations are rejected when insufficient tokens.\n *\n * @see https://en.wikipedia.org/wiki/Token_bucket\n */\n\nimport { type Result, ok, err } from '../core/index.js';\nimport { RateLimitError } from '../core/index.js';\n\n/**\n * Configuration options for the RateLimiter.\n */\nexport interface RateLimiterConfig {\n /**\n * Maximum number of tokens the bucket can hold.\n * This is also the initial token count.\n */\n readonly capacity: number;\n\n /**\n * Number of tokens added to the bucket per second.\n */\n readonly refillRate: number;\n\n /**\n * Interval in milliseconds for automatic refill checks.\n * Only used when waiting for tokens. Default: 100ms.\n */\n readonly refillInterval?: number;\n}\n\n/**\n * Error returned when rate limit is exceeded.\n */\nexport interface RateLimitExceeded {\n readonly type: 'rate_limit_exceeded';\n readonly requested: number;\n readonly available: number;\n readonly retryAfterMs: number;\n}\n\n/**\n * Token bucket rate limiter for controlling request rates.\n *\n * The token bucket algorithm works as follows:\n * 1. A bucket holds tokens up to a maximum capacity\n * 2. Tokens are added at a fixed rate (refillRate per second)\n * 3. Each request consumes one or more tokens\n * 4. If insufficient tokens, the request is rejected or waits\n *\n * @example\n * ```typescript\n * const limiter = new RateLimiter({\n * capacity: 100, // Max 100 tokens\n * refillRate: 10, // 10 tokens per second\n * });\n *\n * if (limiter.tryAcquire()) {\n * // Proceed with operation\n * } else {\n * // Rate limited\n * }\n *\n * // Or wait for tokens\n * await limiter.waitForTokens();\n * ```\n */\nexport class RateLimiter {\n private readonly capacity: number;\n private readonly refillRate: number;\n private readonly refillInterval: number;\n private tokens: number;\n private lastRefillTime: number;\n\n /**\n * Creates a new RateLimiter instance.\n *\n * @param config - Configuration options\n * @throws {RateLimitError} If configuration is invalid\n */\n constructor(config: RateLimiterConfig) {\n this.validateConfig(config);\n\n this.capacity = config.capacity;\n this.refillRate = config.refillRate;\n this.refillInterval = config.refillInterval ?? 100;\n this.tokens = config.capacity;\n this.lastRefillTime = Date.now();\n }\n\n /**\n * Validates the configuration parameters.\n */\n private validateConfig(config: RateLimiterConfig): void {\n if (config.capacity <= 0) {\n throw new RateLimitError('Capacity must be a positive number', {\n context: { capacity: config.capacity },\n });\n }\n if (config.refillRate <= 0) {\n throw new RateLimitError('Refill rate must be a positive number', {\n context: { refillRate: config.refillRate },\n });\n }\n if (config.refillInterval !== undefined && config.refillInterval <= 0) {\n throw new RateLimitError('Refill interval must be a positive number', {\n context: { refillInterval: config.refillInterval },\n });\n }\n }\n\n /**\n * Refills tokens based on elapsed time since last refill.\n * Called automatically before token operations.\n */\n private refill(): void {\n const now = Date.now();\n const elapsedMs = now - this.lastRefillTime;\n const elapsedSeconds = elapsedMs / 1000;\n const tokensToAdd = elapsedSeconds * this.refillRate;\n\n if (tokensToAdd >= 1) {\n this.tokens = Math.min(this.capacity, this.tokens + tokensToAdd);\n this.lastRefillTime = now;\n }\n }\n\n /**\n * Attempts to acquire the specified number of tokens.\n *\n * @param tokens - Number of tokens to acquire (default: 1)\n * @returns true if tokens were acquired, false if rate limited\n *\n * @example\n * ```typescript\n * if (limiter.tryAcquire(5)) {\n * // Acquired 5 tokens\n * }\n * ```\n */\n public tryAcquire(tokens: number = 1): boolean {\n if (tokens <= 0) {\n return true;\n }\n if (tokens > this.capacity) {\n return false;\n }\n\n this.refill();\n\n if (this.tokens >= tokens) {\n this.tokens -= tokens;\n return true;\n }\n\n return false;\n }\n\n /**\n * Attempts to acquire tokens and returns a Result with detailed information.\n *\n * @param tokens - Number of tokens to acquire (default: 1)\n * @returns Result containing void on success, or RateLimitExceeded on failure\n *\n * @example\n * ```typescript\n * const result = limiter.acquire(5);\n * if (!result.ok) {\n * console.log(`Retry after ${result.error.retryAfterMs}ms`);\n * }\n * ```\n */\n public acquire(tokens: number = 1): Result<void, RateLimitExceeded> {\n if (tokens <= 0) {\n return ok(undefined);\n }\n if (tokens > this.capacity) {\n return err({\n type: 'rate_limit_exceeded',\n requested: tokens,\n available: this.tokens,\n retryAfterMs: Infinity,\n });\n }\n\n this.refill();\n\n if (this.tokens >= tokens) {\n this.tokens -= tokens;\n return ok(undefined);\n }\n\n const deficit = tokens - this.tokens;\n const retryAfterMs = Math.ceil((deficit / this.refillRate) * 1000);\n\n return err({\n type: 'rate_limit_exceeded',\n requested: tokens,\n available: Math.floor(this.tokens),\n retryAfterMs,\n });\n }\n\n /**\n * Waits until the specified number of tokens are available, then acquires them.\n *\n * @param tokens - Number of tokens to acquire (default: 1)\n * @returns Promise that resolves when tokens are acquired\n * @throws {RateLimitError} If tokens exceed capacity (would wait forever)\n *\n * @example\n * ```typescript\n * await limiter.waitForTokens(10);\n * // 10 tokens acquired\n * ```\n */\n public async waitForTokens(tokens: number = 1): Promise<void> {\n if (tokens <= 0) {\n return;\n }\n if (tokens > this.capacity) {\n throw new RateLimitError(\n `Cannot acquire ${String(tokens)} tokens: exceeds capacity of ${String(this.capacity)}`,\n { context: { requested: tokens, capacity: this.capacity } }\n );\n }\n\n while (!this.tryAcquire(tokens)) {\n await this.sleep(this.refillInterval);\n }\n }\n\n /**\n * Sleeps for the specified duration.\n */\n private sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n\n /**\n * Returns the current number of available tokens.\n * Performs a refill before returning the count.\n *\n * @returns Number of available tokens (may be fractional)\n */\n public getRemainingTokens(): number {\n this.refill();\n return this.tokens;\n }\n\n /**\n * Returns the number of whole tokens available.\n *\n * @returns Integer number of available tokens\n */\n public getAvailableTokens(): number {\n return Math.floor(this.getRemainingTokens());\n }\n\n /**\n * Resets the rate limiter to its initial state.\n * The bucket is refilled to capacity.\n */\n public reset(): void {\n this.tokens = this.capacity;\n this.lastRefillTime = Date.now();\n }\n\n /**\n * Returns the bucket's maximum capacity.\n */\n public getCapacity(): number {\n return this.capacity;\n }\n\n /**\n * Returns the refill rate in tokens per second.\n */\n public getRefillRate(): number {\n return this.refillRate;\n }\n\n /**\n * Calculates the time in milliseconds until the specified tokens are available.\n *\n * @param tokens - Number of tokens needed (default: 1)\n * @returns Time in milliseconds until tokens are available, 0 if already available\n */\n public getTimeUntilAvailable(tokens: number = 1): number {\n if (tokens <= 0) {\n return 0;\n }\n if (tokens > this.capacity) {\n return Infinity;\n }\n\n this.refill();\n\n if (this.tokens >= tokens) {\n return 0;\n }\n\n const deficit = tokens - this.tokens;\n return Math.ceil((deficit / this.refillRate) * 1000);\n }\n}\n\n/**\n * Creates a rate limiter with the specified configuration.\n * Factory function for cleaner API.\n *\n * @param config - Rate limiter configuration\n * @returns A new RateLimiter instance\n *\n * @example\n * ```typescript\n * const limiter = createRateLimiter({\n * capacity: 100,\n * refillRate: 10,\n * });\n * ```\n */\nexport function createRateLimiter(config: RateLimiterConfig): RateLimiter {\n return new RateLimiter(config);\n}\n","/**\n * @nexus-agents/adapters - Retry Logic with Exponential Backoff\n *\n * Provides retry functionality for fallible operations with exponential backoff\n * and jitter to prevent thundering herd problems.\n *\n * (Source: AWS Architecture Blog - Exponential Backoff and Jitter)\n * (Source: Google Cloud API Design Guide - Retry Strategy)\n */\n\nimport {\n type Result,\n type NexusErrorOptions,\n err,\n ok,\n NexusError,\n ErrorCode,\n} from '../core/index.js';\n\n/**\n * Configuration for retry behavior.\n */\nexport interface RetryConfig {\n /** Maximum number of retry attempts. Default: 3 */\n readonly maxRetries: number;\n /** Base delay in milliseconds between retries. Default: 1000 */\n readonly baseDelayMs: number;\n /** Maximum delay in milliseconds between retries. Default: 30000 */\n readonly maxDelayMs: number;\n /** Jitter factor (0-1) to randomize delay. Default: 0.1 (10%) */\n readonly jitterFactor: number;\n}\n\n/**\n * Default retry configuration.\n */\nexport const DEFAULT_RETRY_CONFIG: Readonly<RetryConfig> = {\n maxRetries: 3,\n baseDelayMs: 1000,\n maxDelayMs: 30000,\n jitterFactor: 0.1,\n} as const;\n\n/**\n * Information about a retry attempt for logging/debugging.\n */\nexport interface RetryAttemptInfo {\n /** Current attempt number (1-based) */\n readonly attempt: number;\n /** Maximum attempts allowed */\n readonly maxAttempts: number;\n /** Delay before next retry in milliseconds */\n readonly delayMs: number;\n /** The error that triggered the retry */\n readonly error: unknown;\n}\n\n/**\n * Error thrown when all retry attempts are exhausted.\n */\nexport class RetryExhaustedError extends NexusError {\n /** Number of attempts made */\n readonly attempts: number;\n /** The last error encountered */\n readonly lastError: unknown;\n\n constructor(attempts: number, lastError: unknown) {\n const message = `All ${String(attempts)} retry attempts exhausted`;\n const options: NexusErrorOptions = {\n code: ErrorCode.MODEL_ERROR,\n context: {\n attempts,\n lastErrorMessage: lastError instanceof Error ? lastError.message : String(lastError),\n },\n };\n // Only set cause if lastError is an Error (exactOptionalPropertyTypes compliance)\n if (lastError instanceof Error) {\n options.cause = lastError;\n }\n super(message, options);\n this.name = 'RetryExhaustedError';\n this.attempts = attempts;\n this.lastError = lastError;\n }\n}\n\n/**\n * Calculates delay with exponential backoff and jitter.\n *\n * Uses full jitter strategy: delay = random(0, min(maxDelay, baseDelay * 2^attempt))\n *\n * @param attempt - Current attempt number (0-based)\n * @param config - Retry configuration\n * @returns Delay in milliseconds\n */\nexport function calculateDelay(attempt: number, config: RetryConfig): number {\n // Exponential backoff: baseDelay * 2^attempt\n const exponentialDelay = config.baseDelayMs * Math.pow(2, attempt);\n\n // Cap at maximum delay\n const cappedDelay = Math.min(exponentialDelay, config.maxDelayMs);\n\n // Apply jitter: delay +/- (delay * jitterFactor)\n const jitterRange = cappedDelay * config.jitterFactor;\n const jitter = (Math.random() * 2 - 1) * jitterRange;\n\n return Math.max(0, Math.floor(cappedDelay + jitter));\n}\n\n/**\n * Creates a promise that resolves after the specified delay.\n *\n * @param ms - Delay in milliseconds\n * @returns Promise that resolves after the delay\n */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * HTTP status codes that indicate a retryable error.\n */\nconst RETRYABLE_STATUS_CODES = new Set([\n 408, // Request Timeout\n 429, // Too Many Requests\n 500, // Internal Server Error\n 502, // Bad Gateway\n 503, // Service Unavailable\n 504, // Gateway Timeout\n]);\n\n/**\n * HTTP status codes that should NOT be retried.\n */\nconst NON_RETRYABLE_STATUS_CODES = new Set([\n 400, // Bad Request\n 401, // Unauthorized\n 403, // Forbidden\n 404, // Not Found\n 405, // Method Not Allowed\n 409, // Conflict\n 410, // Gone\n 422, // Unprocessable Entity\n]);\n\n/**\n * Error message patterns that indicate retryable network errors.\n */\nconst RETRYABLE_ERROR_PATTERNS = [\n /ECONNRESET/i,\n /ECONNREFUSED/i,\n /ETIMEDOUT/i,\n /ENOTFOUND/i,\n /ENETUNREACH/i,\n /EAI_AGAIN/i,\n /socket hang up/i,\n /network/i,\n /timeout/i,\n /timed out/i,\n /aborted/i,\n] as const;\n\n/**\n * Extracts HTTP status code from an error if available.\n *\n * @param error - The error to check\n * @returns The status code or undefined\n */\nfunction getStatusCode(error: unknown): number | undefined {\n if (error === null || error === undefined) {\n return undefined;\n }\n\n // Check common error object shapes\n if (typeof error === 'object') {\n const errorObj = error as Record<string, unknown>;\n\n // Direct status property\n if (typeof errorObj['status'] === 'number') {\n return errorObj['status'];\n }\n\n // Nested in response\n if (typeof errorObj['response'] === 'object' && errorObj['response'] !== null) {\n const response = errorObj['response'] as Record<string, unknown>;\n if (typeof response['status'] === 'number') {\n return response['status'];\n }\n }\n\n // statusCode property (some HTTP clients)\n if (typeof errorObj['statusCode'] === 'number') {\n return errorObj['statusCode'];\n }\n }\n\n return undefined;\n}\n\n/**\n * Determines if an error is retryable based on its type, status code, or message.\n *\n * Retryable errors include:\n * - HTTP 429 (Too Many Requests)\n * - HTTP 5xx (Server Errors)\n * - HTTP 408 (Request Timeout)\n * - Network errors (connection reset, timeout, etc.)\n * - NexusError with rate limit or timeout codes\n *\n * Non-retryable errors include:\n * - HTTP 400, 401, 403, 404 (Client Errors)\n * - Validation errors\n * - Authentication errors\n *\n * @param error - The error to check\n * @returns True if the error is retryable\n */\nexport function isRetryableError(error: unknown): boolean {\n // Null/undefined are not retryable\n if (error === null || error === undefined) {\n return false;\n }\n\n // Check HTTP status code first\n const statusCode = getStatusCode(error);\n if (statusCode !== undefined) {\n if (NON_RETRYABLE_STATUS_CODES.has(statusCode)) {\n return false;\n }\n if (RETRYABLE_STATUS_CODES.has(statusCode)) {\n return true;\n }\n }\n\n // Check NexusError codes\n if (error instanceof NexusError) {\n const retryableCodes: ReadonlyArray<string> = [\n ErrorCode.MODEL_RATE_LIMITED,\n ErrorCode.MODEL_TIMEOUT,\n ErrorCode.TIMEOUT_ERROR,\n ErrorCode.RATE_LIMIT_ERROR,\n ];\n return retryableCodes.includes(error.code);\n }\n\n // Check error message patterns for network errors\n if (error instanceof Error) {\n const message = error.message;\n for (const pattern of RETRYABLE_ERROR_PATTERNS) {\n if (pattern.test(message)) {\n return true;\n }\n }\n }\n\n return false;\n}\n\n/**\n * Merges partial retry config with defaults.\n *\n * @param config - Partial configuration to merge\n * @returns Complete retry configuration\n */\nfunction mergeConfig(config: Partial<RetryConfig>): RetryConfig {\n return {\n maxRetries: config.maxRetries ?? DEFAULT_RETRY_CONFIG.maxRetries,\n baseDelayMs: config.baseDelayMs ?? DEFAULT_RETRY_CONFIG.baseDelayMs,\n maxDelayMs: config.maxDelayMs ?? DEFAULT_RETRY_CONFIG.maxDelayMs,\n jitterFactor: config.jitterFactor ?? DEFAULT_RETRY_CONFIG.jitterFactor,\n };\n}\n\n/**\n * Options for withRetry function.\n */\nexport interface WithRetryOptions {\n /** Retry configuration. Defaults to DEFAULT_RETRY_CONFIG. */\n readonly config?: Partial<RetryConfig>;\n /** Custom predicate to determine if an error is retryable. Defaults to isRetryableError. */\n readonly isRetryable?: (error: unknown) => boolean;\n /** Callback invoked before each retry attempt. Useful for logging. */\n readonly onRetry?: (info: RetryAttemptInfo) => void;\n}\n\n/**\n * Executes an operation with retry logic using exponential backoff.\n *\n * @template T - The return type of the operation\n * @param operation - The async operation to execute\n * @param options - Retry options (config, isRetryable predicate, onRetry callback)\n * @returns A Result containing either the operation result or a RetryExhaustedError\n *\n * @example\n * ```typescript\n * const result = await withRetry(\n * () => fetchData('/api/data'),\n * { config: { maxRetries: 5 } }\n * );\n *\n * if (result.ok) {\n * console.log(result.value);\n * } else {\n * console.error('All retries failed:', result.error);\n * }\n * ```\n */\nexport async function withRetry<T>(\n operation: () => Promise<T>,\n options: WithRetryOptions = {}\n): Promise<Result<T, RetryExhaustedError>> {\n const config = mergeConfig(options.config ?? {});\n const isRetryable = options.isRetryable ?? isRetryableError;\n const onRetry = options.onRetry;\n\n const maxAttempts = config.maxRetries + 1; // Initial attempt + retries\n let lastError: unknown;\n let attemptsMade = 0;\n\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n attemptsMade = attempt + 1;\n try {\n const result = await operation();\n return ok(result);\n } catch (error: unknown) {\n lastError = error;\n\n // Check if we have more attempts and error is retryable\n const isLastAttempt = attempt === maxAttempts - 1;\n if (isLastAttempt || !isRetryable(error)) {\n break;\n }\n\n // Calculate delay for next retry\n const delayMs = calculateDelay(attempt, config);\n\n // Notify about retry attempt\n if (onRetry) {\n onRetry({\n attempt: attempt + 1,\n maxAttempts,\n delayMs,\n error,\n });\n }\n\n // Wait before next attempt\n await sleep(delayMs);\n }\n }\n\n return err(new RetryExhaustedError(attemptsMade, lastError));\n}\n\n/**\n * Wraps an async function with retry logic.\n *\n * @template TArgs - The argument types of the function\n * @template TReturn - The return type of the function\n * @param fn - The function to wrap\n * @param options - Retry options\n * @returns A wrapped function that will retry on failure\n *\n * @example\n * ```typescript\n * const fetchWithRetry = withRetryWrapper(\n * async (url: string) => fetch(url),\n * { config: { maxRetries: 3 } }\n * );\n *\n * const result = await fetchWithRetry('https://api.example.com/data');\n * ```\n */\nexport function withRetryWrapper<TArgs extends unknown[], TReturn>(\n fn: (...args: TArgs) => Promise<TReturn>,\n options: WithRetryOptions = {}\n): (...args: TArgs) => Promise<Result<TReturn, RetryExhaustedError>> {\n return (...args: TArgs) => withRetry(() => fn(...args), options);\n}\n","/**\n * @nexus-agents/adapters - Base Adapter\n *\n * Abstract base class that all model adapters extend.\n * Provides common functionality for token counting, logging, error transformation,\n * and capability checking.\n */\n\nimport type {\n Result,\n IModelAdapter,\n CompletionRequest,\n CompletionResponse,\n StreamChunk,\n ILogger,\n ModelCapability,\n} from '../core/index.js';\nimport {\n ok,\n err,\n ConfigError,\n ModelError,\n NexusError,\n ErrorCode,\n createLogger,\n type NexusErrorOptions,\n} from '../core/index.js';\n\n/**\n * Configuration options for BaseAdapter.\n */\nexport interface BaseAdapterConfig {\n /** Provider identifier (e.g., 'anthropic', 'openai') */\n providerId: string;\n /** Model identifier (e.g., 'claude-sonnet-4', 'gpt-4o') */\n modelId: string;\n /** Capabilities this model supports */\n capabilities: readonly ModelCapability[];\n /** Optional custom logger */\n logger?: ILogger;\n /** API key for authentication (optional, may come from environment) */\n apiKey?: string;\n /** Base URL for the API (optional, uses provider default) */\n baseUrl?: string;\n /** Request timeout in milliseconds */\n timeout?: number;\n /** Maximum number of retries for failed requests */\n maxRetries?: number;\n}\n\n/**\n * Token estimation factor - average characters per token.\n * This is a rough estimate; specific providers may have different tokenization.\n * (Source: OpenAI documentation suggests ~4 chars per token for English text)\n */\nconst CHARS_PER_TOKEN = 4;\n\n/**\n * Extended ModelError that supports specific error codes.\n *\n * While ModelError from core uses MODEL_ERROR by default, this class\n * allows adapters to specify more granular error codes like\n * MODEL_RATE_LIMITED, MODEL_TIMEOUT, etc.\n */\nexport class AdapterModelError extends NexusError {\n constructor(message: string, options: NexusErrorOptions) {\n super(message, options);\n this.name = 'ModelError';\n }\n}\n\n/**\n * Abstract base class for model adapters.\n *\n * Provides default implementations for common adapter functionality while\n * leaving the core API interaction methods abstract for provider-specific\n * implementations.\n *\n * @example\n * ```typescript\n * class ClaudeAdapter extends BaseAdapter {\n * constructor(config: ClaudeAdapterConfig) {\n * super({\n * providerId: 'anthropic',\n * modelId: config.modelId,\n * capabilities: [ModelCapability.COMPLETION, ModelCapability.STREAMING],\n * apiKey: config.apiKey,\n * });\n * }\n *\n * async complete(request: CompletionRequest): Promise<Result<CompletionResponse, ModelError>> {\n * this.logRequest(request);\n * // Provider-specific implementation...\n * }\n *\n * async *stream(request: CompletionRequest): AsyncIterable<StreamChunk> {\n * this.logRequest(request);\n * // Provider-specific streaming implementation...\n * }\n * }\n * ```\n */\nexport abstract class BaseAdapter implements IModelAdapter {\n readonly providerId: string;\n readonly modelId: string;\n readonly capabilities: readonly ModelCapability[];\n\n /** Logger for request/response logging */\n protected readonly logger: ILogger;\n\n /** Configuration for the adapter */\n protected readonly config: BaseAdapterConfig;\n\n /**\n * Creates a new BaseAdapter instance.\n *\n * @param config - Adapter configuration\n */\n constructor(config: BaseAdapterConfig) {\n this.providerId = config.providerId;\n this.modelId = config.modelId;\n this.capabilities = config.capabilities;\n this.config = config;\n this.logger =\n config.logger ??\n createLogger({\n adapter: config.providerId,\n model: config.modelId,\n });\n }\n\n /**\n * Send a completion request to the model.\n * Must be implemented by concrete adapter classes.\n *\n * @param request - The completion request\n * @returns Result with response or ModelError\n */\n abstract complete(request: CompletionRequest): Promise<Result<CompletionResponse, ModelError>>;\n\n /**\n * Stream a completion request from the model.\n * Must be implemented by concrete adapter classes.\n *\n * @param request - The completion request\n * @yields StreamChunk objects as they arrive\n */\n abstract stream(request: CompletionRequest): AsyncIterable<StreamChunk>;\n\n /**\n * Count tokens in text using rough character-based estimation.\n *\n * This provides a reasonable estimate for most use cases.\n * Concrete adapters may override this with provider-specific tokenizers.\n *\n * @param text - Text to count tokens for\n * @returns Approximate token count\n */\n countTokens(text: string): Promise<number> {\n // Rough estimation: ~4 characters per token for English text\n return Promise.resolve(Math.ceil(text.length / CHARS_PER_TOKEN));\n }\n\n /**\n * Validate adapter configuration.\n *\n * Checks that required configuration fields are present and valid.\n * Concrete adapters may override to add provider-specific validation.\n *\n * @returns Ok if valid, ConfigError if invalid\n */\n validateConfig(): Result<void, ConfigError> {\n const errors: string[] = [];\n\n if (!this.providerId || this.providerId.trim() === '') {\n errors.push('Provider ID is required');\n }\n\n if (!this.modelId || this.modelId.trim() === '') {\n errors.push('Model ID is required');\n }\n\n if (this.config.timeout !== undefined && this.config.timeout <= 0) {\n errors.push('Timeout must be positive');\n }\n\n if (this.config.maxRetries !== undefined && this.config.maxRetries < 0) {\n errors.push('Max retries cannot be negative');\n }\n\n if (errors.length > 0) {\n return err(\n new ConfigError(`Invalid adapter configuration: ${errors.join('; ')}`, {\n context: {\n providerId: this.providerId,\n modelId: this.modelId,\n errors,\n },\n })\n );\n }\n\n return ok(undefined);\n }\n\n /**\n * Check if this adapter supports a specific capability.\n *\n * @param capability - The capability to check for\n * @returns True if the capability is supported\n */\n hasCapability(capability: ModelCapability): boolean {\n return this.capabilities.includes(capability);\n }\n\n /**\n * Log details about an outgoing request.\n * Sanitizes sensitive information before logging.\n *\n * @param request - The completion request to log\n */\n protected logRequest(request: CompletionRequest): void {\n const messageCount = request.messages.length;\n const hasTools = request.tools !== undefined && request.tools.length > 0;\n const toolCount = request.tools?.length ?? 0;\n\n this.logger.debug('Sending completion request', {\n messageCount,\n hasSystemPrompt: request.systemPrompt !== undefined,\n temperature: request.temperature,\n maxTokens: request.maxTokens,\n hasTools,\n toolCount,\n responseFormat: request.responseFormat?.type,\n stopSequences: request.stop?.length ?? 0,\n });\n }\n\n /**\n * Log details about a received response.\n *\n * @param response - The completion response to log\n */\n protected logResponse(response: CompletionResponse): void {\n this.logger.debug('Received completion response', {\n contentBlocks: response.content.length,\n stopReason: response.stopReason,\n inputTokens: response.usage.inputTokens,\n outputTokens: response.usage.outputTokens,\n totalTokens: response.usage.totalTokens,\n model: response.model,\n });\n }\n\n /**\n * Transform a provider-specific error into a standardized ModelError.\n *\n * Maps common error patterns to appropriate error codes:\n * - Rate limiting (429, quota exceeded)\n * - Timeouts (ETIMEDOUT, ESOCKETTIMEDOUT)\n * - Authentication (401, 403)\n * - Model unavailable (503, 502)\n *\n * @param error - The original error from the provider\n * @returns A standardized ModelError\n */\n protected transformError(error: unknown): ModelError {\n if (error instanceof ModelError) {\n return error;\n }\n\n const errorMessage = error instanceof Error ? error.message : String(error);\n const errorCode = this.determineErrorCode(error);\n\n // Create a NexusError with the specific code, then use ModelError for standard cases\n // For specialized codes, we extend NexusError behavior\n const modelError = this.createModelError(errorMessage, errorCode, error);\n\n this.logger.error('Model adapter error', modelError, {\n errorCode,\n providerId: this.providerId,\n modelId: this.modelId,\n });\n\n return modelError;\n }\n\n /**\n * Create a ModelError with appropriate error code.\n */\n private createModelError(\n message: string,\n errorCode: (typeof ErrorCode)[keyof typeof ErrorCode],\n originalError: unknown\n ): ModelError {\n const fullMessage = `${this.providerId}/${this.modelId}: ${message}`;\n\n // Build options object conditionally to satisfy exactOptionalPropertyTypes\n const options: NexusErrorOptions = {\n code: errorCode,\n context: {\n providerId: this.providerId,\n modelId: this.modelId,\n },\n };\n\n // Only set cause if originalError is an Error\n if (originalError instanceof Error) {\n options.cause = originalError;\n }\n\n // Use AdapterModelError to support specific error codes\n // This is compatible with ModelError checks (instanceof NexusError)\n return new AdapterModelError(fullMessage, options) as ModelError;\n }\n\n /**\n * Determine the appropriate error code based on error characteristics.\n */\n private determineErrorCode(error: unknown): (typeof ErrorCode)[keyof typeof ErrorCode] {\n if (!(error instanceof Error)) {\n return ErrorCode.MODEL_ERROR;\n }\n\n const message = error.message.toLowerCase();\n const errorObj = error as { status?: number; code?: string };\n\n // Check for rate limiting\n if (this.isRateLimitError(message, errorObj)) {\n return ErrorCode.MODEL_RATE_LIMITED;\n }\n\n // Check for timeout\n if (this.isTimeoutError(message, errorObj)) {\n return ErrorCode.MODEL_TIMEOUT;\n }\n\n // Check for model unavailable\n if (this.isUnavailableError(message, errorObj)) {\n return ErrorCode.MODEL_UNAVAILABLE;\n }\n\n return ErrorCode.MODEL_ERROR;\n }\n\n /**\n * Check if error indicates rate limiting.\n */\n private isRateLimitError(message: string, errorObj: { status?: number; code?: string }): boolean {\n const rateLimitPatterns = ['rate limit', 'too many requests', 'quota exceeded'];\n return (\n errorObj.status === 429 || rateLimitPatterns.some((pattern) => message.includes(pattern))\n );\n }\n\n /**\n * Check if error indicates a timeout.\n */\n private isTimeoutError(message: string, errorObj: { status?: number; code?: string }): boolean {\n const timeoutPatterns = ['timeout', 'etimedout', 'esockettimedout'];\n return (\n errorObj.code === 'ETIMEDOUT' ||\n errorObj.code === 'ESOCKETTIMEDOUT' ||\n timeoutPatterns.some((pattern) => message.includes(pattern))\n );\n }\n\n /**\n * Check if error indicates model unavailability.\n */\n private isUnavailableError(\n message: string,\n errorObj: { status?: number; code?: string }\n ): boolean {\n const unavailablePatterns = ['unavailable', 'service unavailable', 'overloaded'];\n return (\n errorObj.status === 502 ||\n errorObj.status === 503 ||\n unavailablePatterns.some((pattern) => message.includes(pattern))\n );\n }\n}\n","/**\n * @nexus-agents/adapters - Stream Operators\n *\n * Stream transformation operators for AsyncIterables.\n * Provides filter, map, merge, concat, buffer, and other stream operations.\n */\n\nimport { type Result, ok, err } from '../core/index.js';\nimport { TimeoutError } from '../core/index.js';\nimport {\n StreamError,\n StreamCancelledError,\n createStream,\n type CreateStreamOptions,\n} from './streaming.js';\n\n/**\n * Transforms stream chunks using a mapping function.\n * @param stream - The source stream\n * @param fn - Transformation function\n * @param options - Options including optional AbortSignal\n * @returns Transformed stream\n */\nexport async function* transformStream<T, U>(\n stream: AsyncIterable<T>,\n fn: (chunk: T, index: number) => U | Promise<U>,\n options: { signal?: AbortSignal } = {}\n): AsyncIterable<U> {\n let index = 0;\n\n for await (const chunk of stream) {\n if (options.signal?.aborted === true) {\n throw new StreamCancelledError('Transform aborted');\n }\n\n yield await fn(chunk, index);\n index++;\n }\n}\n\n/**\n * Merges multiple streams into a single stream.\n * Chunks are yielded as they arrive from any source.\n * @param streams - The streams to merge\n * @param options - Options including optional AbortSignal\n * @returns Merged stream\n */\nexport async function* mergeStreams<T>(\n streams: AsyncIterable<T>[],\n options: { signal?: AbortSignal } = {}\n): AsyncIterable<T> {\n if (streams.length === 0) {\n return;\n }\n\n const streamOptions: CreateStreamOptions = {};\n if (options.signal) {\n streamOptions.signal = options.signal;\n }\n const [controller, merged] = createStream<T>(streamOptions);\n let activeCount = streams.length;\n\n // Start consuming all streams in parallel\n const consumers = streams.map(async (stream, streamIndex) => {\n try {\n for await (const chunk of stream) {\n if (options.signal?.aborted === true) {\n break;\n }\n controller.push(chunk);\n }\n } catch (error) {\n if (error instanceof StreamCancelledError) {\n // Propagate cancellation\n controller.cancel(`Stream ${String(streamIndex)} was cancelled`);\n return;\n }\n controller.error(error instanceof Error ? error : new Error(String(error)));\n return;\n } finally {\n activeCount--;\n if (activeCount === 0) {\n controller.complete();\n }\n }\n });\n\n // Start all consumers without blocking\n void Promise.all(consumers);\n\n yield* merged;\n}\n\n/**\n * Takes chunks from a stream until a predicate returns true.\n * @param stream - The source stream\n * @param predicate - Function that returns true to stop taking\n * @param options - Options including whether to include the matching chunk\n * @returns Stream of chunks up to (and optionally including) the match\n */\nexport async function* takeUntil<T>(\n stream: AsyncIterable<T>,\n predicate: (chunk: T, index: number) => boolean | Promise<boolean>,\n options: { signal?: AbortSignal; inclusive?: boolean } = {}\n): AsyncIterable<T> {\n let index = 0;\n\n for await (const chunk of stream) {\n if (options.signal?.aborted === true) {\n throw new StreamCancelledError('takeUntil aborted');\n }\n\n const shouldStop = await predicate(chunk, index);\n\n if (shouldStop) {\n if (options.inclusive === true) {\n yield chunk;\n }\n return;\n }\n\n yield chunk;\n index++;\n }\n}\n\n/**\n * Takes the first N chunks from a stream.\n * @param stream - The source stream\n * @param count - Number of chunks to take\n * @param options - Options including optional AbortSignal\n * @returns Stream of first N chunks\n */\nexport async function* take<T>(\n stream: AsyncIterable<T>,\n count: number,\n options: { signal?: AbortSignal } = {}\n): AsyncIterable<T> {\n if (count <= 0) {\n return;\n }\n\n let taken = 0;\n\n for await (const chunk of stream) {\n if (options.signal?.aborted === true) {\n throw new StreamCancelledError('take aborted');\n }\n\n yield chunk;\n taken++;\n\n if (taken >= count) {\n return;\n }\n }\n}\n\n/**\n * Skips the first N chunks from a stream.\n * @param stream - The source stream\n * @param count - Number of chunks to skip\n * @param options - Options including optional AbortSignal\n * @returns Stream with first N chunks skipped\n */\nexport async function* skip<T>(\n stream: AsyncIterable<T>,\n count: number,\n options: { signal?: AbortSignal } = {}\n): AsyncIterable<T> {\n let skipped = 0;\n\n for await (const chunk of stream) {\n if (options.signal?.aborted === true) {\n throw new StreamCancelledError('skip aborted');\n }\n\n if (skipped < count) {\n skipped++;\n continue;\n }\n\n yield chunk;\n }\n}\n\n/**\n * Filters stream chunks based on a predicate.\n * @param stream - The source stream\n * @param predicate - Function that returns true to keep the chunk\n * @param options - Options including optional AbortSignal\n * @returns Filtered stream\n */\nexport async function* filterStream<T>(\n stream: AsyncIterable<T>,\n predicate: (chunk: T, index: number) => boolean | Promise<boolean>,\n options: { signal?: AbortSignal } = {}\n): AsyncIterable<T> {\n let index = 0;\n\n for await (const chunk of stream) {\n if (options.signal?.aborted === true) {\n throw new StreamCancelledError('filter aborted');\n }\n\n if (await predicate(chunk, index)) {\n yield chunk;\n }\n\n index++;\n }\n}\n\n/**\n * Adds a timeout to a stream. If no chunk is received within the timeout,\n * the stream throws a TimeoutError.\n * @param stream - The source stream\n * @param timeoutMs - Timeout in milliseconds\n * @param options - Options including optional AbortSignal\n * @returns Stream with timeout applied\n */\nexport async function* withTimeout<T>(\n stream: AsyncIterable<T>,\n timeoutMs: number,\n options: { signal?: AbortSignal } = {}\n): AsyncIterable<T> {\n const iterator = stream[Symbol.asyncIterator]();\n\n try {\n let running = true;\n while (running) {\n if (options.signal?.aborted === true) {\n throw new StreamCancelledError('withTimeout aborted');\n }\n\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n try {\n const result = await Promise.race([\n iterator.next().then((res) => {\n if (timeoutId !== undefined) {\n clearTimeout(timeoutId);\n }\n return res;\n }),\n new Promise<never>((_, reject) => {\n timeoutId = setTimeout(() => {\n reject(\n new TimeoutError(`Stream timed out after ${String(timeoutMs)}ms`, {\n context: { timeoutMs },\n })\n );\n }, timeoutMs);\n }),\n ]);\n\n if (result.done === true) {\n running = false;\n } else {\n yield result.value;\n }\n } finally {\n if (timeoutId !== undefined) {\n clearTimeout(timeoutId);\n }\n }\n }\n } finally {\n // Ensure the iterator is properly closed\n if (iterator.return !== undefined) {\n await iterator.return();\n }\n }\n}\n\n/**\n * Buffers stream chunks into groups of a specified size.\n * @param stream - The source stream\n * @param size - Buffer size\n * @param options - Options including optional AbortSignal\n * @returns Stream of chunk arrays\n */\nexport async function* bufferStream<T>(\n stream: AsyncIterable<T>,\n size: number,\n options: { signal?: AbortSignal } = {}\n): AsyncIterable<T[]> {\n if (size <= 0) {\n throw new StreamError('Buffer size must be positive');\n }\n\n let buffer: T[] = [];\n\n for await (const chunk of stream) {\n if (options.signal?.aborted === true) {\n throw new StreamCancelledError('buffer aborted');\n }\n\n buffer.push(chunk);\n\n if (buffer.length >= size) {\n yield buffer;\n buffer = [];\n }\n }\n\n // Yield remaining chunks\n if (buffer.length > 0) {\n yield buffer;\n }\n}\n\n/**\n * Concatenates multiple streams sequentially.\n * @param streams - The streams to concatenate\n * @param options - Options including optional AbortSignal\n * @returns Concatenated stream\n */\nexport async function* concatStreams<T>(\n streams: AsyncIterable<T>[],\n options: { signal?: AbortSignal } = {}\n): AsyncIterable<T> {\n for (const stream of streams) {\n if (options.signal?.aborted === true) {\n throw new StreamCancelledError('concat aborted');\n }\n\n yield* stream;\n }\n}\n\n/**\n * Creates a stream from an array of values.\n * @param values - The values to stream\n * @param options - Options including optional delay between chunks\n * @returns Stream of values\n */\nexport async function* fromArray<T>(\n values: T[],\n options: { delayMs?: number; signal?: AbortSignal } = {}\n): AsyncIterable<T> {\n for (const value of values) {\n if (options.signal?.aborted === true) {\n throw new StreamCancelledError('fromArray aborted');\n }\n\n if (options.delayMs !== undefined && options.delayMs > 0) {\n await new Promise((resolve) => setTimeout(resolve, options.delayMs));\n }\n\n yield value;\n }\n}\n\n/**\n * Taps into a stream without modifying it (for side effects like logging).\n * @param stream - The source stream\n * @param fn - Side effect function called for each chunk\n * @param options - Options including optional AbortSignal\n * @returns Original stream unchanged\n */\nexport async function* tapStream<T>(\n stream: AsyncIterable<T>,\n fn: (chunk: T, index: number) => void | Promise<void>,\n options: { signal?: AbortSignal } = {}\n): AsyncIterable<T> {\n let index = 0;\n\n for await (const chunk of stream) {\n if (options.signal?.aborted === true) {\n throw new StreamCancelledError('tap aborted');\n }\n\n await fn(chunk, index);\n yield chunk;\n index++;\n }\n}\n\n/**\n * Reduces a stream to a single value.\n * @param stream - The source stream\n * @param reducer - Reducer function\n * @param initialValue - Initial accumulator value\n * @param options - Options including optional AbortSignal\n * @returns Result containing the final value or error\n */\nexport async function reduceStream<T, U>(\n stream: AsyncIterable<T>,\n reducer: (accumulator: U, chunk: T, index: number) => U | Promise<U>,\n initialValue: U,\n options: { signal?: AbortSignal } = {}\n): Promise<Result<U, StreamError>> {\n let accumulator = initialValue;\n let index = 0;\n\n try {\n for await (const chunk of stream) {\n if (options.signal?.aborted === true) {\n return err(new StreamError('Reduce aborted'));\n }\n\n accumulator = await reducer(accumulator, chunk, index);\n index++;\n }\n\n return ok(accumulator);\n } catch (error) {\n return err(\n new StreamError('Failed to reduce stream', {\n cause: error instanceof Error ? error : new Error(String(error)),\n })\n );\n }\n}\n","/**\n * @nexus-agents/adapters - Streaming Utilities\n *\n * AsyncIterator-based streaming utilities for model responses.\n * Provides stream creation, backpressure handling, cancellation support,\n * and chunk collection helpers.\n *\n * For stream transformation operators (map, filter, merge, etc.),\n * see ./stream-operators.ts\n */\n\nimport { type Result, ok, err } from '../core/index.js';\nimport { NexusError, ErrorCode } from '../core/index.js';\n\n/**\n * Error thrown when a stream operation fails.\n */\nexport class StreamError extends NexusError {\n constructor(message: string, options?: { cause?: Error; context?: Record<string, unknown> }) {\n super(message, { code: ErrorCode.INTERNAL_ERROR, ...options });\n this.name = 'StreamError';\n }\n}\n\n/**\n * Error thrown when a stream is cancelled.\n */\nexport class StreamCancelledError extends NexusError {\n constructor(reason?: string) {\n super(reason ?? 'Stream was cancelled', { code: ErrorCode.INTERNAL_ERROR });\n this.name = 'StreamCancelledError';\n }\n}\n\n/**\n * State of a stream controller.\n */\nexport type StreamState = 'idle' | 'streaming' | 'paused' | 'cancelled' | 'completed' | 'error';\n\n/**\n * Options for creating a stream.\n */\nexport interface CreateStreamOptions {\n /** AbortSignal for cancellation support */\n signal?: AbortSignal;\n /** Maximum buffer size for backpressure (default: 100) */\n maxBufferSize?: number;\n}\n\n/**\n * Controller for managing stream lifecycle.\n * Provides push/complete/error methods and cancellation support.\n */\nexport class StreamController<T> {\n private readonly chunks: T[] = [];\n private readonly waiters: Array<{\n resolve: (result: IteratorResult<T, void>) => void;\n reject: (error: Error) => void;\n }> = [];\n\n private _state: StreamState = 'idle';\n private _error: Error | undefined;\n private readonly maxBufferSize: number;\n private readonly abortHandler: (() => void) | undefined;\n\n /**\n * Creates a new StreamController.\n * @param options - Stream creation options\n */\n constructor(options: CreateStreamOptions = {}) {\n this.maxBufferSize = options.maxBufferSize ?? 100;\n\n if (options.signal) {\n this.abortHandler = (): void => {\n this.cancel('AbortSignal triggered');\n };\n options.signal.addEventListener('abort', this.abortHandler);\n }\n }\n\n /**\n * Current state of the stream.\n */\n get state(): StreamState {\n return this._state;\n }\n\n /**\n * Whether the stream is still active (can receive chunks).\n */\n get isActive(): boolean {\n return this._state === 'idle' || this._state === 'streaming' || this._state === 'paused';\n }\n\n /**\n * Current buffer size.\n */\n get bufferSize(): number {\n return this.chunks.length;\n }\n\n /**\n * Push a chunk to the stream.\n * @param chunk - The chunk to push\n * @returns Result indicating success or backpressure\n */\n push(chunk: T): Result<void, StreamError> {\n if (!this.isActive) {\n return err(new StreamError(`Cannot push to stream in state: ${this._state}`));\n }\n\n if (this._state === 'idle') {\n this._state = 'streaming';\n }\n\n // If there's a waiting consumer, deliver directly\n const waiter = this.waiters.shift();\n if (waiter) {\n waiter.resolve({ done: false, value: chunk });\n return ok(undefined);\n }\n\n // Check backpressure\n if (this.chunks.length >= this.maxBufferSize) {\n this._state = 'paused';\n return err(\n new StreamError('Buffer full - backpressure applied', {\n context: { bufferSize: this.chunks.length, maxBufferSize: this.maxBufferSize },\n })\n );\n }\n\n this.chunks.push(chunk);\n return ok(undefined);\n }\n\n /**\n * Complete the stream successfully.\n */\n complete(): void {\n if (!this.isActive) {\n return;\n }\n\n this._state = 'completed';\n this.resolveAllWaiters();\n }\n\n /**\n * Complete the stream with an error.\n * @param error - The error that occurred\n */\n error(error: Error): void {\n if (!this.isActive) {\n return;\n }\n\n this._state = 'error';\n this._error = error;\n this.rejectAllWaiters(error);\n }\n\n /**\n * Cancel the stream.\n * @param reason - Optional reason for cancellation\n */\n cancel(reason?: string): void {\n if (!this.isActive) {\n return;\n }\n\n this._state = 'cancelled';\n this._error = new StreamCancelledError(reason);\n this.rejectAllWaiters(this._error);\n }\n\n /**\n * Get the AsyncIterable for consuming the stream.\n */\n getIterable(): AsyncIterable<T> {\n // Store reference to controller methods for closure\n const nextChunk = (): Promise<IteratorResult<T, void>> => this.nextChunk();\n const cancel = (reason: string): void => {\n this.cancel(reason);\n };\n\n return {\n [Symbol.asyncIterator](): AsyncIterator<T> {\n return {\n async next(): Promise<IteratorResult<T, void>> {\n return nextChunk();\n },\n return(): Promise<IteratorResult<T, void>> {\n cancel('Iterator returned');\n return Promise.resolve({ done: true, value: undefined });\n },\n };\n },\n };\n }\n\n private async nextChunk(): Promise<IteratorResult<T, void>> {\n // If we have buffered chunks, return one\n const chunk = this.chunks.shift();\n if (chunk !== undefined) {\n // Resume if we were paused and buffer is now below threshold\n if (this._state === 'paused' && this.chunks.length < this.maxBufferSize / 2) {\n this._state = 'streaming';\n }\n return { done: false, value: chunk };\n }\n\n // Check terminal states\n if (this._state === 'completed') {\n return { done: true, value: undefined };\n }\n\n if (this._state === 'cancelled' || this._state === 'error') {\n throw this._error ?? new StreamCancelledError();\n }\n\n // Wait for next chunk\n return new Promise((resolve, reject) => {\n this.waiters.push({ resolve, reject });\n });\n }\n\n private resolveAllWaiters(): void {\n for (const waiter of this.waiters) {\n waiter.resolve({ done: true, value: undefined });\n }\n this.waiters.length = 0;\n }\n\n private rejectAllWaiters(error: Error): void {\n for (const waiter of this.waiters) {\n waiter.reject(error);\n }\n this.waiters.length = 0;\n }\n}\n\n/**\n * Creates a controllable stream.\n * @param options - Stream creation options\n * @returns Tuple of [controller, iterable]\n */\nexport function createStream<T>(\n options: CreateStreamOptions = {}\n): [StreamController<T>, AsyncIterable<T>] {\n const controller = new StreamController<T>(options);\n return [controller, controller.getIterable()];\n}\n\n/**\n * Collects all chunks from a stream into an array.\n * @param stream - The stream to collect\n * @param options - Options including optional AbortSignal\n * @returns Result containing collected chunks or error\n */\nexport async function collectStream<T>(\n stream: AsyncIterable<T>,\n options: { signal?: AbortSignal; maxChunks?: number } = {}\n): Promise<Result<T[], StreamError>> {\n const chunks: T[] = [];\n const maxChunks = options.maxChunks ?? Infinity;\n\n try {\n for await (const chunk of stream) {\n if (options.signal?.aborted === true) {\n return err(new StreamError('Collection aborted'));\n }\n\n chunks.push(chunk);\n\n if (chunks.length >= maxChunks) {\n break;\n }\n }\n\n return ok(chunks);\n } catch (error) {\n if (error instanceof StreamCancelledError) {\n return err(new StreamError('Stream was cancelled during collection', { cause: error }));\n }\n return err(\n new StreamError('Failed to collect stream', {\n cause: error instanceof Error ? error : new Error(String(error)),\n })\n );\n }\n}\n\n// Re-export all stream operators for convenience\nexport {\n transformStream,\n mergeStreams,\n takeUntil,\n take,\n skip,\n filterStream,\n withTimeout,\n bufferStream,\n concatStreams,\n fromArray,\n tapStream,\n reduceStream,\n} from './stream-operators.js';\n","/**\n * @nexus-agents/adapters - Claude/Anthropic Model Adapter\n *\n * Adapter for Anthropic's Claude models (claude-opus-4, claude-sonnet-4, claude-haiku-3).\n * Implements the IModelAdapter interface with streaming support, rate limiting,\n * and proper error handling.\n *\n * Verified 2026-01-03: @anthropic-ai/sdk@0.71.2 is current stable\n * (Source: npm registry)\n */\n\nimport Anthropic from '@anthropic-ai/sdk';\nimport type {\n MessageParam,\n ContentBlock as AnthropicContentBlock,\n MessageStreamEvent,\n} from '@anthropic-ai/sdk/resources/messages';\nimport type {\n Result,\n CompletionRequest,\n CompletionResponse,\n StreamChunk,\n ContentBlock,\n Message,\n ToolDefinition,\n TokenUsage,\n StopReason,\n} from '../core/index.js';\nimport { ok, err, ModelError, ConfigError, ModelCapability } from '../core/index.js';\nimport { BaseAdapter, type BaseAdapterConfig } from './base-adapter.js';\nimport { createStream } from './streaming.js';\n\n/**\n * Supported Claude model identifiers.\n */\nexport const CLAUDE_MODELS = {\n OPUS_4: 'claude-opus-4-20250514',\n SONNET_4: 'claude-sonnet-4-20250514',\n HAIKU_3: 'claude-3-haiku-20240307',\n} as const;\n\n/**\n * Model aliases for convenience.\n */\nexport const CLAUDE_MODEL_ALIASES: Record<string, string> = {\n 'claude-opus-4': CLAUDE_MODELS.OPUS_4,\n 'claude-sonnet-4': CLAUDE_MODELS.SONNET_4,\n 'claude-haiku-3': CLAUDE_MODELS.HAIKU_3,\n} as const;\n\n/**\n * Configuration specific to ClaudeAdapter.\n */\nexport interface ClaudeAdapterConfig {\n /** Model ID (e.g., 'claude-sonnet-4' or full model identifier) */\n modelId: string;\n /** API key for Anthropic API (required) */\n apiKey: string;\n /** Base URL for API (optional, defaults to Anthropic's API) */\n baseUrl?: string;\n /** Request timeout in milliseconds (optional) */\n timeout?: number;\n /** Maximum retries for failed requests (optional) */\n maxRetries?: number;\n}\n\n/**\n * Characters per token estimate for Claude models.\n * Claude uses a custom tokenizer, but ~3.5 chars/token is a reasonable estimate\n * for English text.\n * (Source: Anthropic documentation on token counting)\n */\nconst CLAUDE_CHARS_PER_TOKEN = 3.5;\n\n/**\n * Default maximum tokens for Claude models.\n */\nconst DEFAULT_MAX_TOKENS = 4096;\n\n/**\n * Maps Anthropic stop reasons to our StopReason type.\n */\nfunction mapStopReason(anthropicReason: string | null): StopReason {\n switch (anthropicReason) {\n case 'end_turn':\n return 'end_turn';\n case 'max_tokens':\n return 'max_tokens';\n case 'stop_sequence':\n return 'stop_sequence';\n case 'tool_use':\n return 'tool_use';\n default:\n return 'end_turn';\n }\n}\n\n/**\n * Maps Anthropic content blocks to our ContentBlock type.\n */\nfunction mapContentBlock(block: AnthropicContentBlock): ContentBlock {\n if (block.type === 'text') {\n return { type: 'text', text: block.text };\n }\n if (block.type === 'tool_use') {\n const toolBlock = block;\n return {\n type: 'tool_use',\n id: toolBlock.id,\n name: toolBlock.name,\n input: toolBlock.input,\n };\n }\n // Handle unexpected block types gracefully\n return { type: 'text', text: '' };\n}\n\n/**\n * Maps our Message format to Anthropic's MessageParam format.\n */\nfunction mapMessage(message: Message): MessageParam {\n const role = message.role === 'user' ? 'user' : 'assistant';\n\n if (typeof message.content === 'string') {\n return { role, content: message.content };\n }\n\n // Map content blocks\n const content = message.content.map((block) => {\n if (block.type === 'text') {\n return { type: 'text' as const, text: block.text };\n }\n if (block.type === 'tool_use') {\n return {\n type: 'tool_use' as const,\n id: block.id,\n name: block.name,\n input: block.input,\n };\n }\n if (block.type === 'tool_result') {\n const toolResult: {\n type: 'tool_result';\n tool_use_id: string;\n content: string;\n is_error?: boolean;\n } = {\n type: 'tool_result' as const,\n tool_use_id: block.tool_use_id,\n content: block.content,\n };\n // Only set is_error if explicitly defined (exactOptionalPropertyTypes)\n if (block.is_error !== undefined) {\n toolResult.is_error = block.is_error;\n }\n return toolResult;\n }\n // Image type is the remaining possibility\n // Cast source to match Anthropic's expected type\n return {\n type: 'image' as const,\n source: block.source as Anthropic.ImageBlockParam['source'],\n };\n });\n\n return { role, content };\n}\n\n/**\n * Maps our ToolDefinition to Anthropic's tool format.\n */\nfunction mapTool(tool: ToolDefinition): Anthropic.Tool {\n return {\n name: tool.name,\n description: tool.description,\n input_schema: tool.inputSchema as Anthropic.Tool.InputSchema,\n };\n}\n\n/**\n * Resolves model alias to full model identifier.\n */\nfunction resolveModelId(modelId: string): string {\n return CLAUDE_MODEL_ALIASES[modelId] ?? modelId;\n}\n\n/**\n * Determines capabilities based on model ID.\n */\nfunction getModelCapabilities(modelId: string): readonly ModelCapability[] {\n const capabilities: ModelCapability[] = [\n ModelCapability.COMPLETION,\n ModelCapability.STREAMING,\n ModelCapability.TOOL_USE,\n ModelCapability.VISION,\n ];\n\n // Extended thinking is available on Opus and Sonnet 4\n const resolvedId = resolveModelId(modelId);\n if (resolvedId.includes('opus') || resolvedId.includes('sonnet-4')) {\n capabilities.push(ModelCapability.EXTENDED_THINKING);\n }\n\n return capabilities;\n}\n\n/**\n * Claude/Anthropic model adapter.\n *\n * Provides a unified interface for interacting with Anthropic's Claude models.\n * Supports completion, streaming, tool use, and vision capabilities.\n *\n * @example\n * ```typescript\n * const adapter = new ClaudeAdapter({\n * modelId: 'claude-sonnet-4',\n * apiKey: process.env.ANTHROPIC_API_KEY,\n * });\n *\n * const result = await adapter.complete({\n * messages: [{ role: 'user', content: 'Hello!' }],\n * maxTokens: 1024,\n * });\n *\n * if (result.ok) {\n * console.log(result.value.content);\n * }\n * ```\n */\nexport class ClaudeAdapter extends BaseAdapter {\n private readonly client: Anthropic;\n private readonly resolvedModelId: string;\n\n /**\n * Creates a new ClaudeAdapter instance.\n *\n * @param config - Claude adapter configuration\n * @throws {ConfigError} If API key is missing\n */\n constructor(config: ClaudeAdapterConfig) {\n const resolvedModelId = resolveModelId(config.modelId);\n\n // Build baseConfig conditionally to satisfy exactOptionalPropertyTypes\n const baseConfig: BaseAdapterConfig = {\n providerId: 'anthropic',\n modelId: resolvedModelId,\n capabilities: getModelCapabilities(config.modelId),\n apiKey: config.apiKey,\n };\n\n // Only set optional properties if defined\n if (config.baseUrl !== undefined) {\n baseConfig.baseUrl = config.baseUrl;\n }\n if (config.timeout !== undefined) {\n baseConfig.timeout = config.timeout;\n }\n if (config.maxRetries !== undefined) {\n baseConfig.maxRetries = config.maxRetries;\n }\n\n super(baseConfig);\n\n this.resolvedModelId = resolvedModelId;\n\n // Validate API key presence\n if (!config.apiKey || config.apiKey.trim() === '') {\n throw new ConfigError('Anthropic API key is required', {\n context: { providerId: 'anthropic', modelId: config.modelId },\n });\n }\n\n // Create Anthropic client\n this.client = new Anthropic({\n apiKey: config.apiKey,\n baseURL: config.baseUrl,\n timeout: config.timeout,\n maxRetries: config.maxRetries ?? 2,\n });\n }\n\n /**\n * Validates adapter configuration.\n * Extends base validation with Claude-specific checks.\n */\n override validateConfig(): Result<void, ConfigError> {\n const baseResult = super.validateConfig();\n if (!baseResult.ok) {\n return baseResult;\n }\n\n // Validate API key is present\n const apiKey = this.config.apiKey;\n if (apiKey === undefined || apiKey === '' || apiKey.trim() === '') {\n return err(\n new ConfigError('Anthropic API key is required', {\n context: { providerId: this.providerId, modelId: this.modelId },\n })\n );\n }\n\n return ok(undefined);\n }\n\n /**\n * Send a completion request to Claude.\n *\n * @param request - The completion request\n * @returns Result with response or ModelError\n */\n async complete(request: CompletionRequest): Promise<Result<CompletionResponse, ModelError>> {\n this.logRequest(request);\n\n try {\n const response = await this.executeCompletion(request);\n this.logResponse(response);\n return ok(response);\n } catch (error) {\n return err(this.transformError(error));\n }\n }\n\n /**\n * Stream a completion request from Claude.\n *\n * @param request - The completion request\n * @yields StreamChunk objects as they arrive\n */\n async *stream(request: CompletionRequest): AsyncIterable<StreamChunk> {\n this.logRequest(request);\n\n const [controller, iterable] = createStream<StreamChunk>();\n\n // Start streaming in the background\n this.executeStream(request, controller).catch((error: unknown) => {\n const modelError = this.transformError(error);\n controller.error(modelError);\n });\n\n yield* iterable;\n }\n\n /**\n * Count tokens in text using Claude-specific estimation.\n *\n * Claude uses a custom tokenizer. This provides a more accurate estimate\n * than the base adapter's generic calculation.\n *\n * @param text - Text to count tokens for\n * @returns Approximate token count\n */\n override countTokens(text: string): Promise<number> {\n // Claude tokenizes slightly differently than GPT models\n // ~3.5 characters per token is a reasonable estimate for English\n return Promise.resolve(Math.ceil(text.length / CLAUDE_CHARS_PER_TOKEN));\n }\n\n /**\n * Executes the completion request against the Anthropic API.\n */\n private async executeCompletion(request: CompletionRequest): Promise<CompletionResponse> {\n const params = this.buildRequestParams(request);\n const response = await this.client.messages.create(params);\n\n return this.mapResponse(response);\n }\n\n /**\n * Executes streaming completion and pushes chunks to the controller.\n */\n private async executeStream(\n request: CompletionRequest,\n controller: {\n push: (chunk: StreamChunk) => Result<void, Error>;\n complete: () => void;\n error: (error: Error) => void;\n }\n ): Promise<void> {\n try {\n const params = this.buildRequestParams(request);\n const stream = this.client.messages.stream(params);\n\n for await (const event of stream) {\n const chunk = this.mapStreamEvent(event);\n if (chunk) {\n controller.push(chunk);\n }\n }\n\n controller.complete();\n } catch (error) {\n const modelError = this.transformError(error as Error);\n controller.error(modelError);\n }\n }\n\n /**\n * Extracts system prompt from request, checking both systemPrompt field and messages.\n */\n private extractSystemPrompt(request: CompletionRequest): string | undefined {\n // Check explicit systemPrompt field first\n if (request.systemPrompt !== undefined && request.systemPrompt !== '') {\n return request.systemPrompt;\n }\n\n // Check for system message in messages array\n const systemMessage = request.messages.find((m) => m.role === 'system');\n if (systemMessage === undefined) {\n return undefined;\n }\n\n if (typeof systemMessage.content === 'string') {\n return systemMessage.content;\n }\n\n return systemMessage.content\n .filter((b): b is { type: 'text'; text: string } => b.type === 'text')\n .map((b) => b.text)\n .join('\\n');\n }\n\n /**\n * Builds Anthropic API request parameters from our CompletionRequest.\n */\n private buildRequestParams(\n request: CompletionRequest\n ): Anthropic.MessageCreateParamsNonStreaming {\n // Filter out system messages and map the rest\n const messages = request.messages.filter((m) => m.role !== 'system').map(mapMessage);\n\n const params: Anthropic.MessageCreateParamsNonStreaming = {\n model: this.resolvedModelId,\n messages,\n max_tokens: request.maxTokens ?? DEFAULT_MAX_TOKENS,\n };\n\n // Add system prompt if provided\n const systemPrompt = this.extractSystemPrompt(request);\n if (systemPrompt !== undefined) {\n params.system = systemPrompt;\n }\n\n // Apply optional parameters\n this.applyOptionalParams(params, request);\n\n return params;\n }\n\n /**\n * Applies optional parameters to the request params.\n */\n private applyOptionalParams(\n params: Anthropic.MessageCreateParamsNonStreaming,\n request: CompletionRequest\n ): void {\n if (request.temperature !== undefined) {\n params.temperature = request.temperature;\n }\n\n if (request.stop !== undefined && request.stop.length > 0) {\n params.stop_sequences = request.stop;\n }\n\n if (request.tools !== undefined && request.tools.length > 0) {\n params.tools = request.tools.map(mapTool);\n }\n }\n\n /**\n * Maps Anthropic API response to our CompletionResponse format.\n */\n private mapResponse(response: Anthropic.Message): CompletionResponse {\n const content: ContentBlock[] = response.content.map(mapContentBlock);\n\n const usage: TokenUsage = {\n inputTokens: response.usage.input_tokens,\n outputTokens: response.usage.output_tokens,\n totalTokens: response.usage.input_tokens + response.usage.output_tokens,\n };\n\n return {\n content,\n usage,\n stopReason: mapStopReason(response.stop_reason),\n model: response.model,\n };\n }\n\n /**\n * Maps Anthropic stream events to our StreamChunk format.\n */\n private mapStreamEvent(event: MessageStreamEvent): StreamChunk | null {\n switch (event.type) {\n case 'message_start':\n return {\n type: 'message_start',\n message: { model: event.message.model },\n };\n\n case 'content_block_start':\n return {\n type: 'content_block_start',\n index: event.index,\n contentBlock: mapContentBlock(event.content_block),\n };\n\n case 'content_block_delta':\n if (event.delta.type === 'text_delta') {\n return {\n type: 'content_block_delta',\n index: event.index,\n delta: { type: 'text_delta', text: event.delta.text },\n };\n }\n return null;\n\n case 'content_block_stop':\n return {\n type: 'content_block_stop',\n index: event.index,\n };\n\n case 'message_delta':\n return {\n type: 'message_delta',\n delta: { stop_reason: mapStopReason(event.delta.stop_reason ?? null) },\n usage: {\n inputTokens: 0, // Not available in delta\n outputTokens: event.usage.output_tokens,\n totalTokens: event.usage.output_tokens,\n },\n };\n\n case 'message_stop':\n return { type: 'message_stop' };\n\n default:\n return null;\n }\n }\n}\n\n/**\n * Creates a ClaudeAdapter with the specified configuration.\n * Factory function for cleaner API.\n *\n * @param config - Claude adapter configuration\n * @returns A configured ClaudeAdapter instance\n *\n * @example\n * ```typescript\n * const adapter = createClaudeAdapter({\n * modelId: 'claude-sonnet-4',\n * apiKey: process.env.ANTHROPIC_API_KEY!,\n * });\n * ```\n */\nexport function createClaudeAdapter(config: ClaudeAdapterConfig): ClaudeAdapter {\n return new ClaudeAdapter(config);\n}\n","/**\n * @nexus-agents/adapters - OpenAI Model Adapter\n *\n * Adapter for OpenAI models (GPT-4o, GPT-4-turbo, GPT-3.5-turbo).\n * Implements the IModelAdapter interface with streaming support, rate limiting,\n * and proper error handling.\n *\n * Verified 2026-01-03: openai@6.15.0 is current stable\n * (Source: npm registry)\n */\n\nimport OpenAI from 'openai';\nimport type { ChatCompletionMessageParam, ChatCompletion } from 'openai/resources/chat/completions';\nimport type {\n Result,\n CompletionRequest,\n CompletionResponse,\n StreamChunk,\n TokenUsage,\n} from '../core/index.js';\nimport { ok, err, ModelError, ConfigError } from '../core/index.js';\nimport { BaseAdapter, type BaseAdapterConfig } from './base-adapter.js';\nimport { createStream } from './streaming.js';\nimport {\n OPENAI_CHARS_PER_TOKEN,\n DEFAULT_MAX_TOKENS,\n resolveModelId,\n getModelCapabilities,\n type OpenAIAdapterConfig,\n} from './openai-types.js';\nimport {\n mapMessage,\n mapTool,\n mapStopReason,\n mapChoiceToContentBlocks,\n mapResponseUsage,\n mapStreamChunk,\n} from './openai-mappers.js';\n\n// Re-export types and constants for public API\nexport { OPENAI_MODELS, OPENAI_MODEL_ALIASES, type OpenAIAdapterConfig } from './openai-types.js';\n\n/**\n * OpenAI model adapter.\n *\n * Provides a unified interface for interacting with OpenAI's GPT models.\n * Supports completion, streaming, tool use, and vision capabilities.\n *\n * @example\n * ```typescript\n * const adapter = new OpenAIAdapter({\n * modelId: 'gpt-4o',\n * apiKey: process.env.OPENAI_API_KEY,\n * });\n *\n * const result = await adapter.complete({\n * messages: [{ role: 'user', content: 'Hello!' }],\n * maxTokens: 1024,\n * });\n *\n * if (result.ok) {\n * console.log(result.value.content);\n * }\n * ```\n */\nexport class OpenAIAdapter extends BaseAdapter {\n private readonly client: OpenAI;\n private readonly resolvedModelId: string;\n\n /**\n * Creates a new OpenAIAdapter instance.\n *\n * @param config - OpenAI adapter configuration\n * @throws {ConfigError} If API key is missing\n */\n constructor(config: OpenAIAdapterConfig) {\n const resolvedModelId = resolveModelId(config.modelId);\n\n // Build baseConfig conditionally to satisfy exactOptionalPropertyTypes\n const baseConfig: BaseAdapterConfig = {\n providerId: 'openai',\n modelId: resolvedModelId,\n capabilities: getModelCapabilities(config.modelId),\n apiKey: config.apiKey,\n };\n\n // Only set optional properties if defined\n if (config.baseUrl !== undefined) {\n baseConfig.baseUrl = config.baseUrl;\n }\n if (config.timeout !== undefined) {\n baseConfig.timeout = config.timeout;\n }\n if (config.maxRetries !== undefined) {\n baseConfig.maxRetries = config.maxRetries;\n }\n\n super(baseConfig);\n\n this.resolvedModelId = resolvedModelId;\n\n // Validate API key presence\n if (!config.apiKey || config.apiKey.trim() === '') {\n throw new ConfigError('OpenAI API key is required', {\n context: { providerId: 'openai', modelId: config.modelId },\n });\n }\n\n this.client = this.createClient(config);\n }\n\n /**\n * Creates the OpenAI client with configuration.\n */\n private createClient(config: OpenAIAdapterConfig): OpenAI {\n const clientOptions: ConstructorParameters<typeof OpenAI>[0] = {\n apiKey: config.apiKey,\n maxRetries: config.maxRetries ?? 2,\n };\n\n if (config.baseUrl !== undefined) {\n clientOptions.baseURL = config.baseUrl;\n }\n if (config.timeout !== undefined) {\n clientOptions.timeout = config.timeout;\n }\n if (config.organization !== undefined) {\n clientOptions.organization = config.organization;\n }\n\n return new OpenAI(clientOptions);\n }\n\n /**\n * Validates adapter configuration.\n * Extends base validation with OpenAI-specific checks.\n */\n override validateConfig(): Result<void, ConfigError> {\n const baseResult = super.validateConfig();\n if (!baseResult.ok) {\n return baseResult;\n }\n\n // Validate API key is present\n const apiKey = this.config.apiKey;\n if (apiKey === undefined || apiKey === '' || apiKey.trim() === '') {\n return err(\n new ConfigError('OpenAI API key is required', {\n context: { providerId: this.providerId, modelId: this.modelId },\n })\n );\n }\n\n return ok(undefined);\n }\n\n /**\n * Send a completion request to OpenAI.\n *\n * @param request - The completion request\n * @returns Result with response or ModelError\n */\n async complete(request: CompletionRequest): Promise<Result<CompletionResponse, ModelError>> {\n this.logRequest(request);\n\n try {\n const response = await this.executeCompletion(request);\n this.logResponse(response);\n return ok(response);\n } catch (error) {\n return err(this.transformError(error));\n }\n }\n\n /**\n * Stream a completion request from OpenAI.\n *\n * @param request - The completion request\n * @yields StreamChunk objects as they arrive\n */\n async *stream(request: CompletionRequest): AsyncIterable<StreamChunk> {\n this.logRequest(request);\n\n const [controller, iterable] = createStream<StreamChunk>();\n\n // Start streaming in the background\n this.executeStream(request, controller).catch((error: unknown) => {\n const modelError = this.transformError(error);\n controller.error(modelError);\n });\n\n yield* iterable;\n }\n\n /**\n * Count tokens in text using OpenAI-specific estimation.\n *\n * @param text - Text to count tokens for\n * @returns Approximate token count\n */\n override countTokens(text: string): Promise<number> {\n return Promise.resolve(Math.ceil(text.length / OPENAI_CHARS_PER_TOKEN));\n }\n\n /**\n * Executes the completion request against the OpenAI API.\n */\n private async executeCompletion(request: CompletionRequest): Promise<CompletionResponse> {\n const params = this.buildRequestParams(request);\n const response = await this.client.chat.completions.create(params);\n return this.mapResponse(response);\n }\n\n /**\n * Executes streaming completion and pushes chunks to the controller.\n */\n private async executeStream(\n request: CompletionRequest,\n controller: {\n push: (chunk: StreamChunk) => Result<void, Error>;\n complete: () => void;\n error: (error: Error) => void;\n }\n ): Promise<void> {\n try {\n const params = this.buildRequestParams(request);\n const stream = await this.client.chat.completions.create({ ...params, stream: true });\n\n let contentIndex = 0;\n let hasStarted = false;\n\n for await (const chunk of stream) {\n const mappedChunks = mapStreamChunk(chunk, contentIndex, hasStarted);\n\n for (const mappedChunk of mappedChunks) {\n if (mappedChunk.type === 'message_start') {\n hasStarted = true;\n }\n if (mappedChunk.type === 'content_block_start') {\n contentIndex++;\n }\n controller.push(mappedChunk);\n }\n }\n\n controller.complete();\n } catch (error) {\n const modelError = this.transformError(error as Error);\n controller.error(modelError);\n }\n }\n\n /**\n * Builds OpenAI API request parameters from our CompletionRequest.\n */\n private buildRequestParams(\n request: CompletionRequest\n ): OpenAI.Chat.ChatCompletionCreateParamsNonStreaming {\n const messages = this.buildMessages(request);\n\n const params: OpenAI.Chat.ChatCompletionCreateParamsNonStreaming = {\n model: this.resolvedModelId,\n messages,\n max_completion_tokens: request.maxTokens ?? DEFAULT_MAX_TOKENS,\n };\n\n this.addOptionalParams(params, request);\n return params;\n }\n\n /**\n * Builds the messages array for the request.\n */\n private buildMessages(request: CompletionRequest): ChatCompletionMessageParam[] {\n const messages: ChatCompletionMessageParam[] = [];\n\n // Add system prompt if provided explicitly\n if (request.systemPrompt !== undefined && request.systemPrompt !== '') {\n messages.push({ role: 'system', content: request.systemPrompt });\n }\n\n // Map and add all messages (filtering out system if already added via systemPrompt)\n for (const msg of request.messages) {\n if (msg.role === 'system' && request.systemPrompt !== undefined) {\n continue;\n }\n messages.push(mapMessage(msg));\n }\n\n return messages;\n }\n\n /**\n * Adds optional parameters to the request.\n */\n private addOptionalParams(\n params: OpenAI.Chat.ChatCompletionCreateParamsNonStreaming,\n request: CompletionRequest\n ): void {\n if (request.temperature !== undefined) {\n params.temperature = request.temperature;\n }\n\n if (request.stop !== undefined && request.stop.length > 0) {\n params.stop = request.stop;\n }\n\n if (request.tools !== undefined && request.tools.length > 0) {\n params.tools = request.tools.map(mapTool);\n }\n\n this.addResponseFormat(params, request);\n }\n\n /**\n * Adds response format to the request if specified.\n */\n private addResponseFormat(\n params: OpenAI.Chat.ChatCompletionCreateParamsNonStreaming,\n request: CompletionRequest\n ): void {\n if (request.responseFormat === undefined) {\n return;\n }\n\n if (request.responseFormat.type === 'json_object') {\n params.response_format = { type: 'json_object' };\n } else if (request.responseFormat.type === 'json_schema') {\n params.response_format = {\n type: 'json_schema',\n json_schema: {\n name: 'response',\n schema: request.responseFormat.schema,\n },\n };\n }\n }\n\n /**\n * Maps OpenAI API response to our CompletionResponse format.\n */\n private mapResponse(response: ChatCompletion): CompletionResponse {\n const firstChoice = response.choices[0];\n\n // Handle case where no choices are returned\n if (firstChoice === undefined) {\n return this.createEmptyResponse(response);\n }\n\n const content = mapChoiceToContentBlocks(firstChoice);\n const usage: TokenUsage = mapResponseUsage(response);\n\n return {\n content,\n usage,\n stopReason: mapStopReason(firstChoice.finish_reason),\n model: response.model,\n };\n }\n\n /**\n * Creates an empty response when no choices are returned.\n */\n private createEmptyResponse(response: ChatCompletion): CompletionResponse {\n return {\n content: [{ type: 'text', text: '' }],\n usage: mapResponseUsage(response),\n stopReason: 'end_turn',\n model: response.model,\n };\n }\n}\n\n/**\n * Creates an OpenAIAdapter with the specified configuration.\n * Factory function for cleaner API.\n *\n * @param config - OpenAI adapter configuration\n * @returns A configured OpenAIAdapter instance\n *\n * @example\n * ```typescript\n * const adapter = createOpenAIAdapter({\n * modelId: 'gpt-4o',\n * apiKey: process.env.OPENAI_API_KEY!,\n * });\n * ```\n */\nexport function createOpenAIAdapter(config: OpenAIAdapterConfig): OpenAIAdapter {\n return new OpenAIAdapter(config);\n}\n","/**\n * @nexus-agents/adapters - OpenAI Type Helpers\n *\n * Type definitions and constants for OpenAI adapter.\n */\n\nimport type { ModelCapability } from '../core/index.js';\nimport { ModelCapability as MC } from '../core/index.js';\n\n/**\n * Supported OpenAI model identifiers.\n */\nexport const OPENAI_MODELS = {\n GPT_5_2: 'gpt-5.2',\n GPT_5_2_INSTANT: 'gpt-5.2-chat-latest',\n GPT_5_2_PRO: 'gpt-5.2-pro',\n GPT_5_2_CODEX: 'gpt-5.2-codex',\n GPT_4O: 'gpt-4o-2024-11-20',\n GPT_4O_MINI: 'gpt-4o-mini-2024-07-18',\n GPT_4_TURBO: 'gpt-4-turbo-2024-04-09',\n GPT_35_TURBO: 'gpt-3.5-turbo-0125',\n} as const;\n\n/**\n * Model aliases for convenience.\n */\nexport const OPENAI_MODEL_ALIASES: Record<string, string> = {\n // GPT-5.2 aliases\n 'gpt-5.2': OPENAI_MODELS.GPT_5_2,\n 'gpt-5.2-instant': OPENAI_MODELS.GPT_5_2_INSTANT,\n 'gpt-5.2-chat-latest': OPENAI_MODELS.GPT_5_2_INSTANT,\n 'gpt-5.2-pro': OPENAI_MODELS.GPT_5_2_PRO,\n 'gpt-5.2-codex': OPENAI_MODELS.GPT_5_2_CODEX,\n // GPT-4o aliases\n 'gpt-4o': OPENAI_MODELS.GPT_4O,\n 'gpt-4o-mini': OPENAI_MODELS.GPT_4O_MINI,\n 'gpt-4-turbo': OPENAI_MODELS.GPT_4_TURBO,\n 'gpt-3.5-turbo': OPENAI_MODELS.GPT_35_TURBO,\n} as const;\n\n/**\n * Configuration specific to OpenAIAdapter.\n */\nexport interface OpenAIAdapterConfig {\n /** Model ID (e.g., 'gpt-4o' or full model identifier) */\n modelId: string;\n /** API key for OpenAI API (required) */\n apiKey: string;\n /** Base URL for API (optional, defaults to OpenAI's API) */\n baseUrl?: string;\n /** Request timeout in milliseconds (optional) */\n timeout?: number;\n /** Maximum retries for failed requests (optional) */\n maxRetries?: number;\n /** Organization ID (optional) */\n organization?: string;\n}\n\n/**\n * Characters per token estimate for OpenAI models.\n * ~4 chars/token is the standard estimate for English text.\n * (Source: OpenAI documentation on tokenization)\n */\nexport const OPENAI_CHARS_PER_TOKEN = 4;\n\n/**\n * Default maximum tokens for OpenAI models.\n */\nexport const DEFAULT_MAX_TOKENS = 4096;\n\n/**\n * Tool call type for extracting function info.\n */\nexport interface FunctionToolCall {\n id: string;\n type: 'function';\n function: {\n name: string;\n arguments: string;\n };\n}\n\n/**\n * Type guard for function tool calls.\n * Note: typeof null === 'object' is true, so we need to check tc !== null\n */\nexport function isFunctionToolCall(toolCall: unknown): toolCall is FunctionToolCall {\n if (typeof toolCall !== 'object' || toolCall === null) {\n return false;\n }\n const tc = toolCall as Record<string, unknown>;\n return tc['type'] === 'function' && typeof tc['function'] === 'object' && tc['function'] !== null;\n}\n\n/**\n * Resolves model alias to full model identifier.\n */\nexport function resolveModelId(modelId: string): string {\n return OPENAI_MODEL_ALIASES[modelId] ?? modelId;\n}\n\n/**\n * Determines capabilities based on model ID.\n */\nexport function getModelCapabilities(modelId: string): readonly ModelCapability[] {\n const capabilities: ModelCapability[] = [MC.COMPLETION, MC.STREAMING, MC.TOOL_USE];\n\n const resolvedId = resolveModelId(modelId);\n\n // Vision is available on GPT-4o, GPT-4-turbo, and GPT-5.2 models\n if (\n resolvedId.includes('gpt-4o') ||\n resolvedId.includes('gpt-4-turbo') ||\n resolvedId.includes('gpt-5.2')\n ) {\n capabilities.push(MC.VISION);\n }\n\n // Extended thinking is available on GPT-5.2 models\n if (resolvedId.includes('gpt-5.2')) {\n capabilities.push(MC.EXTENDED_THINKING);\n }\n\n return capabilities;\n}\n","/**\n * @nexus-agents/adapters - OpenAI Message Mappers\n *\n * Functions for mapping between Nexus and OpenAI message formats.\n */\n\nimport type OpenAI from 'openai';\nimport type {\n ChatCompletionMessageParam,\n ChatCompletionTool,\n ChatCompletion,\n ChatCompletionChunk,\n} from 'openai/resources/chat/completions';\nimport type {\n ContentBlock,\n Message,\n ToolDefinition,\n TokenUsage,\n StopReason,\n StreamChunk,\n} from '../core/index.js';\nimport { isFunctionToolCall } from './openai-types.js';\n\n/**\n * Maps OpenAI finish reasons to our StopReason type.\n */\nexport function mapStopReason(openaiReason: string | null | undefined): StopReason {\n switch (openaiReason) {\n case 'stop':\n return 'end_turn';\n case 'length':\n return 'max_tokens';\n case 'tool_calls':\n case 'function_call':\n return 'tool_use';\n case 'content_filter':\n return 'end_turn';\n default:\n return 'end_turn';\n }\n}\n\n/**\n * Maps OpenAI choice to our ContentBlock array.\n */\nexport function mapChoiceToContentBlocks(choice: ChatCompletion.Choice): ContentBlock[] {\n const blocks: ContentBlock[] = [];\n const message = choice.message;\n\n // Add text content if present\n if (message.content !== null && message.content !== '') {\n blocks.push({ type: 'text', text: message.content });\n }\n\n // Add tool calls if present\n if (message.tool_calls !== undefined && message.tool_calls.length > 0) {\n for (const toolCall of message.tool_calls) {\n if (isFunctionToolCall(toolCall)) {\n blocks.push({\n type: 'tool_use',\n id: toolCall.id,\n name: toolCall.function.name,\n input: JSON.parse(toolCall.function.arguments) as unknown,\n });\n }\n }\n }\n\n // If no content at all, return empty text block\n if (blocks.length === 0) {\n blocks.push({ type: 'text', text: '' });\n }\n\n return blocks;\n}\n\n/**\n * Maps our Message format to OpenAI's ChatCompletionMessageParam format.\n */\nexport function mapMessage(message: Message): ChatCompletionMessageParam {\n // Handle system messages\n if (message.role === 'system') {\n return mapSystemMessage(message);\n }\n\n // Handle user messages\n if (message.role === 'user') {\n return mapUserMessage(message);\n }\n\n // Handle assistant messages\n return mapAssistantMessage(message);\n}\n\n/**\n * Maps a system message.\n */\nfunction mapSystemMessage(message: Message): ChatCompletionMessageParam {\n const content =\n typeof message.content === 'string'\n ? message.content\n : message.content\n .filter((b): b is { type: 'text'; text: string } => b.type === 'text')\n .map((b) => b.text)\n .join('\\n');\n return { role: 'system', content };\n}\n\n/**\n * Maps a user message.\n */\nfunction mapUserMessage(message: Message): ChatCompletionMessageParam {\n if (typeof message.content === 'string') {\n return { role: 'user', content: message.content };\n }\n\n // Check for tool results - these need special handling\n const toolResults = message.content.filter(\n (b): b is { type: 'tool_result'; tool_use_id: string; content: string; is_error?: boolean } =>\n b.type === 'tool_result'\n );\n\n if (toolResults.length > 0) {\n // Return first tool result as a tool message\n const firstResult = toolResults[0];\n if (firstResult !== undefined) {\n return {\n role: 'tool',\n tool_call_id: firstResult.tool_use_id,\n content: firstResult.content,\n };\n }\n }\n\n // Map to user message with content array\n const content = message.content.map((block) => {\n if (block.type === 'text') {\n return { type: 'text' as const, text: block.text };\n }\n if (block.type === 'image') {\n return {\n type: 'image_url' as const,\n image_url: {\n url: `data:${block.source.media_type};base64,${block.source.data}`,\n },\n };\n }\n // Fallback for other types\n return { type: 'text' as const, text: '' };\n });\n\n return { role: 'user', content };\n}\n\n/**\n * Maps an assistant message.\n */\nfunction mapAssistantMessage(message: Message): ChatCompletionMessageParam {\n if (typeof message.content === 'string') {\n return { role: 'assistant', content: message.content };\n }\n\n // Check for tool uses in assistant message\n const toolUses = message.content.filter(\n (b): b is { type: 'tool_use'; id: string; name: string; input: unknown } =>\n b.type === 'tool_use'\n );\n\n const textContent = message.content\n .filter((b): b is { type: 'text'; text: string } => b.type === 'text')\n .map((b) => b.text)\n .join('');\n\n if (toolUses.length > 0) {\n const assistantMessage: ChatCompletionMessageParam = {\n role: 'assistant',\n content: textContent !== '' ? textContent : null,\n tool_calls: toolUses.map((tool) => ({\n id: tool.id,\n type: 'function' as const,\n function: {\n name: tool.name,\n arguments: JSON.stringify(tool.input),\n },\n })),\n };\n return assistantMessage;\n }\n\n return { role: 'assistant', content: textContent };\n}\n\n/**\n * Maps our ToolDefinition to OpenAI's tool format.\n */\nexport function mapTool(tool: ToolDefinition): ChatCompletionTool {\n return {\n type: 'function',\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.inputSchema,\n },\n };\n}\n\n/**\n * Maps OpenAI API response to our CompletionResponse format.\n */\nexport function mapResponseUsage(response: ChatCompletion): TokenUsage {\n return {\n inputTokens: response.usage?.prompt_tokens ?? 0,\n outputTokens: response.usage?.completion_tokens ?? 0,\n totalTokens: response.usage?.total_tokens ?? 0,\n };\n}\n\n/**\n * Maps content delta from stream chunk.\n */\nfunction mapContentDelta(\n delta: OpenAI.Chat.ChatCompletionChunk.Choice.Delta,\n currentIndex: number,\n hasStarted: boolean\n): StreamChunk[] {\n const chunks: StreamChunk[] = [];\n\n if (delta.content !== undefined && delta.content !== null && delta.content !== '') {\n // Start content block if this is the first content\n if (currentIndex === 0 && !hasStarted) {\n chunks.push({\n type: 'content_block_start',\n index: 0,\n contentBlock: { type: 'text', text: '' },\n });\n }\n\n chunks.push({\n type: 'content_block_delta',\n index: currentIndex,\n delta: { type: 'text_delta', text: delta.content },\n });\n }\n\n return chunks;\n}\n\n/**\n * Maps tool calls from stream chunk delta.\n */\nfunction mapToolCallsDelta(delta: OpenAI.Chat.ChatCompletionChunk.Choice.Delta): StreamChunk[] {\n const chunks: StreamChunk[] = [];\n\n if (delta.tool_calls !== undefined && delta.tool_calls.length > 0) {\n for (const toolCall of delta.tool_calls) {\n if (toolCall.function?.name !== undefined) {\n chunks.push({\n type: 'content_block_start',\n index: toolCall.index,\n contentBlock: {\n type: 'tool_use',\n id: toolCall.id ?? '',\n name: toolCall.function.name,\n input: {},\n },\n });\n }\n }\n }\n\n return chunks;\n}\n\n/**\n * Maps finish reason from stream chunk.\n */\nfunction mapFinishChunks(\n choice: ChatCompletionChunk.Choice,\n chunk: ChatCompletionChunk,\n currentIndex: number\n): StreamChunk[] {\n const chunks: StreamChunk[] = [];\n\n if (choice.finish_reason !== null) {\n // End current content block\n chunks.push({\n type: 'content_block_stop',\n index: currentIndex,\n });\n\n // Emit message_delta with stop reason\n chunks.push({\n type: 'message_delta',\n delta: { stop_reason: mapStopReason(choice.finish_reason) },\n usage: {\n inputTokens: 0,\n outputTokens: chunk.usage?.completion_tokens ?? 0,\n totalTokens: chunk.usage?.total_tokens ?? 0,\n },\n });\n\n // Emit message_stop\n chunks.push({ type: 'message_stop' });\n }\n\n return chunks;\n}\n\n/**\n * Maps OpenAI stream chunks to our StreamChunk format.\n */\nexport function mapStreamChunk(\n chunk: ChatCompletionChunk,\n currentIndex: number,\n hasStarted: boolean\n): StreamChunk[] {\n const chunks: StreamChunk[] = [];\n const choice = chunk.choices[0];\n\n // Emit message_start on first chunk\n if (!hasStarted) {\n chunks.push({\n type: 'message_start',\n message: { model: chunk.model },\n });\n }\n\n if (choice === undefined) {\n return chunks;\n }\n\n const delta = choice.delta;\n\n // Map content delta\n chunks.push(...mapContentDelta(delta, currentIndex, hasStarted));\n\n // Map tool calls\n chunks.push(...mapToolCallsDelta(delta));\n\n // Map finish reason\n chunks.push(...mapFinishChunks(choice, chunk, currentIndex));\n\n return chunks;\n}\n","/**\n * @nexus-agents/adapters - Ollama Model Adapter\n *\n * Adapter for local Ollama models (llama3, mistral, codellama, etc.).\n * Verified 2026-01-03: ollama@0.6.3 is current stable (Source: npm registry)\n */\n\nimport { Ollama } from 'ollama';\nimport type {\n ChatRequest as OllamaChatRequest,\n ChatResponse as OllamaChatResponse,\n Message as OllamaMessage,\n Tool as OllamaTool,\n} from 'ollama';\nimport type {\n Result,\n CompletionRequest,\n CompletionResponse,\n StreamChunk,\n ContentBlock,\n Message,\n ToolDefinition,\n TokenUsage,\n StopReason,\n} from '../core/index.js';\nimport { ok, err, ModelError, ConfigError, ModelCapability } from '../core/index.js';\nimport { BaseAdapter, type BaseAdapterConfig } from './base-adapter.js';\nimport { createStream } from './streaming.js';\n\n/** Popular Ollama model identifiers. */\nexport const OLLAMA_MODELS = {\n LLAMA3_8B: 'llama3:8b',\n LLAMA3_70B: 'llama3:70b',\n LLAMA3_1_8B: 'llama3.1:8b',\n LLAMA3_2_3B: 'llama3.2:3b',\n MISTRAL: 'mistral',\n MISTRAL_NEMO: 'mistral-nemo',\n CODELLAMA: 'codellama',\n CODELLAMA_34B: 'codellama:34b',\n DEEPSEEK_CODER: 'deepseek-coder',\n QWEN2_5_CODER: 'qwen2.5-coder',\n PHI3: 'phi3',\n GEMMA2: 'gemma2',\n} as const;\n\nconst DEFAULT_OLLAMA_HOST = 'http://localhost:11434';\nconst DEFAULT_MAX_TOKENS = 2048;\nconst OLLAMA_CHARS_PER_TOKEN = 4;\n\n/** Configuration specific to OllamaAdapter. */\nexport interface OllamaAdapterConfig {\n modelId: string;\n baseUrl?: string;\n timeout?: number;\n maxRetries?: number;\n headers?: Record<string, string>;\n}\n\nfunction mapStopReason(reason: string | undefined): StopReason {\n if (reason === undefined || reason === '') return 'end_turn';\n switch (reason) {\n case 'stop':\n return 'end_turn';\n case 'length':\n return 'max_tokens';\n case 'tool_calls':\n return 'tool_use';\n default:\n return 'end_turn';\n }\n}\n\nfunction mapOllamaMessageToContent(message: OllamaMessage): ContentBlock[] {\n const content: ContentBlock[] = [];\n const messageContent = message.content;\n if (messageContent !== '' && messageContent.length > 0) {\n content.push({ type: 'text', text: messageContent });\n }\n const toolCalls = message.tool_calls;\n if (toolCalls !== undefined && toolCalls.length > 0) {\n for (const tc of toolCalls) {\n content.push({\n type: 'tool_use',\n id: `tool_${String(Date.now())}_${Math.random().toString(36).slice(2, 9)}`,\n name: tc.function.name,\n input: tc.function.arguments,\n });\n }\n }\n if (content.length === 0) content.push({ type: 'text', text: '' });\n return content;\n}\n\nfunction mapMessage(message: Message): OllamaMessage {\n if (typeof message.content === 'string') {\n return { role: message.role, content: message.content };\n }\n const textParts = message.content\n .filter((b): b is { type: 'text'; text: string } => b.type === 'text')\n .map((b) => b.text);\n const ollamaMessage: OllamaMessage = { role: message.role, content: textParts.join('\\n') };\n const toolResult = message.content.find(\n (b): b is { type: 'tool_result'; tool_use_id: string; content: string } =>\n b.type === 'tool_result'\n );\n if (toolResult !== undefined) {\n ollamaMessage.content = toolResult.content;\n ollamaMessage.tool_name = toolResult.tool_use_id;\n }\n return ollamaMessage;\n}\n\nfunction mapTool(tool: ToolDefinition): OllamaTool {\n const fn: OllamaTool['function'] = { name: tool.name, description: tool.description };\n const schema = tool.inputSchema;\n const hasProperties = Object.keys(schema).length > 0;\n if (hasProperties) {\n fn.parameters = schema as NonNullable<OllamaTool['function']['parameters']>;\n }\n return { type: 'function', function: fn };\n}\n\nfunction getModelCapabilities(modelId: string): readonly ModelCapability[] {\n const caps: ModelCapability[] = [ModelCapability.COMPLETION, ModelCapability.STREAMING];\n const lower = modelId.toLowerCase();\n const toolModels = [\n 'llama3',\n 'mistral',\n 'qwen',\n 'deepseek',\n 'command-r',\n 'hermes',\n 'functionary',\n ];\n if (toolModels.some((m) => lower.includes(m))) caps.push(ModelCapability.TOOL_USE);\n const visionModels = ['llava', 'bakllava', 'moondream', 'llama3.2-vision'];\n if (visionModels.some((m) => lower.includes(m))) caps.push(ModelCapability.VISION);\n return caps;\n}\n\n/** Ollama model adapter for local model inference. */\nexport class OllamaAdapter extends BaseAdapter {\n private readonly client: Ollama;\n\n constructor(config: OllamaAdapterConfig) {\n const baseUrl = config.baseUrl ?? DEFAULT_OLLAMA_HOST;\n const baseConfig: BaseAdapterConfig = {\n providerId: 'ollama',\n modelId: config.modelId,\n capabilities: getModelCapabilities(config.modelId),\n baseUrl,\n };\n if (config.timeout !== undefined) baseConfig.timeout = config.timeout;\n if (config.maxRetries !== undefined) baseConfig.maxRetries = config.maxRetries;\n super(baseConfig);\n this.client = new Ollama({ host: baseUrl, headers: config.headers });\n }\n\n override validateConfig(): Result<void, ConfigError> {\n const baseResult = super.validateConfig();\n if (!baseResult.ok) return baseResult;\n if (this.modelId === '' || this.modelId.trim() === '') {\n return err(\n new ConfigError('Ollama model ID is required', { context: { providerId: this.providerId } })\n );\n }\n return ok(undefined);\n }\n\n async complete(request: CompletionRequest): Promise<Result<CompletionResponse, ModelError>> {\n this.logRequest(request);\n try {\n const params = this.buildRequestParams(request);\n const response = await this.client.chat({ ...params, stream: false });\n const result = this.mapResponse(response);\n this.logResponse(result);\n return ok(result);\n } catch (error) {\n return err(this.transformError(error));\n }\n }\n\n async *stream(request: CompletionRequest): AsyncIterable<StreamChunk> {\n this.logRequest(request);\n const [controller, iterable] = createStream<StreamChunk>();\n this.executeStream(request, controller).catch((error: unknown) => {\n controller.error(this.transformError(error));\n });\n yield* iterable;\n }\n\n override countTokens(text: string): Promise<number> {\n return Promise.resolve(Math.ceil(text.length / OLLAMA_CHARS_PER_TOKEN));\n }\n\n private async executeStream(\n request: CompletionRequest,\n controller: {\n push: (c: StreamChunk) => Result<void, Error>;\n complete: () => void;\n error: (e: Error) => void;\n }\n ): Promise<void> {\n try {\n const params = this.buildRequestParams(request);\n const stream = await this.client.chat({ ...params, stream: true });\n controller.push({ type: 'message_start', message: { model: this.modelId } });\n let hasStartedBlock = false;\n for await (const chunk of stream) {\n if (!hasStartedBlock) {\n controller.push({\n type: 'content_block_start',\n index: 0,\n contentBlock: { type: 'text', text: '' },\n });\n hasStartedBlock = true;\n }\n const chunkContent = chunk.message.content;\n if (chunkContent.length > 0) {\n controller.push({\n type: 'content_block_delta',\n index: 0,\n delta: { type: 'text_delta', text: chunkContent },\n });\n }\n if (chunk.done) {\n controller.push({ type: 'content_block_stop', index: 0 });\n controller.push({\n type: 'message_delta',\n delta: { stop_reason: mapStopReason(chunk.done_reason) },\n usage: this.calcUsage(chunk),\n });\n controller.push({ type: 'message_stop' });\n }\n }\n controller.complete();\n } catch (error) {\n controller.error(this.transformError(error as Error));\n }\n }\n\n private extractSystemPrompt(request: CompletionRequest): string | undefined {\n if (request.systemPrompt !== undefined && request.systemPrompt !== '')\n return request.systemPrompt;\n const sys = request.messages.find((m) => m.role === 'system');\n if (sys === undefined) return undefined;\n if (typeof sys.content === 'string') return sys.content;\n return sys.content\n .filter((b): b is { type: 'text'; text: string } => b.type === 'text')\n .map((b) => b.text)\n .join('\\n');\n }\n\n private buildOptions(request: CompletionRequest): Record<string, unknown> {\n const options: Record<string, unknown> = {\n num_predict: request.maxTokens ?? DEFAULT_MAX_TOKENS,\n };\n if (request.temperature !== undefined) options['temperature'] = request.temperature;\n if (request.stop !== undefined && request.stop.length > 0) options['stop'] = request.stop;\n return options;\n }\n\n private applyFormatAndTools(params: OllamaChatRequest, request: CompletionRequest): void {\n if (request.tools !== undefined && request.tools.length > 0)\n params.tools = request.tools.map(mapTool);\n if (request.responseFormat?.type === 'json_object') params.format = 'json';\n else if (request.responseFormat?.type === 'json_schema')\n params.format = request.responseFormat.schema;\n }\n\n private buildRequestParams(request: CompletionRequest): OllamaChatRequest {\n const messages = request.messages.filter((m) => m.role !== 'system').map(mapMessage);\n const systemPrompt = this.extractSystemPrompt(request);\n if (systemPrompt !== undefined) messages.unshift({ role: 'system', content: systemPrompt });\n const params: OllamaChatRequest = {\n model: this.modelId,\n messages,\n options: this.buildOptions(request),\n };\n this.applyFormatAndTools(params, request);\n return params;\n }\n\n private mapResponse(response: OllamaChatResponse): CompletionResponse {\n return {\n content: mapOllamaMessageToContent(response.message),\n usage: this.calcUsage(response),\n stopReason: mapStopReason(response.done_reason),\n model: response.model,\n };\n }\n\n private calcUsage(response: OllamaChatResponse): TokenUsage {\n const input = response.prompt_eval_count;\n const output = response.eval_count;\n const inputCount = typeof input === 'number' ? input : 0;\n const outputCount = typeof output === 'number' ? output : 0;\n return {\n inputTokens: inputCount,\n outputTokens: outputCount,\n totalTokens: inputCount + outputCount,\n };\n }\n}\n\n/** Creates an OllamaAdapter with the specified configuration. */\nexport function createOllamaAdapter(config: OllamaAdapterConfig): OllamaAdapter {\n return new OllamaAdapter(config);\n}\n","/**\n * @nexus-agents/adapters - Gemini/Google AI Model Adapter\n *\n * Adapter for Google's Gemini models (gemini-2.5-flash, gemini-2.0-flash, gemini-1.5-pro).\n * Implements the IModelAdapter interface with streaming support, tool calling,\n * and proper error handling.\n *\n * Verified 2026-01-03: @google/genai@1.34.0 is current stable\n * (Source: npm registry - last modified 2025-12-17)\n */\n\nimport { GoogleGenAI } from '@google/genai';\nimport type { GenerateContentResponse, Content } from '@google/genai';\nimport type {\n Result,\n CompletionRequest,\n CompletionResponse,\n StreamChunk,\n ContentBlock,\n TokenUsage,\n} from '../core/index.js';\nimport { ok, err, ModelError, ConfigError } from '../core/index.js';\nimport { BaseAdapter, type BaseAdapterConfig } from './base-adapter.js';\nimport { createStream } from './streaming.js';\nimport {\n GEMINI_CHARS_PER_TOKEN,\n DEFAULT_MAX_TOKENS,\n mapStopReason,\n mapMessageToContent,\n mapToolToFunctionDeclaration,\n resolveModelId,\n getModelCapabilities,\n type GeminiAdapterConfig,\n type GeminiRequestConfig,\n type GeminiRequestParams,\n} from './gemini-types.js';\n\n// Re-export types and constants\nexport { GEMINI_MODELS, GEMINI_MODEL_ALIASES, type GeminiAdapterConfig } from './gemini-types.js';\n\n/**\n * Gemini/Google AI model adapter.\n *\n * Provides a unified interface for interacting with Google's Gemini models.\n * Supports completion, streaming, tool use, and vision capabilities.\n *\n * @example\n * ```typescript\n * const adapter = new GeminiAdapter({\n * modelId: 'gemini-2.5-flash',\n * apiKey: process.env.GOOGLE_API_KEY,\n * });\n *\n * const result = await adapter.complete({\n * messages: [{ role: 'user', content: 'Hello!' }],\n * maxTokens: 1024,\n * });\n *\n * if (result.ok) {\n * console.log(result.value.content);\n * }\n * ```\n */\nexport class GeminiAdapter extends BaseAdapter {\n private readonly client: GoogleGenAI;\n private readonly resolvedModelId: string;\n\n /**\n * Creates a new GeminiAdapter instance.\n *\n * @param config - Gemini adapter configuration\n * @throws {ConfigError} If API key is missing\n */\n constructor(config: GeminiAdapterConfig) {\n const resolvedModelId = resolveModelId(config.modelId);\n\n // Build baseConfig conditionally to satisfy exactOptionalPropertyTypes\n const baseConfig: BaseAdapterConfig = {\n providerId: 'google',\n modelId: resolvedModelId,\n capabilities: getModelCapabilities(config.modelId),\n apiKey: config.apiKey,\n };\n\n // Only set optional properties if defined\n if (config.timeout !== undefined) {\n baseConfig.timeout = config.timeout;\n }\n if (config.maxRetries !== undefined) {\n baseConfig.maxRetries = config.maxRetries;\n }\n\n super(baseConfig);\n\n this.resolvedModelId = resolvedModelId;\n\n // Validate API key presence\n if (!config.apiKey || config.apiKey.trim() === '') {\n throw new ConfigError('Google API key is required', {\n context: { providerId: 'google', modelId: config.modelId },\n });\n }\n\n // Create Google GenAI client\n this.client = new GoogleGenAI({ apiKey: config.apiKey });\n }\n\n /**\n * Validates adapter configuration.\n * Extends base validation with Gemini-specific checks.\n */\n override validateConfig(): Result<void, ConfigError> {\n const baseResult = super.validateConfig();\n if (!baseResult.ok) {\n return baseResult;\n }\n\n // Validate API key is present\n const apiKey = this.config.apiKey;\n if (apiKey === undefined || apiKey === '' || apiKey.trim() === '') {\n return err(\n new ConfigError('Google API key is required', {\n context: { providerId: this.providerId, modelId: this.modelId },\n })\n );\n }\n\n return ok(undefined);\n }\n\n /**\n * Send a completion request to Gemini.\n *\n * @param request - The completion request\n * @returns Result with response or ModelError\n */\n async complete(request: CompletionRequest): Promise<Result<CompletionResponse, ModelError>> {\n this.logRequest(request);\n\n try {\n const response = await this.executeCompletion(request);\n this.logResponse(response);\n return ok(response);\n } catch (error) {\n return err(this.transformError(error));\n }\n }\n\n /**\n * Stream a completion request from Gemini.\n *\n * @param request - The completion request\n * @yields StreamChunk objects as they arrive\n */\n async *stream(request: CompletionRequest): AsyncIterable<StreamChunk> {\n this.logRequest(request);\n\n const [controller, iterable] = createStream<StreamChunk>();\n\n // Start streaming in the background\n this.executeStream(request, controller).catch((error: unknown) => {\n const modelError = this.transformError(error);\n controller.error(modelError);\n });\n\n yield* iterable;\n }\n\n /**\n * Count tokens in text using Gemini-specific estimation.\n *\n * @param text - Text to count tokens for\n * @returns Approximate token count\n */\n override countTokens(text: string): Promise<number> {\n return Promise.resolve(Math.ceil(text.length / GEMINI_CHARS_PER_TOKEN));\n }\n\n /**\n * Executes the completion request against the Google AI API.\n */\n private async executeCompletion(request: CompletionRequest): Promise<CompletionResponse> {\n const params = this.buildRequestParams(request);\n const response = await this.client.models.generateContent(params);\n\n return this.mapResponse(response);\n }\n\n /** Stream controller type for executeStream. */\n private readonly streamControllerType = {} as {\n push: (chunk: StreamChunk) => Result<void, Error>;\n complete: () => void;\n error: (error: Error) => void;\n };\n\n /**\n * Emits the end-of-message events to the stream controller.\n */\n private emitStreamEnd(\n controller: typeof this.streamControllerType,\n hasStartedBlock: boolean,\n index: number\n ): void {\n if (hasStartedBlock) {\n controller.push({ type: 'content_block_stop', index });\n }\n controller.push({\n type: 'message_delta',\n delta: { stop_reason: 'end_turn' },\n usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },\n });\n controller.push({ type: 'message_stop' });\n controller.complete();\n }\n\n /**\n * Executes streaming completion and pushes chunks to the controller.\n */\n private async executeStream(\n request: CompletionRequest,\n controller: typeof this.streamControllerType\n ): Promise<void> {\n try {\n const params = this.buildRequestParams(request);\n const stream = await this.client.models.generateContentStream(params);\n\n controller.push({ type: 'message_start', message: { model: this.resolvedModelId } });\n\n const index = 0;\n let hasStartedBlock = false;\n\n for await (const chunk of stream) {\n const text = chunk.text;\n if (text !== undefined && text !== '') {\n if (!hasStartedBlock) {\n controller.push({\n type: 'content_block_start',\n index,\n contentBlock: { type: 'text', text: '' },\n });\n hasStartedBlock = true;\n }\n controller.push({\n type: 'content_block_delta',\n index,\n delta: { type: 'text_delta', text },\n });\n }\n }\n\n this.emitStreamEnd(controller, hasStartedBlock, index);\n } catch (error) {\n controller.error(this.transformError(error as Error));\n }\n }\n\n /**\n * Extracts system prompt from request.\n */\n private extractSystemPrompt(request: CompletionRequest): string | undefined {\n // Check explicit systemPrompt field first\n if (request.systemPrompt !== undefined && request.systemPrompt !== '') {\n return request.systemPrompt;\n }\n\n // Check for system message in messages array\n const systemMessage = request.messages.find((m) => m.role === 'system');\n if (systemMessage === undefined) {\n return undefined;\n }\n\n if (typeof systemMessage.content === 'string') {\n return systemMessage.content;\n }\n\n return systemMessage.content\n .filter((b): b is { type: 'text'; text: string } => b.type === 'text')\n .map((b) => b.text)\n .join('\\n');\n }\n\n /**\n * Builds Google AI API request parameters from our CompletionRequest.\n */\n private buildRequestParams(request: CompletionRequest): GeminiRequestParams {\n const contents = request.messages\n .map(mapMessageToContent)\n .filter((c): c is Content => c !== null);\n\n const params: GeminiRequestParams = { model: this.resolvedModelId, contents };\n const config: GeminiRequestConfig = {};\n\n // Add max tokens (default if not specified)\n config.maxOutputTokens = request.maxTokens ?? DEFAULT_MAX_TOKENS;\n\n // Add system instruction\n const systemPrompt = this.extractSystemPrompt(request);\n if (systemPrompt !== undefined) {\n config.systemInstruction = systemPrompt;\n }\n\n // Add temperature\n if (request.temperature !== undefined) {\n config.temperature = request.temperature;\n }\n\n // Add stop sequences\n if (request.stop !== undefined && request.stop.length > 0) {\n config.stopSequences = request.stop;\n }\n\n // Add tools\n if (request.tools !== undefined && request.tools.length > 0) {\n config.tools = [{ functionDeclarations: request.tools.map(mapToolToFunctionDeclaration) }];\n }\n\n // Only add config if we have properties\n if (Object.keys(config).length > 0) {\n params.config = config;\n }\n\n return params;\n }\n\n /**\n * Generates a unique tool ID.\n */\n private generateToolId(): string {\n return `tool_${String(Date.now())}_${Math.random().toString(36).slice(2, 9)}`;\n }\n\n /**\n * Extracts content blocks from the response.\n */\n private extractContentBlocks(response: GenerateContentResponse): ContentBlock[] {\n const content: ContentBlock[] = [];\n\n const text = response.text;\n if (text !== undefined && text !== '') {\n content.push({ type: 'text', text });\n }\n\n const functionCalls = response.functionCalls;\n if (functionCalls !== undefined) {\n for (const fc of functionCalls) {\n content.push({\n type: 'tool_use',\n id: this.generateToolId(),\n name: fc.name ?? '',\n input: fc.args ?? {},\n });\n }\n }\n\n return content;\n }\n\n /**\n * Maps Google AI API response to our CompletionResponse format.\n */\n private mapResponse(response: GenerateContentResponse): CompletionResponse {\n const content = this.extractContentBlocks(response);\n const candidate = response.candidates?.[0];\n const usageMetadata = response.usageMetadata;\n\n const usage: TokenUsage = {\n inputTokens: usageMetadata?.promptTokenCount ?? 0,\n outputTokens: usageMetadata?.candidatesTokenCount ?? 0,\n totalTokens: usageMetadata?.totalTokenCount ?? 0,\n };\n\n return {\n content,\n usage,\n stopReason: mapStopReason(candidate?.finishReason),\n model: this.resolvedModelId,\n };\n }\n}\n\n/**\n * Creates a GeminiAdapter with the specified configuration.\n * Factory function for cleaner API.\n *\n * @param config - Gemini adapter configuration\n * @returns A configured GeminiAdapter instance\n *\n * @example\n * ```typescript\n * const adapter = createGeminiAdapter({\n * modelId: 'gemini-2.5-flash',\n * apiKey: process.env.GOOGLE_API_KEY!,\n * });\n * ```\n */\nexport function createGeminiAdapter(config: GeminiAdapterConfig): GeminiAdapter {\n return new GeminiAdapter(config);\n}\n","/**\n * @nexus-agents/adapters - Gemini Type Utilities\n *\n * Type mappings and helper functions for the Gemini adapter.\n */\n\nimport type { Content, Part, FunctionDeclaration } from '@google/genai';\nimport type { ContentBlock, Message, ToolDefinition, StopReason } from '../core/index.js';\nimport { ModelCapability } from '../core/index.js';\n\n/**\n * Supported Gemini model identifiers.\n */\nexport const GEMINI_MODELS = {\n PRO_3: 'gemini-3-pro-preview',\n FLASH_3: 'gemini-3-flash',\n FLASH_2_5: 'gemini-2.5-flash',\n FLASH_2_0: 'gemini-2.0-flash',\n PRO_1_5: 'gemini-1.5-pro',\n FLASH_1_5: 'gemini-1.5-flash',\n} as const;\n\n/**\n * Model aliases for convenience.\n */\nexport const GEMINI_MODEL_ALIASES: Record<string, string> = {\n // Gemini 3 aliases\n 'gemini-3-pro-preview': GEMINI_MODELS.PRO_3,\n 'gemini-3-pro': GEMINI_MODELS.PRO_3,\n 'gemini-3-flash': GEMINI_MODELS.FLASH_3,\n // Gemini 2.x aliases\n 'gemini-2.5-flash': GEMINI_MODELS.FLASH_2_5,\n 'gemini-2.0-flash': GEMINI_MODELS.FLASH_2_0,\n // Gemini 1.5 aliases\n 'gemini-1.5-pro': GEMINI_MODELS.PRO_1_5,\n 'gemini-1.5-flash': GEMINI_MODELS.FLASH_1_5,\n // Short aliases (point to latest versions)\n 'gemini-flash': GEMINI_MODELS.FLASH_3,\n 'gemini-pro': GEMINI_MODELS.PRO_3,\n} as const;\n\n/**\n * Configuration specific to GeminiAdapter.\n */\nexport interface GeminiAdapterConfig {\n /** Model ID (e.g., 'gemini-2.5-flash' or full model identifier) */\n modelId: string;\n /** API key for Google AI API (required) */\n apiKey: string;\n /** Request timeout in milliseconds (optional) */\n timeout?: number;\n /** Maximum retries for failed requests (optional) */\n maxRetries?: number;\n}\n\n/**\n * Characters per token estimate for Gemini models.\n * Gemini uses a similar tokenizer to other modern LLMs.\n * ~4 chars/token is a reasonable estimate for English text.\n */\nexport const GEMINI_CHARS_PER_TOKEN = 4;\n\n/**\n * Default maximum tokens for Gemini models.\n */\nexport const DEFAULT_MAX_TOKENS = 8192;\n\n/**\n * Maps Gemini finish reasons to our StopReason type.\n */\nexport function mapStopReason(finishReason: string | undefined): StopReason {\n switch (finishReason) {\n case 'STOP':\n return 'end_turn';\n case 'MAX_TOKENS':\n return 'max_tokens';\n case 'STOP_SEQUENCE':\n return 'stop_sequence';\n case 'TOOL_CODE':\n case 'MALFORMED_FUNCTION_CALL':\n return 'tool_use';\n default:\n return 'end_turn';\n }\n}\n\n/**\n * Maps Gemini response parts to our ContentBlock type.\n */\nexport function mapPartToContentBlock(part: Part): ContentBlock | null {\n if (part.text !== undefined) {\n return { type: 'text', text: part.text };\n }\n if (part.functionCall !== undefined) {\n return {\n type: 'tool_use',\n id: `tool_${String(Date.now())}_${Math.random().toString(36).slice(2, 9)}`,\n name: part.functionCall.name ?? '',\n input: part.functionCall.args ?? {},\n };\n }\n return null;\n}\n\n/**\n * Maps our Message format to Gemini's Content format.\n */\nexport function mapMessageToContent(message: Message): Content | null {\n // Skip system messages - they are handled separately\n if (message.role === 'system') {\n return null;\n }\n\n const role = message.role === 'assistant' ? 'model' : 'user';\n const parts: Part[] = [];\n\n if (typeof message.content === 'string') {\n parts.push({ text: message.content });\n } else {\n for (const block of message.content) {\n if (block.type === 'text') {\n parts.push({ text: block.text });\n } else if (block.type === 'tool_use') {\n parts.push({\n functionCall: {\n name: block.name,\n args: block.input as Record<string, unknown>,\n },\n });\n } else if (block.type === 'tool_result') {\n parts.push({\n functionResponse: {\n name: block.tool_use_id,\n response: { result: block.content },\n },\n });\n } else {\n // block.type === 'image'\n parts.push({\n inlineData: {\n mimeType: block.source.media_type,\n data: block.source.data,\n },\n });\n }\n }\n }\n\n return { role, parts };\n}\n\n/**\n * Maps our ToolDefinition to Gemini's FunctionDeclaration format.\n * Uses parametersJsonSchema which accepts raw JSON Schema objects.\n */\nexport function mapToolToFunctionDeclaration(tool: ToolDefinition): FunctionDeclaration {\n return {\n name: tool.name,\n description: tool.description,\n parametersJsonSchema: {\n type: 'object',\n properties: tool.inputSchema.properties ?? {},\n required: tool.inputSchema.required ?? [],\n },\n };\n}\n\n/**\n * Resolves model alias to full model identifier.\n */\nexport function resolveModelId(modelId: string): string {\n return GEMINI_MODEL_ALIASES[modelId] ?? modelId;\n}\n\n/**\n * Configuration object for Gemini request.\n */\nexport interface GeminiRequestConfig {\n maxOutputTokens?: number;\n temperature?: number;\n stopSequences?: string[];\n systemInstruction?: string;\n tools?: Array<{ functionDeclarations: FunctionDeclaration[] }>;\n}\n\n/**\n * Parameters for Gemini generateContent request.\n */\nexport interface GeminiRequestParams {\n model: string;\n contents: Content[];\n config?: GeminiRequestConfig;\n}\n\n/**\n * Determines capabilities based on model ID.\n */\nexport function getModelCapabilities(modelId: string): readonly ModelCapability[] {\n const capabilities: ModelCapability[] = [\n ModelCapability.COMPLETION,\n ModelCapability.STREAMING,\n ModelCapability.TOOL_USE,\n ModelCapability.VISION,\n ];\n\n // Gemini 2.0+, 2.5+, and 3.x models support extended thinking\n const resolvedId = resolveModelId(modelId);\n if (resolvedId.includes('2.5') || resolvedId.includes('2.0') || resolvedId.includes('gemini-3')) {\n capabilities.push(ModelCapability.EXTENDED_THINKING);\n }\n\n return capabilities;\n}\n","/**\n * @nexus-agents/agents - Agent Validation Schemas\n *\n * Zod schemas for validating agent-related data structures.\n */\n\nimport { z } from 'zod';\n\n/**\n * Zod schema for validating Task objects.\n */\nexport const TaskSchema = z.object({\n id: z.string().min(1, 'Task ID is required'),\n description: z.string().min(1, 'Task description is required'),\n context: z.object({\n workingDirectory: z.string().optional(),\n files: z.array(z.string()).optional(),\n history: z\n .array(\n z.object({\n role: z.enum(['user', 'assistant', 'system']),\n content: z.string(),\n timestamp: z.string(),\n })\n )\n .optional(),\n metadata: z.record(z.unknown()).optional(),\n }),\n constraints: z\n .object({\n maxDuration: z.number().positive().optional(),\n maxTokens: z.number().positive().optional(),\n outputFormat: z.enum(['text', 'json', 'markdown']).optional(),\n allowedTools: z.array(z.string()).optional(),\n })\n .optional(),\n priority: z.number().optional(),\n});\n\n/**\n * Zod schema for validating AgentMessage objects.\n */\nexport const AgentMessageSchema = z.object({\n id: z.string().min(1, 'Message ID is required'),\n from: z.string().min(1, 'Sender ID is required'),\n to: z.string().min(1, 'Recipient ID is required'),\n type: z.enum(['task', 'result', 'query', 'feedback', 'status']),\n payload: z.unknown(),\n timestamp: z.string(),\n});\n\n/**\n * Zod schema for validating BaseAgentOptions.\n */\nexport const BaseAgentOptionsSchema = z.object({\n id: z.string().min(1, 'Agent ID is required'),\n role: z.enum([\n 'tech_lead',\n 'code_expert',\n 'architecture_expert',\n 'security_expert',\n 'documentation_expert',\n 'testing_expert',\n 'custom',\n ]),\n capabilities: z.array(\n z.enum([\n 'task_execution',\n 'delegation',\n 'collaboration',\n 'tool_use',\n 'code_generation',\n 'code_review',\n 'research',\n ])\n ),\n systemPrompt: z.string().optional(),\n temperature: z.number().min(0).max(1).optional(),\n maxTokens: z.number().positive().optional(),\n});\n","/**\n * @nexus-agents/agents - BaseAgent\n *\n * Abstract base class implementing the IAgent interface.\n * Provides common functionality for state management, logging,\n * error handling, and model adapter integration.\n */\n\nimport type {\n Result,\n IAgent,\n IModelAdapter,\n ILogger,\n Task,\n TaskResult,\n AgentMessage,\n AgentResponse,\n AgentContext,\n AgentConfig,\n AgentState,\n AgentRole,\n AgentCapability,\n CompletionRequest,\n CompletionResponse,\n Message,\n} from '../core/index.js';\nimport { ok, err, AgentError, createLogger } from '../core/index.js';\nimport { TaskSchema, AgentMessageSchema, BaseAgentOptionsSchema } from './agent-schemas.js';\n\n// Re-export schemas for convenience\nexport { TaskSchema, AgentMessageSchema, BaseAgentOptionsSchema } from './agent-schemas.js';\n\n/**\n * Options for creating a BaseAgent.\n */\nexport interface BaseAgentOptions {\n /** Unique agent identifier */\n id: string;\n /** Agent role */\n role: AgentRole;\n /** Agent capabilities */\n capabilities: readonly AgentCapability[];\n /** Model adapter for LLM interactions */\n adapter?: IModelAdapter;\n /** Custom logger instance */\n logger?: ILogger;\n /** System prompt for the agent */\n systemPrompt?: string;\n /** Default temperature for completions */\n temperature?: number;\n /** Maximum tokens for responses */\n maxTokens?: number;\n}\n\nconst DEFAULT_MAX_DURATION_MS = 5 * 60 * 1000; // 5 minutes\nconst MAX_HISTORY_ITEMS = 100;\n\n/** Abstract base class for all agents. Subclasses must implement executeTask and buildPrompt. */\nexport abstract class BaseAgent implements IAgent {\n readonly id: string;\n readonly role: AgentRole;\n readonly capabilities: readonly AgentCapability[];\n\n private _state: AgentState = 'idle';\n protected adapter: IModelAdapter | undefined;\n protected readonly logger: ILogger;\n protected config: AgentConfig | undefined;\n protected sharedState: Record<string, unknown> = {};\n protected history: Message[] = [];\n protected readonly systemPrompt: string | undefined;\n protected readonly temperature: number;\n protected readonly maxTokens: number;\n private initialized = false;\n\n constructor(options: BaseAgentOptions) {\n const validation = BaseAgentOptionsSchema.safeParse(options);\n if (!validation.success) {\n const issues = validation.error.issues\n .map((issue) => `${issue.path.join('.')}: ${issue.message}`)\n .join('; ');\n throw new AgentError(`Invalid agent options: ${issues}`, {\n context: { options, validationErrors: validation.error.issues },\n });\n }\n\n this.id = options.id;\n this.role = options.role;\n this.capabilities = options.capabilities;\n this.adapter = options.adapter;\n this.systemPrompt = options.systemPrompt;\n this.temperature = options.temperature ?? 0.3;\n this.maxTokens = options.maxTokens ?? 4096;\n this.logger = options.logger ?? createLogger({ agent: this.id, role: this.role });\n }\n\n get state(): AgentState {\n return this._state;\n }\n\n protected setState(newState: AgentState): void {\n const previousState = this._state;\n this._state = newState;\n this.logger.debug('State transition', { from: previousState, to: newState });\n }\n\n initialize(ctx: AgentContext): Promise<Result<void, AgentError>> {\n if (this.initialized) {\n return Promise.resolve(\n err(new AgentError('Agent already initialized', { context: { agentId: this.id } }))\n );\n }\n\n this.logger.info('Initializing agent', {\n modelId: ctx.config.modelId,\n hasTools: ctx.tools !== undefined && ctx.tools.length > 0,\n });\n\n this.config = ctx.config;\n this.sharedState = ctx.sharedState ?? {};\n this.initialized = true;\n\n return Promise.resolve(ok(undefined));\n }\n\n async execute(task: Task): Promise<Result<TaskResult, AgentError>> {\n const validationResult = this.validateTask(task);\n if (!validationResult.ok) {\n return validationResult;\n }\n\n if (this._state !== 'idle') {\n return err(\n new AgentError(`Agent is not idle (current state: ${this._state})`, {\n context: { agentId: this.id, currentState: this._state, taskId: task.id },\n })\n );\n }\n\n const startTime = Date.now();\n this.setState('thinking');\n\n this.logger.info('Executing task', {\n taskId: task.id,\n priority: task.priority,\n hasConstraints: task.constraints !== undefined,\n });\n\n try {\n const maxDuration = task.constraints?.maxDuration ?? DEFAULT_MAX_DURATION_MS;\n const result = await this.executeWithTimeout(task, maxDuration);\n\n if (!result.ok) {\n this.setState('error');\n return result;\n }\n\n const durationMs = Date.now() - startTime;\n this.setState('idle');\n\n this.logger.info('Task completed', {\n taskId: task.id,\n durationMs,\n tokensUsed: result.value.metadata.tokensUsed,\n });\n\n return result;\n } catch (error) {\n this.setState('error');\n return err(this.transformError(error, task.id));\n }\n }\n\n async handleMessage(msg: AgentMessage): Promise<Result<AgentResponse, AgentError>> {\n const validation = AgentMessageSchema.safeParse(msg);\n if (!validation.success) {\n const issues = validation.error.issues\n .map((issue) => `${issue.path.join('.')}: ${issue.message}`)\n .join('; ');\n return err(\n new AgentError(`Invalid message: ${issues}`, {\n context: { messageId: msg.id, validationErrors: validation.error.issues },\n })\n );\n }\n\n this.logger.debug('Handling message', { messageId: msg.id, from: msg.from, type: msg.type });\n\n switch (msg.type) {\n case 'task':\n return this.handleTaskMessage(msg);\n case 'query':\n return this.handleQueryMessage(msg);\n case 'feedback':\n return this.handleFeedbackMessage(msg);\n case 'status':\n return this.handleStatusMessage(msg);\n case 'result':\n return this.handleResultMessage(msg);\n default:\n return err(\n new AgentError(`Unknown message type: ${String(msg.type)}`, {\n context: { messageId: msg.id, type: msg.type },\n })\n );\n }\n }\n\n cleanup(): Promise<void> {\n this.logger.info('Cleaning up agent');\n this.history = [];\n this.sharedState = {};\n this.initialized = false;\n this.setState('idle');\n return Promise.resolve();\n }\n\n hasCapability(capability: AgentCapability): boolean {\n return this.capabilities.includes(capability);\n }\n\n protected abstract executeTask(task: Task): Promise<Result<TaskResult, AgentError>>;\n protected abstract buildPrompt(task: Task): Message[];\n\n private async executeWithTimeout(\n task: Task,\n maxDurationMs: number\n ): Promise<Result<TaskResult, AgentError>> {\n return new Promise((resolve) => {\n const timeoutId = setTimeout(() => {\n resolve(\n err(\n new AgentError(`Task execution timed out after ${String(maxDurationMs)}ms`, {\n context: { taskId: task.id, maxDurationMs },\n })\n )\n );\n }, maxDurationMs);\n\n this.executeTask(task)\n .then((result) => {\n clearTimeout(timeoutId);\n resolve(result);\n })\n .catch((error: unknown) => {\n clearTimeout(timeoutId);\n resolve(err(this.transformError(error, task.id)));\n });\n });\n }\n\n private validateTask(task: Task): Result<Task, AgentError> {\n const result = TaskSchema.safeParse(task);\n if (!result.success) {\n const issues = result.error.issues\n .map((issue) => `${issue.path.join('.')}: ${issue.message}`)\n .join('; ');\n return err(\n new AgentError(`Invalid task: ${issues}`, {\n context: { taskId: task.id, validationErrors: result.error.issues },\n })\n );\n }\n return ok(result.data as Task);\n }\n\n protected transformError(error: unknown, taskId: string): AgentError {\n if (error instanceof AgentError) {\n return error;\n }\n\n const message = error instanceof Error ? error.message : String(error);\n const cause = error instanceof Error ? error : undefined;\n\n const options: { context: Record<string, unknown>; cause?: Error } = {\n context: { agentId: this.id, taskId },\n };\n if (cause !== undefined) {\n options.cause = cause;\n }\n return new AgentError(`Task execution failed: ${message}`, options);\n }\n\n protected async complete(\n request: CompletionRequest\n ): Promise<Result<CompletionResponse, AgentError>> {\n if (this.adapter === undefined) {\n return err(new AgentError('No model adapter configured', { context: { agentId: this.id } }));\n }\n\n this.setState('acting');\n\n const result = await this.adapter.complete(request);\n if (!result.ok) {\n return err(\n new AgentError(`Model completion failed: ${result.error.message}`, {\n context: { agentId: this.id },\n cause: result.error,\n })\n );\n }\n\n this.setState('thinking');\n return ok(result.value);\n }\n\n protected addToHistory(message: Message): void {\n this.history.push(message);\n if (this.history.length > MAX_HISTORY_ITEMS) {\n this.history = this.history.slice(-MAX_HISTORY_ITEMS);\n }\n }\n\n protected getHistory(): Message[] {\n return [...this.history];\n }\n\n protected clearHistory(): void {\n this.history = [];\n }\n\n private async handleTaskMessage(msg: AgentMessage): Promise<Result<AgentResponse, AgentError>> {\n const taskPayload = msg.payload as Partial<Task>;\n if (taskPayload.id === undefined || taskPayload.description === undefined) {\n return ok({\n messageId: msg.id,\n status: 'rejected',\n error: 'Invalid task payload: missing id or description',\n });\n }\n\n const task: Task = {\n id: taskPayload.id,\n description: taskPayload.description,\n context: taskPayload.context ?? {},\n };\n if (taskPayload.constraints !== undefined) {\n task.constraints = taskPayload.constraints;\n }\n if (taskPayload.priority !== undefined) {\n task.priority = taskPayload.priority;\n }\n\n const result = await this.execute(task);\n if (!result.ok) {\n return ok({ messageId: msg.id, status: 'failed', error: result.error.message });\n }\n\n return ok({ messageId: msg.id, status: 'completed', data: result.value });\n }\n\n private handleQueryMessage(msg: AgentMessage): Promise<Result<AgentResponse, AgentError>> {\n return Promise.resolve(\n ok({\n messageId: msg.id,\n status: 'completed',\n data: {\n agentId: this.id,\n role: this.role,\n state: this._state,\n capabilities: this.capabilities,\n },\n })\n );\n }\n\n private handleFeedbackMessage(msg: AgentMessage): Promise<Result<AgentResponse, AgentError>> {\n this.logger.info('Received feedback', { from: msg.from, payload: msg.payload });\n return Promise.resolve(ok({ messageId: msg.id, status: 'accepted' }));\n }\n\n private handleStatusMessage(msg: AgentMessage): Promise<Result<AgentResponse, AgentError>> {\n return Promise.resolve(\n ok({\n messageId: msg.id,\n status: 'completed',\n data: {\n agentId: this.id,\n state: this._state,\n initialized: this.initialized,\n historyLength: this.history.length,\n },\n })\n );\n }\n\n private handleResultMessage(msg: AgentMessage): Promise<Result<AgentResponse, AgentError>> {\n this.logger.debug('Received result', { from: msg.from });\n return Promise.resolve(ok({ messageId: msg.id, status: 'accepted' }));\n }\n}\n","/**\n * @nexus-agents/agents - SimpleAgent\n *\n * A simple concrete agent implementation for testing and basic use cases.\n */\n\nimport type { Result, Task, TaskResult, CompletionRequest, Message } from '../core/index.js';\nimport { ok, err, AgentError } from '../core/index.js';\nimport { BaseAgent } from './base-agent.js';\n\n/**\n * Simple concrete agent implementation for testing and basic use cases.\n *\n * This agent processes tasks by sending them directly to the model adapter\n * and returning the response.\n */\nexport class SimpleAgent extends BaseAgent {\n /**\n * Execute a task by sending it to the model.\n */\n protected async executeTask(task: Task): Promise<Result<TaskResult, AgentError>> {\n const startTime = Date.now();\n const messages = this.buildPrompt(task);\n\n // Build request, only including defined optional properties\n const request: CompletionRequest = {\n messages,\n temperature: this.temperature,\n maxTokens: task.constraints?.maxTokens ?? this.maxTokens,\n };\n if (this.systemPrompt !== undefined) {\n request.systemPrompt = this.systemPrompt;\n }\n\n const result = await this.complete(request);\n if (!result.ok) {\n return err(result.error);\n }\n\n const durationMs = Date.now() - startTime;\n\n // Extract text content from response\n const textContent = result.value.content\n .filter((block): block is { type: 'text'; text: string } => block.type === 'text')\n .map((block) => block.text)\n .join('\\n');\n\n return ok({\n taskId: task.id,\n output: textContent,\n metadata: {\n durationMs,\n tokensUsed: result.value.usage.totalTokens,\n toolsUsed: [],\n model: result.value.model,\n },\n });\n }\n\n /**\n * Build prompt messages from a task.\n */\n protected buildPrompt(task: Task): Message[] {\n const messages: Message[] = [];\n\n // Add history from task context\n if (task.context.history !== undefined) {\n for (const item of task.context.history) {\n if (item.role === 'user' || item.role === 'assistant') {\n messages.push({\n role: item.role,\n content: item.content,\n });\n }\n }\n }\n\n // Add the task description as the user message\n messages.push({\n role: 'user',\n content: task.description,\n });\n\n return messages;\n }\n}\n","/**\n * @nexus-agents/agents - TechLead Types and Schemas\n *\n * Type definitions and Zod schemas for TechLead agent functionality.\n * Includes subtask, expert selection, and synthesis types.\n */\n\nimport { z } from 'zod';\nimport type { AgentRole } from '../core/index.js';\n\n/**\n * Subtask priority levels.\n */\nexport type SubtaskPriority = 'critical' | 'high' | 'medium' | 'low';\n\n/**\n * Subtask status.\n */\nexport type SubtaskStatus = 'pending' | 'assigned' | 'in_progress' | 'completed' | 'failed';\n\n/**\n * A subtask broken down from the main task.\n */\nexport interface SubTask {\n /** Unique subtask identifier */\n id: string;\n /** Parent task ID */\n parentTaskId: string;\n /** Description of what needs to be done */\n description: string;\n /** Expected output format or type */\n expectedOutput: string;\n /** Dependencies on other subtasks (by ID) */\n dependencies: string[];\n /** Priority level */\n priority: SubtaskPriority;\n /** Current status */\n status: SubtaskStatus;\n /** Assigned expert role (if any) */\n assignedRole?: AgentRole;\n /** Estimated complexity (1-10) */\n complexity: number;\n /** Required capabilities for this subtask */\n requiredCapabilities: string[];\n}\n\n/**\n * Result of task analysis.\n */\nexport interface TaskAnalysis {\n /** Task ID being analyzed */\n taskId: string;\n /** Overall complexity score (1-10) */\n complexity: number;\n /** Type of task (code, architecture, documentation, etc.) */\n taskType: string;\n /** Key requirements extracted from the task */\n requirements: string[];\n /** Identified risks or challenges */\n risks: string[];\n /** Whether task needs decomposition */\n needsDecomposition: boolean;\n /** Recommended approach */\n approach: string;\n /** Estimated total effort in relative units */\n estimatedEffort: number;\n}\n\n/**\n * Expert assignment for a subtask.\n */\nexport interface ExpertAssignment {\n /** Subtask ID */\n subtaskId: string;\n /** Assigned expert role */\n expertRole: AgentRole;\n /** Reason for selection */\n selectionReason: string;\n /** Confidence in the assignment (0-1) */\n confidence: number;\n}\n\n/**\n * Synthesis of multiple task results.\n */\nexport interface SynthesizedResult {\n /** Combined output from all results */\n combinedOutput: string;\n /** Summary of the synthesis process */\n summary: string;\n /** Individual result summaries */\n resultSummaries: ResultSummary[];\n /** Any conflicts detected between results */\n conflicts: Conflict[];\n /** Overall quality assessment */\n qualityScore: number;\n /** Recommendations for follow-up */\n recommendations: string[];\n}\n\n/**\n * Summary of a single result.\n */\nexport interface ResultSummary {\n /** Subtask ID */\n subtaskId: string;\n /** Brief summary of the output */\n summary: string;\n /** Quality of this result (0-1) */\n quality: number;\n /** Key contributions to final output */\n contributions: string[];\n}\n\n/**\n * Conflict between results.\n */\nexport interface Conflict {\n /** First subtask ID */\n subtaskId1: string;\n /** Second subtask ID */\n subtaskId2: string;\n /** Description of the conflict */\n description: string;\n /** How the conflict was resolved */\n resolution: string;\n}\n\n/**\n * Options for TechLead agent.\n */\nexport interface TechLeadOptions {\n /** Maximum number of subtasks to create */\n maxSubtasks?: number;\n /** Minimum complexity to trigger decomposition */\n decompositionThreshold?: number;\n /** Enable parallel execution hints */\n enableParallelHints?: boolean;\n /** Custom expert selection weights */\n expertWeights?: Partial<Record<AgentRole, number>>;\n}\n\n/**\n * Zod schema for SubtaskPriority.\n */\nexport const SubtaskPrioritySchema = z.enum(['critical', 'high', 'medium', 'low']);\n\n/**\n * Zod schema for SubtaskStatus.\n */\nexport const SubtaskStatusSchema = z.enum([\n 'pending',\n 'assigned',\n 'in_progress',\n 'completed',\n 'failed',\n]);\n\n/**\n * Zod schema for SubTask.\n */\nexport const SubTaskSchema = z.object({\n id: z.string().min(1, 'Subtask ID is required'),\n parentTaskId: z.string().min(1, 'Parent task ID is required'),\n description: z.string().min(1, 'Description is required'),\n expectedOutput: z.string().min(1, 'Expected output is required'),\n dependencies: z.array(z.string()),\n priority: SubtaskPrioritySchema,\n status: SubtaskStatusSchema,\n assignedRole: z\n .enum([\n 'tech_lead',\n 'code_expert',\n 'architecture_expert',\n 'security_expert',\n 'documentation_expert',\n 'testing_expert',\n 'custom',\n ])\n .optional(),\n complexity: z.number().min(1).max(10),\n requiredCapabilities: z.array(z.string()),\n});\n\n/**\n * Zod schema for TaskAnalysis.\n */\nexport const TaskAnalysisSchema = z.object({\n taskId: z.string().min(1),\n complexity: z.number().min(1).max(10),\n taskType: z.string().min(1),\n requirements: z.array(z.string()),\n risks: z.array(z.string()),\n needsDecomposition: z.boolean(),\n approach: z.string().min(1),\n estimatedEffort: z.number().min(0),\n});\n\n/**\n * Zod schema for ExpertAssignment.\n */\nexport const ExpertAssignmentSchema = z.object({\n subtaskId: z.string().min(1),\n expertRole: z.enum([\n 'tech_lead',\n 'code_expert',\n 'architecture_expert',\n 'security_expert',\n 'documentation_expert',\n 'testing_expert',\n 'custom',\n ]),\n selectionReason: z.string().min(1),\n confidence: z.number().min(0).max(1),\n});\n\n/**\n * Zod schema for ResultSummary.\n */\nexport const ResultSummarySchema = z.object({\n subtaskId: z.string().min(1),\n summary: z.string().min(1),\n quality: z.number().min(0).max(1),\n contributions: z.array(z.string()),\n});\n\n/**\n * Zod schema for Conflict.\n */\nexport const ConflictSchema = z.object({\n subtaskId1: z.string().min(1),\n subtaskId2: z.string().min(1),\n description: z.string().min(1),\n resolution: z.string().min(1),\n});\n\n/**\n * Zod schema for SynthesizedResult.\n */\nexport const SynthesizedResultSchema = z.object({\n combinedOutput: z.string(),\n summary: z.string().min(1),\n resultSummaries: z.array(ResultSummarySchema),\n conflicts: z.array(ConflictSchema),\n qualityScore: z.number().min(0).max(1),\n recommendations: z.array(z.string()),\n});\n\n/**\n * Zod schema for TechLeadOptions.\n */\nexport const TechLeadOptionsSchema = z.object({\n maxSubtasks: z.number().min(1).max(20).optional(),\n decompositionThreshold: z.number().min(1).max(10).optional(),\n enableParallelHints: z.boolean().optional(),\n expertWeights: z.record(z.number().min(0).max(10)).optional(),\n});\n\n/**\n * Expert role capabilities mapping.\n * Maps each expert role to their core capabilities.\n */\nexport const EXPERT_CAPABILITIES: Readonly<Record<AgentRole, readonly string[]>> = {\n tech_lead: ['task_execution', 'delegation', 'collaboration', 'research'],\n code_expert: ['task_execution', 'code_generation', 'code_review', 'tool_use'],\n architecture_expert: ['task_execution', 'research', 'collaboration'],\n security_expert: ['task_execution', 'code_review', 'research'],\n documentation_expert: ['task_execution', 'research'],\n testing_expert: ['task_execution', 'code_generation', 'tool_use'],\n custom: ['task_execution'],\n};\n\n/**\n * Task type to expert role mapping.\n * Maps common task types to their primary expert roles.\n */\nexport const TASK_TYPE_EXPERTS: Readonly<Record<string, AgentRole>> = {\n implementation: 'code_expert',\n refactoring: 'code_expert',\n code_review: 'code_expert',\n architecture: 'architecture_expert',\n design: 'architecture_expert',\n security_audit: 'security_expert',\n vulnerability: 'security_expert',\n documentation: 'documentation_expert',\n api_docs: 'documentation_expert',\n testing: 'testing_expert',\n test_coverage: 'testing_expert',\n general: 'code_expert',\n};\n","/**\n * @nexus-agents/agents - TechLead Task Decomposition Helpers\n *\n * Helper functions for decomposing tasks into subtasks based on task type.\n */\n\nimport type { Task } from '../core/index.js';\nimport type { SubTask, TaskAnalysis } from './tech-lead-types.js';\nimport { createSubtask } from './tech-lead-helpers.js';\n\n/**\n * Create subtasks for implementation task type.\n */\nfunction createImplementationSubtasks(baseId: string, parentTaskId: string): SubTask[] {\n return [\n createSubtask({\n baseId,\n num: 1,\n parentTaskId,\n description: 'Design the implementation approach',\n expectedOutput: 'Design document',\n deps: [],\n priority: 'high',\n complexity: 4,\n capabilities: ['research'],\n }),\n createSubtask({\n baseId,\n num: 2,\n parentTaskId,\n description: 'Implement core functionality',\n expectedOutput: 'Working code',\n deps: ['1'],\n priority: 'critical',\n complexity: 6,\n capabilities: ['code_generation'],\n }),\n createSubtask({\n baseId,\n num: 3,\n parentTaskId,\n description: 'Write unit tests',\n expectedOutput: 'Test suite',\n deps: ['2'],\n priority: 'high',\n complexity: 4,\n capabilities: ['code_generation'],\n }),\n ];\n}\n\n/**\n * Create subtasks for architecture task type.\n */\nfunction createArchitectureSubtasks(baseId: string, parentTaskId: string): SubTask[] {\n return [\n createSubtask({\n baseId,\n num: 1,\n parentTaskId,\n description: 'Analyze current architecture',\n expectedOutput: 'Architecture analysis',\n deps: [],\n priority: 'high',\n complexity: 5,\n capabilities: ['research'],\n }),\n createSubtask({\n baseId,\n num: 2,\n parentTaskId,\n description: 'Design new architecture',\n expectedOutput: 'Architecture proposal',\n deps: ['1'],\n priority: 'critical',\n complexity: 7,\n capabilities: ['research'],\n }),\n createSubtask({\n baseId,\n num: 3,\n parentTaskId,\n description: 'Document architecture decisions',\n expectedOutput: 'ADR document',\n deps: ['2'],\n priority: 'medium',\n complexity: 3,\n capabilities: ['research'],\n }),\n ];\n}\n\n/**\n * Create subtasks for security audit task type.\n */\nfunction createSecurityAuditSubtasks(baseId: string, parentTaskId: string): SubTask[] {\n return [\n createSubtask({\n baseId,\n num: 1,\n parentTaskId,\n description: 'Review code for vulnerabilities',\n expectedOutput: 'Security findings',\n deps: [],\n priority: 'critical',\n complexity: 6,\n capabilities: ['code_review'],\n }),\n createSubtask({\n baseId,\n num: 2,\n parentTaskId,\n description: 'Check dependency security',\n expectedOutput: 'Dependency report',\n deps: [],\n priority: 'high',\n complexity: 4,\n capabilities: ['research'],\n }),\n createSubtask({\n baseId,\n num: 3,\n parentTaskId,\n description: 'Document security recommendations',\n expectedOutput: 'Security report',\n deps: ['1', '2'],\n priority: 'high',\n complexity: 4,\n capabilities: ['research'],\n }),\n ];\n}\n\n/**\n * Create subtasks for generic task type.\n */\nfunction createGenericSubtasks(\n baseId: string,\n parentTaskId: string,\n complexity: number\n): SubTask[] {\n return [\n createSubtask({\n baseId,\n num: 1,\n parentTaskId,\n description: 'Analyze requirements',\n expectedOutput: 'Requirements document',\n deps: [],\n priority: 'high',\n complexity: 3,\n capabilities: ['research'],\n }),\n createSubtask({\n baseId,\n num: 2,\n parentTaskId,\n description: 'Execute main task',\n expectedOutput: 'Primary deliverable',\n deps: ['1'],\n priority: 'critical',\n complexity,\n capabilities: ['task_execution'],\n }),\n createSubtask({\n baseId,\n num: 3,\n parentTaskId,\n description: 'Review and validate',\n expectedOutput: 'Validation report',\n deps: ['2'],\n priority: 'medium',\n complexity: 3,\n capabilities: ['code_review'],\n }),\n ];\n}\n\n/**\n * Perform heuristic task decomposition without model adapter.\n */\nexport function heuristicDecomposition(\n task: Task,\n analysis: TaskAnalysis,\n maxSubtasks: number\n): SubTask[] {\n const baseId = `${task.id}-sub`;\n let subtasks: SubTask[];\n\n switch (analysis.taskType) {\n case 'implementation':\n subtasks = createImplementationSubtasks(baseId, task.id);\n break;\n case 'architecture':\n subtasks = createArchitectureSubtasks(baseId, task.id);\n break;\n case 'security_audit':\n subtasks = createSecurityAuditSubtasks(baseId, task.id);\n break;\n default:\n subtasks = createGenericSubtasks(baseId, task.id, analysis.complexity);\n }\n\n return subtasks.slice(0, maxSubtasks);\n}\n","/**\n * @nexus-agents/agents - TechLead Expert Selection Helpers\n *\n * Helper functions for selecting and scoring experts for subtask assignment.\n */\n\nimport type { AgentRole } from '../core/index.js';\nimport type { SubTask, ExpertAssignment } from './tech-lead-types.js';\nimport { EXPERT_CAPABILITIES } from './tech-lead-types.js';\n\n/**\n * Build selection reason for expert assignment.\n */\nexport function buildSelectionReason(role: AgentRole, subtask: SubTask): string {\n const capabilities = EXPERT_CAPABILITIES[role];\n const matched = subtask.requiredCapabilities.filter((c) => capabilities.includes(c));\n\n if (matched.length > 0) {\n return `Matches capabilities: ${matched.join(', ')}`;\n }\n\n return `Best available for task type`;\n}\n\n/**\n * Score a single expert role for capability match.\n */\nfunction scoreRoleCapabilities(\n subtask: SubTask,\n role: AgentRole,\n expertWeights: Partial<Record<AgentRole, number>>\n): number {\n const capabilities = EXPERT_CAPABILITIES[role];\n let score = 0;\n\n for (const required of subtask.requiredCapabilities) {\n if (capabilities.includes(required)) {\n score += 2;\n }\n }\n\n const weight = expertWeights[role] ?? 1;\n return score * weight;\n}\n\n/**\n * Apply keyword-based score boosts.\n */\nfunction applyKeywordBoosts(scores: Record<AgentRole, number>, description: string): void {\n const desc = description.toLowerCase();\n const boosts: Array<{ keywords: string[]; role: AgentRole }> = [\n { keywords: ['code', 'implement'], role: 'code_expert' },\n { keywords: ['architecture', 'design'], role: 'architecture_expert' },\n { keywords: ['security', 'vulnerab'], role: 'security_expert' },\n { keywords: ['document', 'readme'], role: 'documentation_expert' },\n { keywords: ['test', 'coverage'], role: 'testing_expert' },\n ];\n\n for (const { keywords, role } of boosts) {\n if (keywords.some((kw) => desc.includes(kw))) {\n scores[role] += 3;\n }\n }\n}\n\n/**\n * Score all expert roles for a subtask.\n */\nfunction scoreExperts(\n subtask: SubTask,\n expertWeights: Partial<Record<AgentRole, number>>\n): Record<AgentRole, number> {\n const roles: AgentRole[] = [\n 'tech_lead',\n 'code_expert',\n 'architecture_expert',\n 'security_expert',\n 'documentation_expert',\n 'testing_expert',\n 'custom',\n ];\n\n const scores: Record<AgentRole, number> = {} as Record<AgentRole, number>;\n for (const role of roles) {\n scores[role] = scoreRoleCapabilities(subtask, role, expertWeights);\n }\n\n applyKeywordBoosts(scores, subtask.description);\n\n return scores;\n}\n\n/**\n * Find the best expert from scores.\n */\nfunction findBestExpert(scores: Record<AgentRole, number>): {\n bestRole: AgentRole;\n bestScore: number;\n} {\n let bestRole: AgentRole = 'code_expert';\n let bestScore = 0;\n\n for (const [role, score] of Object.entries(scores)) {\n if (score > bestScore) {\n bestScore = score;\n bestRole = role as AgentRole;\n }\n }\n\n return { bestRole, bestScore };\n}\n\n/**\n * Select an expert for a single subtask.\n */\nexport function selectExpertForSubtask(\n subtask: SubTask,\n expertWeights: Partial<Record<AgentRole, number>>\n): ExpertAssignment {\n // If already assigned, use that role\n if (subtask.assignedRole !== undefined) {\n return {\n subtaskId: subtask.id,\n expertRole: subtask.assignedRole,\n selectionReason: 'Pre-assigned role',\n confidence: 1.0,\n };\n }\n\n const scores = scoreExperts(subtask, expertWeights);\n const { bestRole, bestScore } = findBestExpert(scores);\n const maxPossibleScore = subtask.requiredCapabilities.length * 2 + 3;\n const confidence = maxPossibleScore > 0 ? Math.min(1, bestScore / maxPossibleScore) : 0.5;\n\n return {\n subtaskId: subtask.id,\n expertRole: bestRole,\n selectionReason: buildSelectionReason(bestRole, subtask),\n confidence,\n };\n}\n","/**\n * @nexus-agents/agents - TechLead Helper Functions\n *\n * Helper functions for TechLead task analysis, decomposition, and synthesis.\n */\n\nimport type { Task, TaskResult } from '../core/index.js';\nimport type {\n SubTask,\n TaskAnalysis,\n SynthesizedResult,\n ResultSummary,\n TechLeadOptions,\n} from './tech-lead-types.js';\n\n/**\n * Infer task type from description keywords.\n */\nexport function inferTaskType(description: string): string {\n const typeKeywords: Record<string, string[]> = {\n implementation: ['implement', 'create', 'build', 'develop', 'write code'],\n refactoring: ['refactor', 'improve', 'optimize', 'clean up'],\n architecture: ['architect', 'design system', 'structure', 'pattern'],\n security_audit: ['security', 'vulnerability', 'audit', 'penetration'],\n documentation: ['document', 'readme', 'api doc', 'explain'],\n testing: ['test', 'coverage', 'unit test', 'integration'],\n code_review: ['review', 'check code', 'analyze code'],\n };\n\n for (const [taskType, keywords] of Object.entries(typeKeywords)) {\n for (const keyword of keywords) {\n if (description.includes(keyword)) {\n return taskType;\n }\n }\n }\n\n return 'general';\n}\n\n/**\n * Extract requirements from task description.\n */\nexport function extractRequirements(description: string): string[] {\n const requirements: string[] = [];\n const lines = description.split(/[.\\n]/);\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (\n trimmed.length > 10 &&\n (trimmed.includes('must') ||\n trimmed.includes('should') ||\n trimmed.includes('need') ||\n trimmed.includes('require'))\n ) {\n requirements.push(trimmed);\n }\n }\n\n return requirements.slice(0, 5);\n}\n\n/**\n * Identify risks based on task description keywords.\n */\nexport function identifyRisks(description: string): string[] {\n const risks: string[] = [];\n\n if (description.includes('database') || description.includes('migration')) {\n risks.push('Data integrity during changes');\n }\n if (description.includes('security')) {\n risks.push('Security vulnerabilities if not thorough');\n }\n if (description.includes('performance')) {\n risks.push('Performance regression');\n }\n if (description.includes('api') || description.includes('interface')) {\n risks.push('Breaking API changes');\n }\n if (description.includes('concurrent') || description.includes('parallel')) {\n risks.push('Race conditions');\n }\n\n return risks;\n}\n\n/**\n * Suggest approach based on task type and complexity.\n */\nexport function suggestApproach(taskType: string, complexity: number): string {\n if (complexity >= 7) {\n return `High complexity ${taskType} task. Recommend iterative approach with frequent reviews.`;\n }\n if (complexity >= 4) {\n return `Medium complexity ${taskType} task. Standard development process with testing.`;\n }\n return `Low complexity ${taskType} task. Direct implementation with basic validation.`;\n}\n\n/**\n * Create a subtask with the given parameters.\n */\nexport interface CreateSubtaskParams {\n baseId: string;\n num: number;\n parentTaskId: string;\n description: string;\n expectedOutput: string;\n deps: string[];\n priority: 'critical' | 'high' | 'medium' | 'low';\n complexity: number;\n capabilities: string[];\n}\n\nexport function createSubtask(params: CreateSubtaskParams): SubTask {\n const {\n baseId,\n num,\n parentTaskId,\n description,\n expectedOutput,\n deps,\n priority,\n complexity,\n capabilities,\n } = params;\n return {\n id: `${baseId}-${String(num)}`,\n parentTaskId,\n description,\n expectedOutput,\n dependencies: deps.map((d) => `${baseId}-${d}`),\n priority,\n status: 'pending',\n complexity,\n requiredCapabilities: capabilities,\n };\n}\n\n/**\n * Perform heuristic task analysis without model adapter.\n */\nexport function heuristicAnalysis(task: Task, options: Required<TechLeadOptions>): TaskAnalysis {\n const description = task.description.toLowerCase();\n const wordCount = task.description.split(/\\s+/).length;\n\n // Estimate complexity based on task characteristics\n let complexity = 3;\n if (wordCount > 100) complexity += 2;\n if (wordCount > 200) complexity += 2;\n if (description.includes('security')) complexity += 1;\n if (description.includes('architecture')) complexity += 1;\n if (description.includes('refactor')) complexity += 1;\n complexity = Math.min(10, complexity);\n\n const taskType = inferTaskType(description);\n const requirements = extractRequirements(description);\n\n return {\n taskId: task.id,\n complexity,\n taskType,\n requirements,\n risks: identifyRisks(description),\n needsDecomposition: complexity >= options.decompositionThreshold,\n approach: suggestApproach(taskType, complexity),\n estimatedEffort: Math.ceil(complexity * 1.5),\n };\n}\n\n// Re-export heuristicDecomposition from the dedicated decomposition module\nexport { heuristicDecomposition } from './tech-lead-decomposition.js';\n\n// Re-export expert selection functions from the dedicated module\nexport { buildSelectionReason, selectExpertForSubtask } from './tech-lead-expert-selection.js';\n\n/**\n * Perform heuristic result synthesis without model adapter.\n */\nexport function heuristicSynthesis(results: TaskResult[]): SynthesizedResult {\n const summaries: ResultSummary[] = results.map((r) => ({\n subtaskId: r.taskId,\n summary: typeof r.output === 'string' ? r.output.slice(0, 200) : 'Completed',\n quality: 0.8,\n contributions: ['Task output'],\n }));\n\n const outputs = results.map((r) =>\n typeof r.output === 'string' ? r.output : JSON.stringify(r.output)\n );\n\n return {\n combinedOutput: outputs.join('\\n\\n---\\n\\n'),\n summary: `Synthesized ${String(results.length)} results`,\n resultSummaries: summaries,\n conflicts: [],\n qualityScore: 0.8,\n recommendations: ['Review combined output for consistency'],\n };\n}\n\n/**\n * Create synthesis for a single result.\n */\nexport function createSingleResultSynthesis(result: TaskResult): SynthesizedResult {\n const output = typeof result.output === 'string' ? result.output : JSON.stringify(result.output);\n\n return {\n combinedOutput: output,\n summary: 'Single result synthesis',\n resultSummaries: [\n {\n subtaskId: result.taskId,\n summary: output.slice(0, 200),\n quality: 0.9,\n contributions: ['Complete task output'],\n },\n ],\n conflicts: [],\n qualityScore: 0.9,\n recommendations: [],\n };\n}\n\n/**\n * Identify parallel execution groups from subtasks.\n */\nexport function identifyParallelGroups(subtasks: SubTask[]): string[][] {\n const groups: string[][] = [];\n const assigned = new Set<string>();\n\n while (assigned.size < subtasks.length) {\n const group: string[] = [];\n\n for (const subtask of subtasks) {\n if (assigned.has(subtask.id)) continue;\n\n const depsResolved = subtask.dependencies.every((d) => assigned.has(d));\n if (depsResolved) {\n group.push(subtask.id);\n }\n }\n\n if (group.length === 0) break; // Prevent infinite loop on circular deps\n\n for (const id of group) {\n assigned.add(id);\n }\n groups.push(group);\n }\n\n return groups;\n}\n\n/**\n * Estimate duration from subtasks.\n */\nexport function estimateDuration(subtasks: SubTask[]): number {\n if (subtasks.length === 0) return 0;\n\n // Sum complexity for sequential estimate\n const totalComplexity = subtasks.reduce((sum, st) => sum + st.complexity, 0);\n return totalComplexity * 60 * 1000; // Convert to ms (1 complexity unit = 1 minute)\n}\n\n/**\n * Extract text content from model response.\n */\nexport function extractTextContent(content: Array<{ type: string; text?: string }>): string {\n return content\n .filter((block): block is { type: 'text'; text: string } => block.type === 'text')\n .map((block) => block.text)\n .join('\\n');\n}\n","/**\n * @nexus-agents/agents - TechLead Agent\n *\n * The TechLead agent is responsible for:\n * - Analyzing incoming tasks for complexity and requirements\n * - Breaking down complex tasks into subtasks\n * - Selecting appropriate expert agents for subtasks\n * - Synthesizing results from multiple experts\n *\n * (Source: Nexus Agents CLAUDE.md, Agent Architecture)\n */\n\nimport type {\n Result,\n Task,\n TaskResult,\n AgentCapability,\n CompletionRequest,\n Message,\n} from '../core/index.js';\nimport { ok, err, AgentError } from '../core/index.js';\nimport { BaseAgent, type BaseAgentOptions } from './base-agent.js';\nimport type {\n SubTask,\n TaskAnalysis,\n ExpertAssignment,\n SynthesizedResult,\n TechLeadOptions,\n} from './tech-lead-types.js';\nimport { TaskAnalysisSchema, SubTaskSchema, SynthesizedResultSchema } from './tech-lead-types.js';\nimport {\n heuristicAnalysis,\n heuristicDecomposition,\n heuristicSynthesis,\n createSingleResultSynthesis,\n selectExpertForSubtask,\n identifyParallelGroups,\n estimateDuration,\n extractTextContent,\n} from './tech-lead-helpers.js';\n\n/** Default TechLead options. */\nconst DEFAULT_OPTIONS: Required<TechLeadOptions> = {\n maxSubtasks: 10,\n decompositionThreshold: 5,\n enableParallelHints: true,\n expertWeights: {},\n};\n\n/** System prompt for task analysis. */\nconst ANALYSIS_PROMPT = `You are a technical lead analyzing a software development task.\nAnalyze the task and provide a structured JSON assessment with: taskId, complexity (1-10),\ntaskType, requirements[], risks[], needsDecomposition, approach, estimatedEffort.`;\n\n/** System prompt for task decomposition. */\nconst DECOMPOSITION_PROMPT = `You are a technical lead breaking down a complex task.\nCreate subtasks as JSON array with: id, parentTaskId, description, expectedOutput,\ndependencies[], priority (critical/high/medium/low), status: \"pending\", complexity (1-10),\nrequiredCapabilities[].`;\n\n/** System prompt for result synthesis. */\nconst SYNTHESIS_PROMPT = `You are a technical lead synthesizing results from multiple experts.\nRespond with JSON: combinedOutput, summary, resultSummaries[], conflicts[], qualityScore (0-1),\nrecommendations[].`;\n\n/**\n * Execution plan output structure.\n */\nexport interface ExecutionPlan {\n taskId: string;\n analysis: TaskAnalysis;\n subtasks: SubTask[];\n assignments: ExpertAssignment[];\n parallelGroups: string[][];\n estimatedDuration: number;\n}\n\n/**\n * TechLead Agent - orchestrates task execution by analyzing, decomposing,\n * delegating, and synthesizing results from expert agents.\n */\nexport class TechLead extends BaseAgent {\n private readonly techLeadOptions: Required<TechLeadOptions>;\n\n constructor(options: Partial<BaseAgentOptions> & { techLeadOptions?: TechLeadOptions } = {}) {\n const baseOptions: BaseAgentOptions = {\n id: options.id ?? 'tech-lead',\n role: 'tech_lead',\n capabilities: options.capabilities ?? [\n 'task_execution' as AgentCapability,\n 'delegation' as AgentCapability,\n 'collaboration' as AgentCapability,\n 'research' as AgentCapability,\n ],\n temperature: options.temperature ?? 0.3,\n maxTokens: options.maxTokens ?? 4096,\n };\n\n // Only add optional properties if defined (for exactOptionalPropertyTypes)\n if (options.adapter !== undefined) baseOptions.adapter = options.adapter;\n if (options.logger !== undefined) baseOptions.logger = options.logger;\n if (options.systemPrompt !== undefined) baseOptions.systemPrompt = options.systemPrompt;\n\n super(baseOptions);\n\n this.techLeadOptions = { ...DEFAULT_OPTIONS, ...options.techLeadOptions };\n }\n\n /** Execute a task by analyzing, decomposing (if needed), and coordinating. */\n protected async executeTask(task: Task): Promise<Result<TaskResult, AgentError>> {\n const startTime = Date.now();\n\n const analysisResult = await this.analyzeTask(task);\n if (!analysisResult.ok) return err(analysisResult.error);\n const analysis = analysisResult.value;\n\n this.logger.info('Task analyzed', {\n taskId: task.id,\n complexity: analysis.complexity,\n needsDecomposition: analysis.needsDecomposition,\n });\n\n let subtasks: SubTask[] = [];\n if (analysis.needsDecomposition) {\n const decomposeResult = await this.decomposeTask(task, analysis);\n if (!decomposeResult.ok) return err(decomposeResult.error);\n subtasks = decomposeResult.value;\n }\n\n const assignments = this.selectExperts(subtasks);\n const output = this.buildExecutionPlan(task, analysis, subtasks, assignments);\n\n return ok({\n taskId: task.id,\n output,\n metadata: {\n durationMs: Date.now() - startTime,\n tokensUsed: 0,\n toolsUsed: [],\n model: 'tech-lead-orchestration',\n },\n });\n }\n\n /** Build prompt messages for task execution. */\n protected buildPrompt(task: Task): Message[] {\n return [{ role: 'user', content: `Analyze and plan execution for:\\n\\n${task.description}` }];\n }\n\n /** Analyze a task to understand its complexity and requirements. */\n async analyzeTask(task: Task): Promise<Result<TaskAnalysis, AgentError>> {\n if (this.adapter === undefined) {\n return ok(heuristicAnalysis(task, this.techLeadOptions));\n }\n\n const request: CompletionRequest = {\n messages: [{ role: 'user', content: `Task ID: ${task.id}\\n\\n${task.description}` }],\n systemPrompt: ANALYSIS_PROMPT,\n temperature: 0.2,\n maxTokens: 2048,\n };\n\n const result = await this.complete(request);\n if (!result.ok) return err(result.error);\n\n const parseResult = this.parseJson<TaskAnalysis>(\n extractTextContent(result.value.content),\n TaskAnalysisSchema\n );\n\n if (!parseResult.ok) {\n this.logger.warn('Failed to parse analysis response, using heuristic', {\n error: parseResult.error.message,\n });\n return ok(heuristicAnalysis(task, this.techLeadOptions));\n }\n\n return ok(parseResult.value);\n }\n\n /** Decompose a task into subtasks. */\n async decomposeTask(task: Task, analysis: TaskAnalysis): Promise<Result<SubTask[], AgentError>> {\n if (this.adapter === undefined) {\n return ok(heuristicDecomposition(task, analysis, this.techLeadOptions.maxSubtasks));\n }\n\n const request: CompletionRequest = {\n messages: [\n {\n role: 'user',\n content: `Task: ${task.description}\\nAnalysis: ${JSON.stringify(analysis)}\\nMax: ${String(this.techLeadOptions.maxSubtasks)}`,\n },\n ],\n systemPrompt: DECOMPOSITION_PROMPT,\n temperature: 0.3,\n maxTokens: 4096,\n };\n\n const result = await this.complete(request);\n if (!result.ok) return err(result.error);\n\n try {\n const parsed = JSON.parse(extractTextContent(result.value.content)) as unknown[];\n const subtasks = parsed\n .map((item) => SubTaskSchema.safeParse(item))\n .filter((r) => r.success)\n .map((r) => r.data as SubTask);\n\n return ok(\n subtasks.length > 0\n ? subtasks.slice(0, this.techLeadOptions.maxSubtasks)\n : heuristicDecomposition(task, analysis, this.techLeadOptions.maxSubtasks)\n );\n } catch {\n this.logger.warn('Failed to parse decomposition response, using heuristic');\n return ok(heuristicDecomposition(task, analysis, this.techLeadOptions.maxSubtasks));\n }\n }\n\n /** Select appropriate expert agents for each subtask. */\n selectExperts(subtasks: SubTask[]): ExpertAssignment[] {\n return subtasks.map((st) => selectExpertForSubtask(st, this.techLeadOptions.expertWeights));\n }\n\n /** Synthesize results from multiple experts into a cohesive output. */\n async synthesizeResults(results: TaskResult[]): Promise<Result<SynthesizedResult, AgentError>> {\n if (results.length === 0) {\n return ok({\n combinedOutput: '',\n summary: 'No results to synthesize',\n resultSummaries: [],\n conflicts: [],\n qualityScore: 0,\n recommendations: ['Ensure subtasks complete before synthesis'],\n });\n }\n\n if (results.length === 1) {\n const r = results[0];\n if (r === undefined) return err(new AgentError('Invalid result in array'));\n return ok(createSingleResultSynthesis(r));\n }\n\n if (this.adapter === undefined) return ok(heuristicSynthesis(results));\n\n const request: CompletionRequest = {\n messages: [{ role: 'user', content: `Synthesize:\\n${JSON.stringify(results, null, 2)}` }],\n systemPrompt: SYNTHESIS_PROMPT,\n temperature: 0.2,\n maxTokens: 4096,\n };\n\n const result = await this.complete(request);\n if (!result.ok) return err(result.error);\n\n const parseResult = this.parseJson<SynthesizedResult>(\n extractTextContent(result.value.content),\n SynthesizedResultSchema\n );\n\n return parseResult.ok ? ok(parseResult.value) : ok(heuristicSynthesis(results));\n }\n\n /** Get the TechLead options. */\n getOptions(): Readonly<Required<TechLeadOptions>> {\n return { ...this.techLeadOptions };\n }\n\n private buildExecutionPlan(\n task: Task,\n analysis: TaskAnalysis,\n subtasks: SubTask[],\n assignments: ExpertAssignment[]\n ): ExecutionPlan {\n return {\n taskId: task.id,\n analysis,\n subtasks,\n assignments,\n parallelGroups: this.techLeadOptions.enableParallelHints\n ? identifyParallelGroups(subtasks)\n : [],\n estimatedDuration: estimateDuration(subtasks),\n };\n }\n\n private parseJson<T>(\n text: string,\n schema: {\n safeParse: (d: unknown) => { success: boolean; data?: T; error?: { message: string } };\n }\n ): Result<T, AgentError> {\n try {\n let jsonText = text;\n const match = text.match(/```(?:json)?\\s*([\\s\\S]*?)```/);\n if (match?.[1] !== undefined) jsonText = match[1];\n\n const parsed = JSON.parse(jsonText) as unknown;\n const validation = schema.safeParse(parsed);\n\n if (!validation.success) {\n return err(new AgentError(`Invalid schema: ${validation.error?.message ?? 'Unknown'}`));\n }\n return ok(validation.data as T);\n } catch (error) {\n return err(\n new AgentError(\n `JSON parse failed: ${error instanceof Error ? error.message : String(error)}`\n )\n );\n }\n }\n}\n\n/** Creates a new TechLead agent with the given options. */\nexport function createTechLead(\n options?: Partial<BaseAgentOptions> & { techLeadOptions?: TechLeadOptions }\n): TechLead {\n return new TechLead(options);\n}\n","/**\n * @nexus-agents/agents - Agent State Machine\n *\n * Manages agent state transitions with validation, events, and error recovery.\n *\n * States:\n * - idle: Agent is ready for tasks\n * - thinking: Agent is analyzing/planning\n * - acting: Agent is performing work\n * - waiting: Agent is waiting for input/response\n * - error: Agent encountered an error\n *\n * (Source: Nexus Agents CLAUDE.md, Agent State Machine Design)\n */\n\nimport type { AgentState } from '../core/index.js';\nimport { type Result, ok, err, AgentError } from '../core/index.js';\n\n/**\n * State transition event types.\n */\nexport type StateTransitionEvent =\n | 'task_assigned'\n | 'plan_completed'\n | 'needs_input'\n | 'task_completed'\n | 'failure'\n | 'input_received'\n | 'recovered';\n\n/**\n * State transition metadata.\n */\nexport interface StateTransition {\n /** Previous state */\n from: AgentState;\n /** New state */\n to: AgentState;\n /** Event that triggered the transition */\n event: StateTransitionEvent;\n /** Timestamp of the transition */\n timestamp: string;\n /** Optional context data */\n context?: Record<string, unknown>;\n}\n\n/**\n * Callback for state change events.\n */\nexport type StateChangeCallback = (transition: StateTransition) => void;\n\n/**\n * Error callback for invalid transitions.\n */\nexport type TransitionErrorCallback = (\n currentState: AgentState,\n attemptedEvent: StateTransitionEvent,\n error: AgentError\n) => void;\n\n/**\n * State machine options.\n */\nexport interface StateMachineOptions {\n /** Initial state (defaults to 'idle') */\n initialState?: AgentState;\n /** Maximum error count before permanent error state */\n maxErrorCount?: number;\n /** Enable transition history tracking */\n trackHistory?: boolean;\n /** Maximum history entries to keep */\n maxHistorySize?: number;\n}\n\n/**\n * Valid state transitions map.\n * Maps (currentState, event) -> nextState\n */\nconst VALID_TRANSITIONS: ReadonlyMap<\n AgentState,\n ReadonlyMap<StateTransitionEvent, AgentState>\n> = new Map([\n ['idle', new Map<StateTransitionEvent, AgentState>([['task_assigned', 'thinking']])],\n [\n 'thinking',\n new Map<StateTransitionEvent, AgentState>([\n ['plan_completed', 'acting'],\n ['needs_input', 'waiting'],\n ['failure', 'error'],\n ]),\n ],\n [\n 'acting',\n new Map<StateTransitionEvent, AgentState>([\n ['task_completed', 'idle'],\n ['failure', 'error'],\n ['needs_input', 'waiting'],\n ]),\n ],\n [\n 'waiting',\n new Map<StateTransitionEvent, AgentState>([\n ['input_received', 'thinking'],\n ['failure', 'error'],\n ]),\n ],\n ['error', new Map<StateTransitionEvent, AgentState>([['recovered', 'idle']])],\n]);\n\n/**\n * Agent State Machine.\n *\n * Manages agent lifecycle states with validation, event callbacks,\n * and error recovery mechanisms.\n */\nexport class AgentStateMachine {\n private currentState: AgentState;\n private readonly stateChangeCallbacks: Set<StateChangeCallback> = new Set();\n private readonly errorCallbacks: Set<TransitionErrorCallback> = new Set();\n private readonly history: StateTransition[] = [];\n private errorCount = 0;\n\n private readonly maxErrorCount: number;\n private readonly trackHistory: boolean;\n private readonly maxHistorySize: number;\n\n constructor(options: StateMachineOptions = {}) {\n this.currentState = options.initialState ?? 'idle';\n this.maxErrorCount = options.maxErrorCount ?? 3;\n this.trackHistory = options.trackHistory ?? true;\n this.maxHistorySize = options.maxHistorySize ?? 100;\n }\n\n /**\n * Gets the current state.\n */\n get state(): AgentState {\n return this.currentState;\n }\n\n /**\n * Gets the transition history.\n */\n get transitionHistory(): readonly StateTransition[] {\n return this.history;\n }\n\n /**\n * Gets the current error count.\n */\n get errors(): number {\n return this.errorCount;\n }\n\n /**\n * Checks if a transition is valid from the current state.\n */\n canTransition(event: StateTransitionEvent): boolean {\n const stateTransitions = VALID_TRANSITIONS.get(this.currentState);\n return stateTransitions?.has(event) ?? false;\n }\n\n /**\n * Gets the next state for an event, if valid.\n */\n getNextState(event: StateTransitionEvent): AgentState | undefined {\n const stateTransitions = VALID_TRANSITIONS.get(this.currentState);\n return stateTransitions?.get(event);\n }\n\n /**\n * Gets all valid events from the current state.\n */\n getValidEvents(): StateTransitionEvent[] {\n const stateTransitions = VALID_TRANSITIONS.get(this.currentState);\n return stateTransitions ? Array.from(stateTransitions.keys()) : [];\n }\n\n /**\n * Attempts a state transition.\n *\n * @param event - The event triggering the transition\n * @param context - Optional context data for the transition\n * @returns Result with the new state or an AgentError\n */\n transition(\n event: StateTransitionEvent,\n context?: Record<string, unknown>\n ): Result<AgentState, AgentError> {\n const nextState = this.getNextState(event);\n\n if (nextState === undefined) {\n const error = new AgentError(\n `Invalid transition: cannot apply event '${event}' in state '${this.currentState}'`,\n {\n context: {\n currentState: this.currentState,\n event,\n validEvents: this.getValidEvents(),\n },\n }\n );\n\n this.notifyErrorCallbacks(this.currentState, event, error);\n return err(error);\n }\n\n const transition = this.createTransition(nextState, event, context);\n this.applyTransition(transition);\n\n return ok(this.currentState);\n }\n\n /**\n * Forces a transition to the error state.\n * Use for unrecoverable errors that should bypass normal transition rules.\n *\n * @param context - Optional context data about the error\n */\n forceError(context?: Record<string, unknown>): void {\n if (this.currentState === 'error') {\n return;\n }\n\n const transition = this.createTransition('error', 'failure', context);\n this.applyTransition(transition);\n }\n\n /**\n * Attempts recovery from the error state.\n *\n * @param context - Optional context data about the recovery\n * @returns Result with the new state or an AgentError if recovery failed\n */\n recover(context?: Record<string, unknown>): Result<AgentState, AgentError> {\n if (this.currentState !== 'error') {\n return err(\n new AgentError(\n `Cannot recover: agent is not in error state (current: ${this.currentState})`,\n {\n context: { currentState: this.currentState },\n }\n )\n );\n }\n\n if (this.errorCount >= this.maxErrorCount) {\n return err(\n new AgentError(\n `Recovery failed: maximum error count (${String(this.maxErrorCount)}) exceeded`,\n {\n context: { errorCount: this.errorCount, maxErrorCount: this.maxErrorCount },\n }\n )\n );\n }\n\n return this.transition('recovered', context);\n }\n\n /**\n * Resets the error count. Call after successful task completion.\n */\n resetErrorCount(): void {\n this.errorCount = 0;\n }\n\n /**\n * Resets the state machine to its initial state.\n *\n * @param clearHistory - Whether to clear the transition history\n */\n reset(clearHistory = false): void {\n this.currentState = 'idle';\n this.errorCount = 0;\n if (clearHistory) {\n this.history.length = 0;\n }\n }\n\n /**\n * Subscribes to state change events.\n *\n * @param callback - Callback to invoke on state changes\n * @returns Unsubscribe function\n */\n onStateChange(callback: StateChangeCallback): () => void {\n this.stateChangeCallbacks.add(callback);\n return () => {\n this.stateChangeCallbacks.delete(callback);\n };\n }\n\n /**\n * Subscribes to transition error events.\n *\n * @param callback - Callback to invoke on transition errors\n * @returns Unsubscribe function\n */\n onTransitionError(callback: TransitionErrorCallback): () => void {\n this.errorCallbacks.add(callback);\n return () => {\n this.errorCallbacks.delete(callback);\n };\n }\n\n /**\n * Checks if the agent is in a state where it can accept new tasks.\n */\n isAvailable(): boolean {\n return this.currentState === 'idle';\n }\n\n /**\n * Checks if the agent is currently working.\n */\n isWorking(): boolean {\n return this.currentState === 'thinking' || this.currentState === 'acting';\n }\n\n /**\n * Checks if the agent is in an error state.\n */\n hasError(): boolean {\n return this.currentState === 'error';\n }\n\n private createTransition(\n to: AgentState,\n event: StateTransitionEvent,\n context?: Record<string, unknown>\n ): StateTransition {\n const transition: StateTransition = {\n from: this.currentState,\n to,\n event,\n timestamp: new Date().toISOString(),\n };\n if (context !== undefined) {\n transition.context = context;\n }\n return transition;\n }\n\n private applyTransition(transition: StateTransition): void {\n const previousState = this.currentState;\n this.currentState = transition.to;\n\n // Track error count\n if (transition.to === 'error') {\n this.errorCount++;\n }\n\n // Record history\n if (this.trackHistory) {\n this.history.push(transition);\n this.pruneHistory();\n }\n\n // Notify callbacks\n this.notifyStateChangeCallbacks(transition);\n\n // Reset error count on successful task completion\n if (previousState === 'acting' && transition.to === 'idle') {\n this.resetErrorCount();\n }\n }\n\n private pruneHistory(): void {\n if (this.history.length > this.maxHistorySize) {\n const excess = this.history.length - this.maxHistorySize;\n this.history.splice(0, excess);\n }\n }\n\n private notifyStateChangeCallbacks(transition: StateTransition): void {\n for (const callback of this.stateChangeCallbacks) {\n try {\n callback(transition);\n } catch {\n // Silently ignore callback errors to prevent cascading failures\n }\n }\n }\n\n private notifyErrorCallbacks(\n currentState: AgentState,\n event: StateTransitionEvent,\n error: AgentError\n ): void {\n for (const callback of this.errorCallbacks) {\n try {\n callback(currentState, event, error);\n } catch {\n // Silently ignore callback errors\n }\n }\n }\n}\n\n/**\n * Creates a new agent state machine.\n *\n * @param options - State machine options\n * @returns A new AgentStateMachine instance\n */\nexport function createStateMachine(options?: StateMachineOptions): AgentStateMachine {\n return new AgentStateMachine(options);\n}\n","/**\n * @nexus-agents/agents - ContextManager\n *\n * Manages context window for agents, enforcing token budgets\n * and content priority levels. Integrates with model adapters\n * for accurate token counting.\n */\n\nimport { z } from 'zod';\nimport type { Result, Message, IModelAdapter, ILogger } from '../core/index.js';\nimport { ok, err, ValidationError, createLogger } from '../core/index.js';\n\n/**\n * Priority levels for context content.\n * Higher priority content is retained longer during pruning.\n */\nexport const ContentPriority = {\n /** System instructions - highest priority, never pruned */\n SYSTEM: 100,\n /** Current task description and requirements */\n TASK: 80,\n /** Active working content (recent code, research) */\n ACTIVE: 60,\n /** Historical context (older messages, results) */\n HISTORY: 40,\n /** Ephemeral content (debug logs, temp data) */\n EPHEMERAL: 20,\n} as const;\n\nexport type ContentPriority = (typeof ContentPriority)[keyof typeof ContentPriority];\n\n/**\n * Budget allocation for context categories.\n * Based on PROJECT_PLAN.md recommendations.\n */\nexport interface ContextBudget {\n /** System instructions and project context (default: 15%) */\n system: number;\n /** Current task description and requirements (default: 20%) */\n task: number;\n /** Active working content (default: 50%) */\n active: number;\n /** Reserved for response generation (default: 15%) */\n reserved: number;\n}\n\n/**\n * Default budget allocation percentages.\n */\nexport const DEFAULT_BUDGET: ContextBudget = {\n system: 0.15,\n task: 0.2,\n active: 0.5,\n reserved: 0.15,\n};\n\n/**\n * Zod schema for ContextBudget validation.\n */\nexport const ContextBudgetSchema = z\n .object({\n system: z.number().min(0).max(1),\n task: z.number().min(0).max(1),\n active: z.number().min(0).max(1),\n reserved: z.number().min(0).max(1),\n })\n .refine((data) => data.system + data.task + data.active + data.reserved <= 1.0, {\n message: 'Budget allocations must not exceed 100%',\n });\n\n/**\n * A piece of content in the context with its metadata.\n */\nexport interface ContextItem {\n /** Unique identifier for this item */\n id: string;\n /** The content (message, text, etc.) */\n content: string;\n /** Priority level for retention */\n priority: ContentPriority;\n /** Budget category this item belongs to */\n category: keyof Omit<ContextBudget, 'reserved'>;\n /** Token count for this item */\n tokenCount: number;\n /** When this item was added */\n addedAt: number;\n /** Optional metadata */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Configuration for ContextManager.\n */\nexport interface ContextManagerConfig {\n /** Maximum context window size in tokens */\n maxTokens: number;\n /** Budget allocation (defaults to DEFAULT_BUDGET) */\n budget?: ContextBudget;\n /** Model adapter for token counting */\n adapter?: IModelAdapter;\n /** Custom logger */\n logger?: ILogger;\n /** Warning threshold (0-1) - warn when this % of budget is used */\n warningThreshold?: number;\n}\n\n/**\n * Schema for ContextManagerConfig validation.\n */\nexport const ContextManagerConfigSchema = z.object({\n maxTokens: z.number().positive(),\n budget: ContextBudgetSchema.optional(),\n warningThreshold: z.number().min(0).max(1).optional(),\n});\n\n/**\n * Statistics about context usage.\n */\nexport interface ContextStats {\n /** Total tokens currently used */\n totalTokens: number;\n /** Tokens used per category */\n categoryTokens: Record<keyof Omit<ContextBudget, 'reserved'>, number>;\n /** Number of items per category */\n itemCounts: Record<keyof Omit<ContextBudget, 'reserved'>, number>;\n /** Available tokens (total - reserved) */\n availableTokens: number;\n /** Whether any category is over budget */\n isOverBudget: boolean;\n /** Categories that are over budget */\n overBudgetCategories: Array<keyof Omit<ContextBudget, 'reserved'>>;\n /** Percentage of total capacity used */\n usagePercentage: number;\n}\n\n/**\n * Average characters per token for estimation fallback.\n * (Source: OpenAI documentation suggests ~4 chars per token for English)\n */\nconst CHARS_PER_TOKEN = 4;\n\n/**\n * Manages context window for agents with token budget enforcement.\n *\n * @example\n * ```typescript\n * const manager = new ContextManager({\n * maxTokens: 128000,\n * adapter: claudeAdapter,\n * });\n *\n * // Add content with priority\n * await manager.add({\n * id: 'system-prompt',\n * content: systemPrompt,\n * priority: ContentPriority.SYSTEM,\n * category: 'system',\n * });\n *\n * // Check if we can add more\n * const canAdd = await manager.canAdd(newContent, 'active');\n * ```\n */\n/**\n * Type alias for context item categories (excludes 'reserved').\n */\ntype ContextItemCategory = keyof Omit<ContextBudget, 'reserved'>;\n\nexport class ContextManager {\n private readonly maxTokens: number;\n private readonly budget: ContextBudget;\n private readonly adapter: IModelAdapter | undefined;\n private readonly logger: ILogger;\n private readonly warningThreshold: number;\n private readonly items: Map<string, ContextItem> = new Map();\n private cachedStats: ContextStats | null = null;\n\n /**\n * Running totals for token counts by category.\n * Updated incrementally on add/remove operations for O(1) lookups.\n */\n private categoryTokenCounts: Map<ContextItemCategory, number> = new Map([\n ['system', 0],\n ['task', 0],\n ['active', 0],\n ]);\n\n /**\n * Running total token count across all categories.\n * Updated incrementally on add/remove operations for O(1) lookups.\n */\n private totalTokenCount: number = 0;\n\n constructor(config: ContextManagerConfig) {\n const validation = ContextManagerConfigSchema.safeParse(config);\n if (!validation.success) {\n const issues = validation.error.issues\n .map((issue) => `${issue.path.join('.')}: ${issue.message}`)\n .join('; ');\n throw new ValidationError(`Invalid ContextManager config: ${issues}`, {\n context: { config, validationErrors: validation.error.issues },\n });\n }\n\n this.maxTokens = config.maxTokens;\n this.budget = config.budget ?? DEFAULT_BUDGET;\n this.adapter = config.adapter;\n this.warningThreshold = config.warningThreshold ?? 0.8;\n this.logger = config.logger ?? createLogger({ component: 'ContextManager' });\n }\n\n /**\n * Add an item to the context.\n *\n * @param item - The item to add (without tokenCount, will be calculated)\n * @returns Result with the added item or error\n */\n async add(\n item: Omit<ContextItem, 'tokenCount' | 'addedAt'>\n ): Promise<Result<ContextItem, ValidationError>> {\n const tokenCount = await this.countTokens(item.content);\n\n const fullItem: ContextItem = {\n ...item,\n tokenCount,\n addedAt: Date.now(),\n };\n\n // Validate budget constraints\n const budgetError = this.validateBudgetConstraints(item.category, tokenCount);\n if (budgetError !== null) {\n return err(budgetError);\n }\n\n // Add or replace the item\n this.storeItem(item.id, fullItem);\n this.checkWarningThreshold();\n\n return ok(fullItem);\n }\n\n /**\n * Validate that adding tokens would not exceed budget constraints.\n */\n private validateBudgetConstraints(\n category: keyof Omit<ContextBudget, 'reserved'>,\n tokenCount: number\n ): ValidationError | null {\n const categoryError = this.checkCategoryBudget(category, tokenCount);\n if (categoryError !== null) {\n return categoryError;\n }\n\n return this.checkTotalBudget(tokenCount);\n }\n\n /**\n * Check if adding tokens would exceed category budget.\n */\n private checkCategoryBudget(\n category: keyof Omit<ContextBudget, 'reserved'>,\n tokenCount: number\n ): ValidationError | null {\n const categoryBudget = this.getCategoryBudget(category);\n const currentCategoryTokens = this.getCategoryTokenCount(category);\n const newTotal = currentCategoryTokens + tokenCount;\n\n if (newTotal > categoryBudget) {\n this.logger.warn('Item would exceed category budget', {\n category,\n itemTokens: tokenCount,\n currentTokens: currentCategoryTokens,\n budget: categoryBudget,\n });\n return new ValidationError(\n `Adding item would exceed ${category} budget: ${String(newTotal)} > ${String(categoryBudget)}`,\n { context: { category, tokenCount, categoryBudget } }\n );\n }\n return null;\n }\n\n /**\n * Check if adding tokens would exceed total budget.\n */\n private checkTotalBudget(tokenCount: number): ValidationError | null {\n const usableTokens = this.maxTokens * (1 - this.budget.reserved);\n const currentTotal = this.getTotalTokenCount();\n const newTotal = currentTotal + tokenCount;\n\n if (newTotal > usableTokens) {\n this.logger.warn('Item would exceed total budget', {\n itemTokens: tokenCount,\n currentTotal,\n usableTokens,\n });\n return new ValidationError(\n `Adding item would exceed total context budget: ${String(newTotal)} > ${String(usableTokens)}`,\n { context: { tokenCount, currentTotal, usableTokens } }\n );\n }\n return null;\n }\n\n /**\n * Store an item and log the operation.\n * Updates running token count totals.\n */\n private storeItem(id: string, fullItem: ContextItem): void {\n const existing = this.items.get(id);\n\n // Update running totals\n if (existing !== undefined) {\n // Remove old item's token count from totals\n this.subtractFromTotals(existing.category, existing.tokenCount);\n }\n // Add new item's token count to totals\n this.addToTotals(fullItem.category, fullItem.tokenCount);\n\n this.items.set(id, fullItem);\n this.invalidateCache();\n\n if (existing !== undefined) {\n this.logger.debug('Replaced existing item', { id });\n } else {\n this.logger.debug('Added new item', {\n id,\n category: fullItem.category,\n tokenCount: fullItem.tokenCount,\n });\n }\n }\n\n /**\n * Remove an item from the context.\n *\n * @param id - The item ID to remove\n * @returns True if item was removed, false if not found\n */\n remove(id: string): boolean {\n const item = this.items.get(id);\n if (item === undefined) {\n return false;\n }\n\n // Update running totals before removal\n this.subtractFromTotals(item.category, item.tokenCount);\n\n this.items.delete(id);\n this.invalidateCache();\n this.logger.debug('Removed item', { id });\n return true;\n }\n\n /**\n * Get an item by ID.\n *\n * @param id - The item ID\n * @returns The item or undefined\n */\n get(id: string): ContextItem | undefined {\n return this.items.get(id);\n }\n\n /**\n * Check if an item with the given content can be added to a category.\n *\n * @param content - The content to check\n * @param category - The target category\n * @returns True if the content can fit\n */\n async canAdd(content: string, category: keyof Omit<ContextBudget, 'reserved'>): Promise<boolean> {\n const tokenCount = await this.countTokens(content);\n const categoryBudget = this.getCategoryBudget(category);\n const currentCategoryTokens = this.getCategoryTokenCount(category);\n\n if (currentCategoryTokens + tokenCount > categoryBudget) {\n return false;\n }\n\n const usableTokens = this.maxTokens * (1 - this.budget.reserved);\n const currentTotal = this.getTotalTokenCount();\n\n return currentTotal + tokenCount <= usableTokens;\n }\n\n /**\n * Get all items in a category.\n *\n * @param category - The category to filter by\n * @returns Items in the category, sorted by priority (desc) then addedAt (asc)\n */\n getByCategory(category: keyof Omit<ContextBudget, 'reserved'>): ContextItem[] {\n return Array.from(this.items.values())\n .filter((item) => item.category === category)\n .sort((a, b) => {\n // Higher priority first\n if (a.priority !== b.priority) {\n return b.priority - a.priority;\n }\n // Then by addedAt (older first for FIFO within same priority)\n return a.addedAt - b.addedAt;\n });\n }\n\n /**\n * Get all items sorted by priority (desc) then addedAt (asc).\n *\n * @returns All items sorted\n */\n getAllItems(): ContextItem[] {\n return Array.from(this.items.values()).sort((a, b) => {\n if (a.priority !== b.priority) {\n return b.priority - a.priority;\n }\n return a.addedAt - b.addedAt;\n });\n }\n\n /**\n * Build messages array from context items.\n * Converts context items to Message format for model requests.\n *\n * @returns Array of messages\n */\n buildMessages(): Message[] {\n const items = this.getAllItems();\n const messages: Message[] = [];\n\n for (const item of items) {\n // Skip system items as they go in systemPrompt\n if (item.category === 'system') {\n continue;\n }\n\n // Parse content to determine role\n // By default, treat as user message\n messages.push({\n role: 'user',\n content: item.content,\n });\n }\n\n return messages;\n }\n\n /**\n * Get the system prompt from system category items.\n *\n * @returns Combined system prompt or undefined\n */\n getSystemPrompt(): string | undefined {\n const systemItems = this.getByCategory('system');\n if (systemItems.length === 0) {\n return undefined;\n }\n return systemItems.map((item) => item.content).join('\\n\\n');\n }\n\n /**\n * Get current context statistics.\n *\n * @returns Context usage statistics\n */\n getStats(): ContextStats {\n if (this.cachedStats !== null) {\n return this.cachedStats;\n }\n\n const categoryTokens: Record<keyof Omit<ContextBudget, 'reserved'>, number> = {\n system: 0,\n task: 0,\n active: 0,\n };\n\n const itemCounts: Record<keyof Omit<ContextBudget, 'reserved'>, number> = {\n system: 0,\n task: 0,\n active: 0,\n };\n\n for (const item of this.items.values()) {\n categoryTokens[item.category] += item.tokenCount;\n itemCounts[item.category]++;\n }\n\n const totalTokens = categoryTokens.system + categoryTokens.task + categoryTokens.active;\n const availableTokens = Math.floor(this.maxTokens * (1 - this.budget.reserved));\n const usagePercentage = totalTokens / availableTokens;\n\n const overBudgetCategories: Array<keyof Omit<ContextBudget, 'reserved'>> = [];\n const categories: Array<keyof Omit<ContextBudget, 'reserved'>> = ['system', 'task', 'active'];\n\n for (const category of categories) {\n const budget = this.getCategoryBudget(category);\n if (categoryTokens[category] > budget) {\n overBudgetCategories.push(category);\n }\n }\n\n this.cachedStats = {\n totalTokens,\n categoryTokens,\n itemCounts,\n availableTokens,\n isOverBudget: overBudgetCategories.length > 0,\n overBudgetCategories,\n usagePercentage,\n };\n\n return this.cachedStats;\n }\n\n /**\n * Get remaining tokens available in a category.\n *\n * @param category - The category to check\n * @returns Available tokens in the category\n */\n getRemainingTokens(category: keyof Omit<ContextBudget, 'reserved'>): number {\n const budget = this.getCategoryBudget(category);\n const used = this.getCategoryTokenCount(category);\n return Math.max(0, budget - used);\n }\n\n /**\n * Get total remaining tokens across all categories.\n *\n * @returns Available tokens in total\n */\n getTotalRemainingTokens(): number {\n const usableTokens = Math.floor(this.maxTokens * (1 - this.budget.reserved));\n return Math.max(0, usableTokens - this.getTotalTokenCount());\n }\n\n /**\n * Clear all items from the context.\n */\n clear(): void {\n this.items.clear();\n this.resetTokenCounts();\n this.invalidateCache();\n this.logger.info('Context cleared');\n }\n\n /**\n * Clear items from a specific category.\n *\n * @param category - The category to clear\n * @returns Number of items removed\n */\n clearCategory(category: keyof Omit<ContextBudget, 'reserved'>): number {\n let count = 0;\n let tokensRemoved = 0;\n for (const [id, item] of this.items.entries()) {\n if (item.category === category) {\n tokensRemoved += item.tokenCount;\n this.items.delete(id);\n count++;\n }\n }\n if (count > 0) {\n // Update running totals\n this.subtractFromTotals(category, tokensRemoved);\n this.invalidateCache();\n this.logger.debug('Cleared category', { category, itemsRemoved: count });\n }\n return count;\n }\n\n /**\n * Count tokens in text using adapter or fallback estimation.\n *\n * @param text - Text to count tokens for\n * @returns Token count\n */\n async countTokens(text: string): Promise<number> {\n if (this.adapter !== undefined) {\n return await this.adapter.countTokens(text);\n }\n // Fallback: rough character-based estimation\n return Math.ceil(text.length / CHARS_PER_TOKEN);\n }\n\n /**\n * Get the token budget for a category.\n */\n private getCategoryBudget(category: keyof Omit<ContextBudget, 'reserved'>): number {\n return Math.floor(this.maxTokens * this.budget[category]);\n }\n\n /**\n * Get current token count for a category.\n * Returns cached value updated on add/remove operations (O(1)).\n */\n private getCategoryTokenCount(category: ContextItemCategory): number {\n return this.categoryTokenCounts.get(category) ?? 0;\n }\n\n /**\n * Get total token count across all categories.\n * Returns cached value updated on add/remove operations (O(1)).\n */\n private getTotalTokenCount(): number {\n return this.totalTokenCount;\n }\n\n /**\n * Invalidate cached statistics.\n */\n private invalidateCache(): void {\n this.cachedStats = null;\n }\n\n /**\n * Add token count to running totals for a category.\n */\n private addToTotals(category: ContextItemCategory, tokenCount: number): void {\n const current = this.categoryTokenCounts.get(category) ?? 0;\n this.categoryTokenCounts.set(category, current + tokenCount);\n this.totalTokenCount += tokenCount;\n }\n\n /**\n * Subtract token count from running totals for a category.\n */\n private subtractFromTotals(category: ContextItemCategory, tokenCount: number): void {\n const current = this.categoryTokenCounts.get(category) ?? 0;\n this.categoryTokenCounts.set(category, Math.max(0, current - tokenCount));\n this.totalTokenCount = Math.max(0, this.totalTokenCount - tokenCount);\n }\n\n /**\n * Reset all token count totals to zero.\n */\n private resetTokenCounts(): void {\n this.categoryTokenCounts.set('system', 0);\n this.categoryTokenCounts.set('task', 0);\n this.categoryTokenCounts.set('active', 0);\n this.totalTokenCount = 0;\n }\n\n /**\n * Check if usage exceeds warning threshold and log.\n */\n private checkWarningThreshold(): void {\n const stats = this.getStats();\n if (stats.usagePercentage >= this.warningThreshold) {\n this.logger.warn('Context usage approaching limit', {\n usagePercentage: Math.round(stats.usagePercentage * 100),\n totalTokens: stats.totalTokens,\n availableTokens: stats.availableTokens,\n threshold: Math.round(this.warningThreshold * 100),\n });\n }\n }\n}\n","/**\n * @nexus-agents/agents - ContextPruner\n *\n * Handles context pruning with priority-based content retention,\n * summarization triggers, and various history pruning strategies.\n */\n\nimport { z } from 'zod';\nimport type { Result, IModelAdapter, ILogger, Message } from '../core/index.js';\nimport { ok, err, ValidationError, createLogger } from '../core/index.js';\nimport {\n ContextManager,\n ContentPriority,\n type ContextItem,\n type ContextBudget,\n} from './context-manager.js';\n\n/**\n * Strategy for pruning context when budget is exceeded.\n */\nexport const PruningStrategy = {\n /** Remove oldest items first (FIFO) */\n OLDEST_FIRST: 'oldest_first',\n /** Remove lowest priority items first */\n LOWEST_PRIORITY: 'lowest_priority',\n /** Remove items by combining priority and age */\n PRIORITY_WEIGHTED_AGE: 'priority_weighted_age',\n /** Summarize old content instead of removing */\n SUMMARIZE: 'summarize',\n} as const;\n\nexport type PruningStrategy = (typeof PruningStrategy)[keyof typeof PruningStrategy];\n\n/**\n * Result of a pruning operation.\n */\nexport interface PruneResult {\n /** Items that were removed */\n removedItems: ContextItem[];\n /** Items that were summarized (if using SUMMARIZE strategy) */\n summarizedItems: ContextItem[];\n /** New summary item (if content was summarized) */\n summaryItem?: ContextItem;\n /** Tokens freed by pruning */\n tokensFreed: number;\n /** Whether pruning achieved the target */\n targetReached: boolean;\n}\n\n/**\n * Configuration for ContextPruner.\n */\nexport interface ContextPrunerConfig {\n /** The context manager to prune */\n contextManager: ContextManager;\n /** Model adapter for summarization (optional) */\n adapter?: IModelAdapter;\n /** Custom logger */\n logger?: ILogger;\n /** Default pruning strategy */\n defaultStrategy?: PruningStrategy;\n /** Minimum items to keep in each category */\n minItemsPerCategory?: number;\n /** Items with priority >= this are never pruned */\n protectedPriority?: ContentPriority;\n /** Token threshold that triggers automatic pruning (0-1) */\n autoTriggerThreshold?: number;\n}\n\n/**\n * Schema for ContextPrunerConfig validation.\n */\nexport const ContextPrunerConfigSchema = z.object({\n defaultStrategy: z\n .enum([\n PruningStrategy.OLDEST_FIRST,\n PruningStrategy.LOWEST_PRIORITY,\n PruningStrategy.PRIORITY_WEIGHTED_AGE,\n PruningStrategy.SUMMARIZE,\n ])\n .optional(),\n minItemsPerCategory: z.number().int().min(0).optional(),\n protectedPriority: z.number().min(0).max(100).optional(),\n autoTriggerThreshold: z.number().min(0).max(1).optional(),\n});\n\n/**\n * Options for a pruning operation.\n */\nexport interface PruneOptions {\n /** Target tokens to free */\n targetTokens?: number;\n /** Strategy to use (overrides default) */\n strategy?: PruningStrategy;\n /** Categories to prune (defaults to all non-protected) */\n categories?: Array<keyof Omit<ContextBudget, 'reserved'>>;\n /** Prompt for summarization (if using SUMMARIZE strategy) */\n summarizationPrompt?: string;\n}\n\n/**\n * Score for an item used in priority-weighted pruning.\n */\ninterface PruneScore {\n item: ContextItem;\n score: number;\n}\n\n/**\n * Default minimum items to keep per category.\n */\nconst DEFAULT_MIN_ITEMS = 1;\n\n/**\n * Default threshold that triggers auto-pruning.\n */\nconst DEFAULT_AUTO_TRIGGER = 0.9;\n\n/**\n * Default summarization prompt.\n */\nconst DEFAULT_SUMMARIZATION_PROMPT = `Summarize the following content concisely, preserving key information:`;\n\n/**\n * Handles context pruning with multiple strategies.\n *\n * @example\n * ```typescript\n * const pruner = new ContextPruner({\n * contextManager,\n * adapter: claudeAdapter,\n * defaultStrategy: PruningStrategy.PRIORITY_WEIGHTED_AGE,\n * });\n *\n * // Prune to free 10000 tokens\n * const result = await pruner.prune({ targetTokens: 10000 });\n *\n * // Check if auto-pruning is needed\n * if (pruner.shouldPrune()) {\n * await pruner.prune();\n * }\n * ```\n */\nexport class ContextPruner {\n private readonly contextManager: ContextManager;\n private readonly adapter: IModelAdapter | undefined;\n private readonly logger: ILogger;\n private readonly defaultStrategy: PruningStrategy;\n private readonly minItemsPerCategory: number;\n private readonly protectedPriority: ContentPriority;\n private readonly autoTriggerThreshold: number;\n\n constructor(config: ContextPrunerConfig) {\n const validation = ContextPrunerConfigSchema.safeParse({\n defaultStrategy: config.defaultStrategy,\n minItemsPerCategory: config.minItemsPerCategory,\n protectedPriority: config.protectedPriority,\n autoTriggerThreshold: config.autoTriggerThreshold,\n });\n\n if (!validation.success) {\n const issues = validation.error.issues\n .map((issue) => `${issue.path.join('.')}: ${issue.message}`)\n .join('; ');\n throw new ValidationError(`Invalid ContextPruner config: ${issues}`, {\n context: { validationErrors: validation.error.issues },\n });\n }\n\n this.contextManager = config.contextManager;\n this.adapter = config.adapter;\n this.logger = config.logger ?? createLogger({ component: 'ContextPruner' });\n this.defaultStrategy = config.defaultStrategy ?? PruningStrategy.PRIORITY_WEIGHTED_AGE;\n this.minItemsPerCategory = config.minItemsPerCategory ?? DEFAULT_MIN_ITEMS;\n this.protectedPriority = config.protectedPriority ?? ContentPriority.SYSTEM;\n this.autoTriggerThreshold = config.autoTriggerThreshold ?? DEFAULT_AUTO_TRIGGER;\n }\n\n /**\n * Check if pruning should be triggered based on usage threshold.\n *\n * @returns True if usage exceeds auto-trigger threshold\n */\n shouldPrune(): boolean {\n const stats = this.contextManager.getStats();\n return stats.usagePercentage >= this.autoTriggerThreshold;\n }\n\n /**\n * Prune context to free tokens or reach target capacity.\n *\n * @param options - Pruning options\n * @returns Result with pruning details\n */\n async prune(options: PruneOptions = {}): Promise<Result<PruneResult, ValidationError>> {\n const strategy = options.strategy ?? this.defaultStrategy;\n const categories = options.categories ?? ['active', 'task'];\n\n // Calculate target tokens to free\n const targetTokens = options.targetTokens ?? this.calculateDefaultTarget();\n\n if (targetTokens <= 0) {\n return ok({\n removedItems: [],\n summarizedItems: [],\n tokensFreed: 0,\n targetReached: true,\n });\n }\n\n this.logger.info('Starting pruning operation', {\n strategy,\n targetTokens,\n categories,\n });\n\n switch (strategy) {\n case PruningStrategy.OLDEST_FIRST:\n return this.pruneOldestFirst(targetTokens, categories);\n case PruningStrategy.LOWEST_PRIORITY:\n return this.pruneLowestPriority(targetTokens, categories);\n case PruningStrategy.PRIORITY_WEIGHTED_AGE:\n return this.prunePriorityWeightedAge(targetTokens, categories);\n case PruningStrategy.SUMMARIZE:\n return this.pruneWithSummarization(targetTokens, categories, options.summarizationPrompt);\n default:\n return err(new ValidationError(`Unknown pruning strategy: ${String(strategy)}`));\n }\n }\n\n /**\n * Prune items from a specific category.\n *\n * @param category - Category to prune\n * @param targetTokens - Tokens to free\n * @returns Result with pruning details\n */\n async pruneCategory(\n category: keyof Omit<ContextBudget, 'reserved'>,\n targetTokens: number\n ): Promise<Result<PruneResult, ValidationError>> {\n return this.prune({\n targetTokens,\n categories: [category],\n });\n }\n\n /**\n * Get candidates for pruning from specified categories.\n *\n * @param categories - Categories to consider\n * @returns Prunable items (excludes protected items)\n */\n getPruneCandidates(categories: Array<keyof Omit<ContextBudget, 'reserved'>>): ContextItem[] {\n const allItems: ContextItem[] = [];\n\n for (const category of categories) {\n const categoryItems = this.contextManager.getByCategory(category);\n allItems.push(...categoryItems);\n }\n\n // Filter out protected items\n const prunableItems = allItems.filter((item) => item.priority < this.protectedPriority);\n\n return prunableItems;\n }\n\n /**\n * Estimate tokens that can be freed from specified categories.\n *\n * @param categories - Categories to consider\n * @returns Tokens that could be freed\n */\n estimateFreeableTokens(categories: Array<keyof Omit<ContextBudget, 'reserved'>>): number {\n const candidates = this.getPruneCandidates(categories);\n\n // Account for minimum items per category\n const categoryItems: Map<keyof Omit<ContextBudget, 'reserved'>, ContextItem[]> = new Map();\n\n for (const item of candidates) {\n const existing = categoryItems.get(item.category) ?? [];\n existing.push(item);\n categoryItems.set(item.category, existing);\n }\n\n let freeableTokens = 0;\n for (const [, items] of categoryItems) {\n // Sort by pruning order (lowest priority, oldest first)\n const sorted = items.sort((a, b) => {\n if (a.priority !== b.priority) return a.priority - b.priority;\n return a.addedAt - b.addedAt;\n });\n\n // Can prune all except minItemsPerCategory\n const prunableCount = Math.max(0, sorted.length - this.minItemsPerCategory);\n for (let i = 0; i < prunableCount; i++) {\n const item = sorted[i];\n if (item !== undefined) {\n freeableTokens += item.tokenCount;\n }\n }\n }\n\n return freeableTokens;\n }\n\n /**\n * Calculate default target tokens based on current usage.\n */\n private calculateDefaultTarget(): number {\n const stats = this.contextManager.getStats();\n // Free 20% of current usage or enough to get below threshold\n const targetUsage = this.autoTriggerThreshold - 0.1;\n const targetTotal = Math.floor(stats.availableTokens * targetUsage);\n return Math.max(0, stats.totalTokens - targetTotal);\n }\n\n /**\n * Prune oldest items first (FIFO strategy).\n */\n private pruneOldestFirst(\n targetTokens: number,\n categories: Array<keyof Omit<ContextBudget, 'reserved'>>\n ): Result<PruneResult, ValidationError> {\n const candidates = this.getPruneCandidates(categories);\n\n // Sort by addedAt (oldest first)\n const sorted = candidates.sort((a, b) => a.addedAt - b.addedAt);\n\n return this.removeItemsToTarget(sorted, targetTokens, categories);\n }\n\n /**\n * Prune lowest priority items first.\n */\n private pruneLowestPriority(\n targetTokens: number,\n categories: Array<keyof Omit<ContextBudget, 'reserved'>>\n ): Result<PruneResult, ValidationError> {\n const candidates = this.getPruneCandidates(categories);\n\n // Sort by priority (lowest first), then age (oldest first)\n const sorted = candidates.sort((a, b) => {\n if (a.priority !== b.priority) return a.priority - b.priority;\n return a.addedAt - b.addedAt;\n });\n\n return this.removeItemsToTarget(sorted, targetTokens, categories);\n }\n\n /**\n * Prune using priority-weighted age scoring.\n */\n private prunePriorityWeightedAge(\n targetTokens: number,\n categories: Array<keyof Omit<ContextBudget, 'reserved'>>\n ): Result<PruneResult, ValidationError> {\n const candidates = this.getPruneCandidates(categories);\n const now = Date.now();\n\n // Calculate score for each item\n // Lower score = prune first\n // Score = priority * recency_factor\n // recency_factor = 1 / (age_hours + 1)\n const scores: PruneScore[] = candidates.map((item) => {\n const ageMs = now - item.addedAt;\n const ageHours = ageMs / (1000 * 60 * 60);\n const recencyFactor = 1 / (ageHours + 1);\n const score = item.priority * recencyFactor;\n return { item, score };\n });\n\n // Sort by score (lowest first = prune first)\n scores.sort((a, b) => a.score - b.score);\n const sorted = scores.map((s) => s.item);\n\n return this.removeItemsToTarget(sorted, targetTokens, categories);\n }\n\n /**\n * Prune with summarization of old content.\n */\n private async pruneWithSummarization(\n targetTokens: number,\n categories: Array<keyof Omit<ContextBudget, 'reserved'>>,\n customPrompt?: string\n ): Promise<Result<PruneResult, ValidationError>> {\n if (this.adapter === undefined) {\n this.logger.warn('No adapter configured, falling back to priority-weighted pruning');\n return this.prunePriorityWeightedAge(targetTokens, categories);\n }\n\n const candidates = this.getPruneCandidates(categories);\n if (candidates.length === 0) {\n return ok(this.createEmptyPruneResult());\n }\n\n const toSummarize = this.selectItemsForSummarization(candidates);\n const summaryResult = await this.performSummarization(toSummarize, customPrompt);\n\n if (!summaryResult.ok) {\n this.logger.warn('Summarization failed, falling back to removal');\n return this.prunePriorityWeightedAge(targetTokens, categories);\n }\n\n return this.finalizeSummarization(toSummarize, summaryResult.value, targetTokens);\n }\n\n /**\n * Create an empty prune result.\n */\n private createEmptyPruneResult(): PruneResult {\n return {\n removedItems: [],\n summarizedItems: [],\n tokensFreed: 0,\n targetReached: false,\n };\n }\n\n /**\n * Select items to summarize (oldest 50%).\n */\n private selectItemsForSummarization(candidates: ContextItem[]): ContextItem[] {\n const sorted = candidates.sort((a, b) => a.addedAt - b.addedAt);\n return sorted.slice(0, Math.ceil(sorted.length / 2));\n }\n\n /**\n * Perform summarization of items.\n */\n private async performSummarization(\n items: ContextItem[],\n customPrompt?: string\n ): Promise<Result<string, ValidationError>> {\n const content = items.map((item) => item.content).join('\\n\\n---\\n\\n');\n const prompt = customPrompt ?? DEFAULT_SUMMARIZATION_PROMPT;\n return this.generateSummary(content, prompt);\n }\n\n /**\n * Finalize summarization by removing items and adding summary.\n */\n private async finalizeSummarization(\n toSummarize: ContextItem[],\n summary: string,\n targetTokens: number\n ): Promise<Result<PruneResult, ValidationError>> {\n let tokensFreed = this.removeSummarizedItems(toSummarize);\n const summaryCategory = this.findDominantCategory(toSummarize);\n\n const summaryAddResult = await this.addSummaryItem(summary, summaryCategory);\n let summaryItem: ContextItem | undefined;\n\n if (summaryAddResult.item !== undefined) {\n summaryItem = summaryAddResult.item;\n tokensFreed -= summaryAddResult.tokenCount;\n }\n\n const targetReached = tokensFreed >= targetTokens;\n this.logger.info('Pruning with summarization completed', {\n summarizedItems: toSummarize.length,\n tokensFreed,\n targetReached,\n });\n\n const result: PruneResult = {\n removedItems: [],\n summarizedItems: toSummarize,\n tokensFreed,\n targetReached,\n };\n\n if (summaryItem !== undefined) {\n result.summaryItem = summaryItem;\n }\n\n return ok(result);\n }\n\n /**\n * Remove summarized items and return tokens freed.\n */\n private removeSummarizedItems(items: ContextItem[]): number {\n let tokensFreed = 0;\n for (const item of items) {\n this.contextManager.remove(item.id);\n tokensFreed += item.tokenCount;\n }\n return tokensFreed;\n }\n\n /**\n * Find the category with most items.\n */\n private findDominantCategory(items: ContextItem[]): keyof Omit<ContextBudget, 'reserved'> {\n const counts = new Map<keyof Omit<ContextBudget, 'reserved'>, number>();\n for (const item of items) {\n counts.set(item.category, (counts.get(item.category) ?? 0) + 1);\n }\n\n let dominant: keyof Omit<ContextBudget, 'reserved'> = 'active';\n let maxCount = 0;\n for (const [cat, count] of counts) {\n if (count > maxCount) {\n maxCount = count;\n dominant = cat;\n }\n }\n return dominant;\n }\n\n /**\n * Add a summary item to the context.\n */\n private async addSummaryItem(\n summary: string,\n category: keyof Omit<ContextBudget, 'reserved'>\n ): Promise<{ item: ContextItem | undefined; tokenCount: number }> {\n const tokenCount = await this.contextManager.countTokens(summary);\n const result = await this.contextManager.add({\n id: `summary-${String(Date.now())}`,\n content: summary,\n priority: ContentPriority.HISTORY,\n category,\n });\n\n return {\n item: result.ok ? result.value : undefined,\n tokenCount,\n };\n }\n\n /**\n * Remove items from sorted list until target is reached.\n */\n private removeItemsToTarget(\n sortedItems: ContextItem[],\n targetTokens: number,\n categories: Array<keyof Omit<ContextBudget, 'reserved'>>\n ): Result<PruneResult, ValidationError> {\n // Track items per category to enforce minimum\n const categoryRemaining = new Map<keyof Omit<ContextBudget, 'reserved'>, number>();\n for (const category of categories) {\n const items = this.contextManager.getByCategory(category);\n categoryRemaining.set(category, items.length);\n }\n\n const removedItems: ContextItem[] = [];\n let tokensFreed = 0;\n\n for (const item of sortedItems) {\n if (tokensFreed >= targetTokens) {\n break;\n }\n\n // Check minimum items constraint\n const remaining = categoryRemaining.get(item.category) ?? 0;\n if (remaining <= this.minItemsPerCategory) {\n continue;\n }\n\n // Remove the item\n this.contextManager.remove(item.id);\n removedItems.push(item);\n tokensFreed += item.tokenCount;\n categoryRemaining.set(item.category, remaining - 1);\n }\n\n const targetReached = tokensFreed >= targetTokens;\n\n this.logger.info('Pruning completed', {\n itemsRemoved: removedItems.length,\n tokensFreed,\n targetTokens,\n targetReached,\n });\n\n return ok({\n removedItems,\n summarizedItems: [],\n tokensFreed,\n targetReached,\n });\n }\n\n /**\n * Generate a summary using the model adapter.\n */\n private async generateSummary(\n content: string,\n prompt: string\n ): Promise<Result<string, ValidationError>> {\n if (this.adapter === undefined) {\n return err(new ValidationError('No adapter configured for summarization'));\n }\n\n const messages: Message[] = [{ role: 'user', content: `${prompt}\\n\\n${content}` }];\n\n const result = await this.adapter.complete({\n messages,\n temperature: 0.3,\n maxTokens: 1024,\n });\n\n if (!result.ok) {\n return err(new ValidationError(`Summarization failed: ${result.error.message}`));\n }\n\n // Extract text content from response\n const textContent = result.value.content\n .filter((block): block is { type: 'text'; text: string } => block.type === 'text')\n .map((block) => block.text)\n .join('\\n');\n\n return ok(textContent);\n }\n}\n","/**\n * @nexus-agents/agents - Expert Types and Schemas\n *\n * Shared type definitions and Zod schemas for expert agents.\n * Experts are domain-specialized agents that handle specific task types.\n */\n\nimport { z } from 'zod';\nimport type { AgentCapability, AgentRole } from '../../core/index.js';\n\n/**\n * Expert domain categories.\n */\nexport type ExpertDomain = 'code' | 'security' | 'architecture' | 'testing' | 'documentation';\n\n/**\n * Expert-specific configuration options.\n */\nexport interface ExpertOptions {\n /** Custom system prompt override */\n systemPromptOverride?: string;\n /** Temperature for completions (domain-specific default if not set) */\n temperature?: number;\n /** Maximum tokens for responses */\n maxTokens?: number;\n /** Enable domain-specific heuristics */\n enableHeuristics?: boolean;\n /** Custom capability extensions */\n additionalCapabilities?: AgentCapability[];\n}\n\n/**\n * Output format for expert task results.\n */\nexport interface ExpertOutput {\n /** Primary result content */\n content: string;\n /** Structured data if applicable */\n structuredData?: Record<string, unknown> | undefined;\n /** Recommendations or suggestions */\n recommendations?: string[] | undefined;\n /** Warnings or issues found */\n warnings?: string[] | undefined;\n /** Confidence score (0-1) */\n confidence: number;\n}\n\n/**\n * Code analysis result from CodeExpert.\n */\nexport interface CodeAnalysisResult extends ExpertOutput {\n /** Type of code operation performed */\n operationType: 'generation' | 'refactoring' | 'optimization' | 'debugging';\n /** Files affected */\n affectedFiles?: string[] | undefined;\n /** Code changes or suggestions */\n codeChanges?: CodeChange[] | undefined;\n}\n\n/**\n * Represents a single code change.\n */\nexport interface CodeChange {\n /** File path */\n file: string;\n /** Line number or range */\n lineRange?: { start: number; end: number };\n /** Original code */\n original?: string;\n /** Modified code */\n modified: string;\n /** Description of change */\n description: string;\n}\n\n/**\n * Security analysis result from SecurityExpert.\n */\nexport interface SecurityAnalysisResult extends ExpertOutput {\n /** Vulnerabilities found */\n vulnerabilities: Vulnerability[];\n /** Security score (0-100) */\n securityScore: number;\n /** Compliance status */\n compliance?: ComplianceStatus;\n}\n\n/**\n * Represents a security vulnerability.\n */\nexport interface Vulnerability {\n /** Unique vulnerability ID */\n id: string;\n /** Severity level */\n severity: 'critical' | 'high' | 'medium' | 'low' | 'info';\n /** Vulnerability type (OWASP category) */\n type: string;\n /** Description of the vulnerability */\n description: string;\n /** Affected location */\n location?: string;\n /** Remediation steps */\n remediation: string;\n /** CWE reference if applicable */\n cweId?: string;\n}\n\n/**\n * Compliance check status.\n */\nexport interface ComplianceStatus {\n /** Compliance framework */\n framework: string;\n /** Overall status */\n status: 'compliant' | 'partial' | 'non-compliant';\n /** Specific findings */\n findings: string[];\n}\n\n/**\n * Architecture analysis result from ArchitectureExpert.\n */\nexport interface ArchitectureAnalysisResult extends ExpertOutput {\n /** Analysis type */\n analysisType: 'design' | 'review' | 'pattern_selection';\n /** Identified patterns */\n patterns?: ArchitecturePattern[] | undefined;\n /** Design decisions */\n decisions?: ArchitectureDecision[] | undefined;\n /** System components */\n components?: SystemComponent[] | undefined;\n}\n\n/**\n * Architecture pattern identification.\n */\nexport interface ArchitecturePattern {\n /** Pattern name */\n name: string;\n /** Pattern category */\n category: string;\n /** Applicability score (0-1) */\n applicability: number;\n /** Trade-offs */\n tradeoffs: { pros: string[]; cons: string[] };\n}\n\n/**\n * Architecture decision record.\n */\nexport interface ArchitectureDecision {\n /** Decision ID */\n id: string;\n /** Decision title */\n title: string;\n /** Context */\n context: string;\n /** Decision made */\n decision: string;\n /** Consequences */\n consequences: string[];\n /** Status */\n status: 'proposed' | 'accepted' | 'deprecated' | 'superseded';\n}\n\n/**\n * System component in architecture.\n */\nexport interface SystemComponent {\n /** Component name */\n name: string;\n /** Component type */\n type: string;\n /** Responsibilities */\n responsibilities: string[];\n /** Dependencies */\n dependencies: string[];\n}\n\n/**\n * Testing analysis result from TestingExpert.\n */\nexport interface TestingAnalysisResult extends ExpertOutput {\n /** Operation type */\n operationType: 'generation' | 'coverage_analysis' | 'quality_assessment';\n /** Generated tests */\n tests?: GeneratedTest[] | undefined;\n /** Coverage metrics */\n coverage?: CoverageMetrics | undefined;\n /** Test quality assessment */\n quality?: TestQuality | undefined;\n}\n\n/**\n * Generated test case.\n */\nexport interface GeneratedTest {\n /** Test name */\n name: string;\n /** Test type */\n type: 'unit' | 'integration' | 'e2e';\n /** Test code */\n code: string;\n /** Target function/component */\n target: string;\n /** Test scenarios covered */\n scenarios: string[];\n}\n\n/**\n * Code coverage metrics.\n */\nexport interface CoverageMetrics {\n /** Line coverage percentage */\n line: number;\n /** Branch coverage percentage */\n branch: number;\n /** Function coverage percentage */\n function: number;\n /** Statement coverage percentage */\n statement: number;\n /** Uncovered areas */\n uncoveredAreas?: string[];\n}\n\n/**\n * Test quality assessment.\n */\nexport interface TestQuality {\n /** Overall score (0-100) */\n score: number;\n /** Test isolation */\n isolation: 'good' | 'fair' | 'poor';\n /** Assertion quality */\n assertionQuality: 'good' | 'fair' | 'poor';\n /** Issues found */\n issues: string[];\n}\n\n/**\n * Documentation result from DocumentationExpert.\n */\nexport interface DocumentationResult extends ExpertOutput {\n /** Documentation type */\n documentationType: 'api' | 'readme' | 'guide' | 'reference';\n /** Generated documentation sections */\n sections?: DocumentationSection[] | undefined;\n /** API documentation */\n apiDocs?: ApiDocumentation | undefined;\n}\n\n/**\n * Documentation section.\n */\nexport interface DocumentationSection {\n /** Section title */\n title: string;\n /** Section content */\n content: string;\n /** Subsections */\n subsections?: DocumentationSection[];\n}\n\n/**\n * API documentation structure.\n */\nexport interface ApiDocumentation {\n /** API endpoints or functions */\n endpoints: ApiEndpoint[];\n /** Data types */\n types: ApiType[];\n}\n\n/**\n * API endpoint documentation.\n */\nexport interface ApiEndpoint {\n /** Endpoint name */\n name: string;\n /** Description */\n description: string;\n /** Parameters */\n parameters: Array<{\n name: string;\n type: string;\n description: string;\n required: boolean;\n }>;\n /** Return type */\n returns: { type: string; description: string };\n /** Example usage */\n example?: string;\n}\n\n/**\n * API type documentation.\n */\nexport interface ApiType {\n /** Type name */\n name: string;\n /** Description */\n description: string;\n /** Properties */\n properties: Array<{\n name: string;\n type: string;\n description: string;\n optional: boolean;\n }>;\n}\n\n// ============================================================================\n// Zod Schemas\n// ============================================================================\n\n/**\n * Expert domain schema.\n */\nexport const ExpertDomainSchema = z.enum([\n 'code',\n 'security',\n 'architecture',\n 'testing',\n 'documentation',\n]);\n\n/**\n * Expert options schema.\n */\nexport const ExpertOptionsSchema = z.object({\n systemPromptOverride: z.string().optional(),\n temperature: z.number().min(0).max(1).optional(),\n maxTokens: z.number().positive().optional(),\n enableHeuristics: z.boolean().optional(),\n additionalCapabilities: z.array(z.string()).optional(),\n});\n\n/**\n * Expert output schema.\n */\nexport const ExpertOutputSchema = z.object({\n content: z.string(),\n structuredData: z.record(z.unknown()).optional(),\n recommendations: z.array(z.string()).optional(),\n warnings: z.array(z.string()).optional(),\n confidence: z.number().min(0).max(1),\n});\n\n/**\n * Vulnerability severity schema.\n */\nexport const VulnerabilitySeveritySchema = z.enum(['critical', 'high', 'medium', 'low', 'info']);\n\n/**\n * Vulnerability schema.\n */\nexport const VulnerabilitySchema = z.object({\n id: z.string().min(1),\n severity: VulnerabilitySeveritySchema,\n type: z.string().min(1),\n description: z.string().min(1),\n location: z.string().optional(),\n remediation: z.string().min(1),\n cweId: z.string().optional(),\n});\n\n/**\n * Code change schema.\n */\nexport const CodeChangeSchema = z.object({\n file: z.string().min(1),\n lineRange: z\n .object({\n start: z.number().positive(),\n end: z.number().positive(),\n })\n .optional(),\n original: z.string().optional(),\n modified: z.string(),\n description: z.string().min(1),\n});\n\n/**\n * Generated test schema.\n */\nexport const GeneratedTestSchema = z.object({\n name: z.string().min(1),\n type: z.enum(['unit', 'integration', 'e2e']),\n code: z.string().min(1),\n target: z.string().min(1),\n scenarios: z.array(z.string()),\n});\n\n/**\n * Coverage metrics schema.\n */\nexport const CoverageMetricsSchema = z.object({\n line: z.number().min(0).max(100),\n branch: z.number().min(0).max(100),\n function: z.number().min(0).max(100),\n statement: z.number().min(0).max(100),\n uncoveredAreas: z.array(z.string()).optional(),\n});\n\n/**\n * Default temperatures for each expert domain.\n */\nexport const EXPERT_DEFAULT_TEMPERATURES: Record<ExpertDomain, number> = {\n code: 0.2,\n security: 0.3,\n architecture: 0.5,\n testing: 0.3,\n documentation: 0.4,\n};\n\n/**\n * Default capabilities for each expert role.\n */\nexport const EXPERT_DEFAULT_CAPABILITIES: Record<AgentRole, readonly AgentCapability[]> = {\n code_expert: ['task_execution', 'code_generation', 'code_review', 'tool_use'],\n security_expert: ['task_execution', 'code_review', 'research'],\n architecture_expert: ['task_execution', 'research', 'collaboration'],\n testing_expert: ['task_execution', 'code_generation', 'tool_use'],\n documentation_expert: ['task_execution', 'research'],\n tech_lead: ['task_execution', 'delegation', 'collaboration', 'research'],\n custom: ['task_execution'],\n};\n","/**\n * @nexus-agents/agents - CodeExpert\n *\n * Expert agent specialized in code generation, refactoring, optimization,\n * and debugging. Uses low temperature (0.2-0.3) for precise code output.\n *\n * Capabilities:\n * - code_generation: Generate new code from specifications\n * - refactoring: Improve existing code structure\n * - optimization: Enhance performance\n * - debugging: Identify and fix bugs\n */\n\nimport type {\n Result,\n Task,\n TaskResult,\n AgentCapability,\n CompletionRequest,\n Message,\n} from '../../core/index.js';\nimport { ok, err, AgentError } from '../../core/index.js';\nimport { BaseAgent, type BaseAgentOptions } from '../base-agent.js';\nimport {\n type ExpertOptions,\n type CodeAnalysisResult,\n EXPERT_DEFAULT_TEMPERATURES,\n EXPERT_DEFAULT_CAPABILITIES,\n} from './expert-types.js';\n\n/**\n * System prompt for the CodeExpert agent.\n */\nconst CODE_EXPERT_SYSTEM_PROMPT = `You are a senior software engineer expert specializing in code generation, refactoring, optimization, and debugging.\n\n## Core Principles\n1. Write clean, maintainable, and well-documented code\n2. Follow SOLID principles and established design patterns\n3. Prioritize readability over cleverness\n4. Consider edge cases and error handling\n5. Include appropriate type annotations\n\n## Output Format\nRespond with JSON matching this structure:\n{\n \"content\": \"Summary of what was done\",\n \"operationType\": \"generation\" | \"refactoring\" | \"optimization\" | \"debugging\",\n \"codeChanges\": [\n {\n \"file\": \"path/to/file.ts\",\n \"modified\": \"// new or modified code\",\n \"description\": \"What this change does\"\n }\n ],\n \"recommendations\": [\"Suggestion 1\", \"Suggestion 2\"],\n \"warnings\": [\"Warning 1\"],\n \"confidence\": 0.0-1.0\n}\n\n## Guidelines\n- For code generation: Create complete, working implementations\n- For refactoring: Preserve functionality while improving structure\n- For optimization: Measure before and after, document trade-offs\n- For debugging: Identify root cause, not just symptoms`;\n\n/**\n * Configuration options for CodeExpert.\n */\nexport interface CodeExpertOptions extends ExpertOptions {\n /** Enable strict type checking recommendations */\n strictTypes?: boolean;\n /** Preferred code style (if applicable) */\n codeStyle?: 'functional' | 'object-oriented' | 'mixed';\n /** Target language for code generation */\n targetLanguage?: string;\n}\n\n/**\n * CodeExpert - Expert agent for code-related tasks.\n *\n * Specialized in:\n * - Code generation from specifications\n * - Code refactoring and cleanup\n * - Performance optimization\n * - Bug detection and debugging\n */\nexport class CodeExpert extends BaseAgent {\n private readonly expertOptions: CodeExpertOptions;\n\n constructor(options: Partial<BaseAgentOptions> & { expertOptions?: CodeExpertOptions } = {}) {\n const expertOpts = options.expertOptions ?? {};\n const baseOptions = buildCodeExpertBaseOptions(options, expertOpts);\n\n super(baseOptions);\n this.expertOptions = expertOpts;\n }\n\n /**\n * Execute a code-related task.\n */\n protected async executeTask(task: Task): Promise<Result<TaskResult, AgentError>> {\n const startTime = Date.now();\n const operationType = this.inferOperationType(task.description);\n\n this.logger.info('Executing code task', {\n taskId: task.id,\n operationType,\n hasAdapter: this.adapter !== undefined,\n });\n\n // If no adapter, use heuristic analysis\n if (this.adapter === undefined) {\n return this.executeHeuristic(task, operationType, startTime);\n }\n\n // Use model for code analysis\n return this.executeWithModel(task, operationType, startTime);\n }\n\n /**\n * Build prompt messages for the task.\n */\n protected buildPrompt(task: Task): Message[] {\n const contextInfo = this.buildContextInfo(task);\n\n return [\n {\n role: 'user',\n content: `${contextInfo}\n\n## Task\n${task.description}\n\nPlease analyze and provide your response in the JSON format specified.`,\n },\n ];\n }\n\n /**\n * Get the expert options.\n */\n getExpertOptions(): Readonly<CodeExpertOptions> {\n return { ...this.expertOptions };\n }\n\n /**\n * Execute task with heuristic analysis (no model).\n */\n private executeHeuristic(\n task: Task,\n operationType: CodeAnalysisResult['operationType'],\n startTime: number\n ): Result<TaskResult, AgentError> {\n const result = this.createHeuristicResult(task, operationType);\n\n return ok({\n taskId: task.id,\n output: result,\n metadata: {\n durationMs: Date.now() - startTime,\n tokensUsed: 0,\n toolsUsed: [],\n model: 'heuristic',\n },\n });\n }\n\n /**\n * Execute task with model adapter.\n */\n private async executeWithModel(\n task: Task,\n operationType: CodeAnalysisResult['operationType'],\n startTime: number\n ): Promise<Result<TaskResult, AgentError>> {\n const messages = this.buildPrompt(task);\n\n const request: CompletionRequest = {\n messages,\n systemPrompt: this.systemPrompt ?? CODE_EXPERT_SYSTEM_PROMPT,\n temperature: this.temperature,\n maxTokens: this.maxTokens,\n };\n\n const completionResult = await this.complete(request);\n if (!completionResult.ok) {\n return err(completionResult.error);\n }\n\n const response = completionResult.value;\n const textContent = this.extractTextContent(response.content);\n const result = this.parseCodeResult(textContent, operationType);\n\n return ok({\n taskId: task.id,\n output: result,\n metadata: {\n durationMs: Date.now() - startTime,\n tokensUsed: response.usage.totalTokens,\n toolsUsed: [],\n model: response.model,\n },\n });\n }\n\n /**\n * Infer the operation type from task description.\n */\n private inferOperationType(description: string): CodeAnalysisResult['operationType'] {\n const desc = description.toLowerCase();\n\n if (desc.includes('debug') || desc.includes('fix bug') || desc.includes('error')) {\n return 'debugging';\n }\n if (desc.includes('optimize') || desc.includes('performance') || desc.includes('faster')) {\n return 'optimization';\n }\n if (desc.includes('refactor') || desc.includes('clean') || desc.includes('restructure')) {\n return 'refactoring';\n }\n return 'generation';\n }\n\n /**\n * Build context information from task.\n */\n private buildContextInfo(task: Task): string {\n const parts: string[] = [];\n\n if (task.context.workingDirectory !== undefined) {\n parts.push(`Working Directory: ${task.context.workingDirectory}`);\n }\n\n if (task.context.files !== undefined && task.context.files.length > 0) {\n parts.push(`Relevant Files:\\n${task.context.files.map((f) => `- ${f}`).join('\\n')}`);\n }\n\n if (this.expertOptions.targetLanguage !== undefined) {\n parts.push(`Target Language: ${this.expertOptions.targetLanguage}`);\n }\n\n if (this.expertOptions.codeStyle !== undefined) {\n parts.push(`Code Style: ${this.expertOptions.codeStyle}`);\n }\n\n if (this.expertOptions.strictTypes === true) {\n parts.push('Note: Strict type checking is enabled');\n }\n\n return parts.length > 0 ? `## Context\\n${parts.join('\\n')}\\n` : '';\n }\n\n /**\n * Create a heuristic result without model.\n */\n private createHeuristicResult(\n task: Task,\n operationType: CodeAnalysisResult['operationType']\n ): CodeAnalysisResult {\n const recommendations = this.generateHeuristicRecommendations(operationType);\n const warnings = this.detectHeuristicWarnings(task.description);\n\n return {\n content: `Heuristic analysis for ${operationType} task. Model adapter required for detailed code generation.`,\n operationType,\n recommendations,\n warnings,\n confidence: 0.4,\n };\n }\n\n /**\n * Generate recommendations based on operation type.\n */\n private generateHeuristicRecommendations(\n operationType: CodeAnalysisResult['operationType']\n ): string[] {\n const baseRecs = ['Consider adding unit tests', 'Document public interfaces'];\n\n switch (operationType) {\n case 'generation':\n return [...baseRecs, 'Follow project coding standards', 'Use TypeScript strict mode'];\n case 'refactoring':\n return [...baseRecs, 'Ensure tests pass before and after', 'Make incremental changes'];\n case 'optimization':\n return [...baseRecs, 'Benchmark before optimizing', 'Document trade-offs'];\n case 'debugging':\n return [...baseRecs, 'Add regression test for the bug', 'Check for similar issues'];\n default:\n return baseRecs;\n }\n }\n\n /**\n * Detect potential warnings from task description.\n */\n private detectHeuristicWarnings(description: string): string[] {\n const warnings: string[] = [];\n const desc = description.toLowerCase();\n\n if (desc.includes('database') || desc.includes('sql')) {\n warnings.push('Database changes may require migration');\n }\n if (desc.includes('api') || desc.includes('endpoint')) {\n warnings.push('API changes may be breaking');\n }\n if (desc.includes('security') || desc.includes('auth')) {\n warnings.push('Security-sensitive code requires careful review');\n }\n if (desc.includes('concurrent') || desc.includes('async')) {\n warnings.push('Concurrency requires careful error handling');\n }\n\n return warnings;\n }\n\n /**\n * Parse code result from model response.\n */\n private parseCodeResult(\n text: string,\n defaultType: CodeAnalysisResult['operationType']\n ): CodeAnalysisResult {\n try {\n const jsonText = this.extractJsonFromText(text);\n const parsed = JSON.parse(jsonText) as Partial<CodeAnalysisResult>;\n\n const result: CodeAnalysisResult = {\n content: parsed.content ?? 'Code analysis completed',\n operationType: parsed.operationType ?? defaultType,\n confidence: parsed.confidence ?? 0.7,\n };\n if (parsed.affectedFiles !== undefined) {\n result.affectedFiles = parsed.affectedFiles;\n }\n if (parsed.codeChanges !== undefined) {\n result.codeChanges = parsed.codeChanges;\n }\n if (parsed.recommendations !== undefined) {\n result.recommendations = parsed.recommendations;\n }\n if (parsed.warnings !== undefined) {\n result.warnings = parsed.warnings;\n }\n return result;\n } catch {\n // Fall back to treating the whole response as content\n return {\n content: text,\n operationType: defaultType,\n confidence: 0.5,\n };\n }\n }\n\n /**\n * Extract JSON from text that may contain markdown code blocks.\n */\n private extractJsonFromText(text: string): string {\n const match = text.match(/```(?:json)?\\s*([\\s\\S]*?)```/);\n return match?.[1]?.trim() ?? text.trim();\n }\n\n /**\n * Extract text content from completion response.\n */\n private extractTextContent(content: Array<{ type: string; text?: string }>): string {\n return content\n .filter((block): block is { type: 'text'; text: string } => block.type === 'text')\n .map((block) => block.text)\n .join('\\n');\n }\n}\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\nfunction buildCodeExpertBaseOptions(\n options: Partial<BaseAgentOptions>,\n expertOpts: CodeExpertOptions\n): BaseAgentOptions {\n const temperature = expertOpts.temperature ?? EXPERT_DEFAULT_TEMPERATURES.code;\n const baseCapabilities = EXPERT_DEFAULT_CAPABILITIES.code_expert;\n const additionalCaps = expertOpts.additionalCapabilities ?? [];\n\n const baseOptions: BaseAgentOptions = {\n id: options.id ?? 'code-expert',\n role: 'code_expert',\n capabilities: [...baseCapabilities, ...additionalCaps] as AgentCapability[],\n temperature,\n maxTokens: options.maxTokens ?? 8192,\n systemPrompt: expertOpts.systemPromptOverride ?? CODE_EXPERT_SYSTEM_PROMPT,\n };\n\n if (options.adapter !== undefined) baseOptions.adapter = options.adapter;\n if (options.logger !== undefined) baseOptions.logger = options.logger;\n\n return baseOptions;\n}\n\n/**\n * Creates a new CodeExpert agent with the given options.\n */\nexport function createCodeExpert(\n options?: Partial<BaseAgentOptions> & { expertOptions?: CodeExpertOptions }\n): CodeExpert {\n return new CodeExpert(options);\n}\n","/**\n * @nexus-agents/agents - Expert System Prompts\n *\n * System prompts for expert agents.\n */\n\n/**\n * System prompt for the TestingExpert agent.\n */\nexport const TESTING_EXPERT_SYSTEM_PROMPT = `You are a testing expert specializing in test-driven development, test automation, and quality assurance.\n\n## Core Principles\n1. Write tests that are independent, repeatable, and fast\n2. Follow AAA pattern: Arrange, Act, Assert\n3. Test behavior, not implementation\n4. Aim for high coverage on critical paths\n5. Include edge cases and error scenarios\n\n## Output Format\nRespond with JSON matching this structure:\n{\n \"content\": \"Summary of testing analysis\",\n \"operationType\": \"generation\" | \"coverage_analysis\" | \"quality_assessment\",\n \"tests\": [\n {\n \"name\": \"should do something when condition\",\n \"type\": \"unit\" | \"integration\" | \"e2e\",\n \"code\": \"// test code here\",\n \"target\": \"function or component being tested\",\n \"scenarios\": [\"Scenario 1\", \"Scenario 2\"]\n }\n ],\n \"coverage\": {\n \"line\": 0-100,\n \"branch\": 0-100,\n \"function\": 0-100,\n \"statement\": 0-100,\n \"uncoveredAreas\": [\"Uncovered area 1\"]\n },\n \"quality\": {\n \"score\": 0-100,\n \"isolation\": \"good\" | \"fair\" | \"poor\",\n \"assertionQuality\": \"good\" | \"fair\" | \"poor\",\n \"issues\": [\"Issue 1\"]\n },\n \"recommendations\": [\"Testing improvement 1\"],\n \"warnings\": [\"Testing concern 1\"],\n \"confidence\": 0.0-1.0\n}\n\n## Test Types\n- Unit: Isolated component tests with mocked dependencies\n- Integration: Tests across module boundaries\n- E2E: Full system tests simulating user behavior\n\n## Testing Frameworks\n- Vitest/Jest for unit and integration tests\n- Playwright/Cypress for e2e tests\n- Testing Library for component tests`;\n\n/**\n * System prompt for the SecurityExpert agent.\n */\nexport const SECURITY_EXPERT_SYSTEM_PROMPT = `You are a security expert specializing in application security, vulnerability assessment, and security hardening.\n\n## Core Principles\n1. Follow OWASP Top 10 and OWASP API Security Top 10 guidelines\n2. Apply defense in depth strategies\n3. Prioritize findings by risk level (CVSS-style scoring)\n4. Provide actionable remediation steps\n5. Consider both code-level and architectural security\n\n## Output Format\nRespond with JSON matching this structure:\n{\n \"content\": \"Summary of security analysis\",\n \"vulnerabilities\": [\n {\n \"id\": \"VULN-001\",\n \"severity\": \"critical\" | \"high\" | \"medium\" | \"low\" | \"info\",\n \"type\": \"OWASP category or CWE type\",\n \"description\": \"Detailed description\",\n \"location\": \"file:line or component\",\n \"remediation\": \"How to fix\",\n \"cweId\": \"CWE-XXX (optional)\"\n }\n ],\n \"securityScore\": 0-100,\n \"compliance\": {\n \"framework\": \"OWASP/NIST/etc\",\n \"status\": \"compliant\" | \"partial\" | \"non-compliant\",\n \"findings\": [\"Finding 1\", \"Finding 2\"]\n },\n \"recommendations\": [\"Security improvement 1\"],\n \"warnings\": [\"Critical warning 1\"],\n \"confidence\": 0.0-1.0\n}\n\n## Security Categories\n- A01: Broken Access Control\n- A02: Cryptographic Failures\n- A03: Injection\n- A04: Insecure Design\n- A05: Security Misconfiguration\n- A06: Vulnerable Components\n- A07: Authentication Failures\n- A08: Software/Data Integrity Failures\n- A09: Security Logging/Monitoring Failures\n- A10: Server-Side Request Forgery (SSRF)`;\n\n/**\n * System prompt for the DocumentationExpert agent.\n */\nexport const DOCUMENTATION_EXPERT_SYSTEM_PROMPT = `You are a technical documentation expert specializing in creating clear, comprehensive, and user-friendly documentation.\n\n## Core Principles\n1. Write for your audience - consider their technical level\n2. Use clear, concise language\n3. Include practical examples\n4. Maintain consistent structure and formatting\n5. Keep documentation up-to-date with code\n\n## Output Format\nRespond with JSON matching this structure:\n{\n \"content\": \"Main documentation content in markdown\",\n \"documentationType\": \"api\" | \"readme\" | \"guide\" | \"reference\",\n \"sections\": [\n {\n \"title\": \"Section Title\",\n \"content\": \"Section content in markdown\",\n \"subsections\": [/* nested sections */]\n }\n ],\n \"apiDocs\": {\n \"endpoints\": [\n {\n \"name\": \"functionOrEndpointName\",\n \"description\": \"What it does\",\n \"parameters\": [\n {\"name\": \"param\", \"type\": \"string\", \"description\": \"desc\", \"required\": true}\n ],\n \"returns\": {\"type\": \"ReturnType\", \"description\": \"What is returned\"},\n \"example\": \"// Usage example\"\n }\n ],\n \"types\": [\n {\n \"name\": \"TypeName\",\n \"description\": \"What this type represents\",\n \"properties\": [\n {\"name\": \"prop\", \"type\": \"string\", \"description\": \"desc\", \"optional\": false}\n ]\n }\n ]\n },\n \"recommendations\": [\"Documentation improvement 1\"],\n \"warnings\": [\"Documentation issue 1\"],\n \"confidence\": 0.0-1.0\n}\n\n## Documentation Types\n- API Docs: Function signatures, parameters, return types, examples\n- README: Project overview, installation, usage, contribution guidelines\n- Guide: Step-by-step tutorials, how-to content\n- Reference: Comprehensive technical reference`;\n\n/**\n * System prompt for the ArchitectureExpert agent.\n */\nexport const ARCHITECTURE_EXPERT_SYSTEM_PROMPT = `You are an architecture expert specializing in software design, system architecture, and design patterns.\n\n## Core Principles\n1. Follow SOLID principles\n2. Favor composition over inheritance\n3. Design for change and extensibility\n4. Consider scalability and performance\n5. Document architectural decisions (ADRs)\n\n## Output Format\nRespond with JSON matching this structure:\n{\n \"content\": \"Summary of architectural analysis\",\n \"patterns\": [\n {\n \"name\": \"Pattern Name\",\n \"category\": \"creational\" | \"structural\" | \"behavioral\" | \"architectural\",\n \"applicability\": \"When to use this pattern\",\n \"tradeoffs\": [\"Pro 1\", \"Con 1\"]\n }\n ],\n \"components\": [\n {\n \"name\": \"Component Name\",\n \"responsibility\": \"What this component does\",\n \"dependencies\": [\"Dependency 1\"],\n \"interfaces\": [\"Interface 1\"]\n }\n ],\n \"recommendations\": [\"Architecture improvement 1\"],\n \"warnings\": [\"Architecture concern 1\"],\n \"confidence\": 0.0-1.0\n}\n\n## Architecture Patterns\n- Layered, Hexagonal, Clean Architecture\n- Microservices, Event-Driven, CQRS\n- Repository, Factory, Strategy patterns`;\n\n/**\n * System prompt for the CodeExpert agent.\n */\nexport const CODE_EXPERT_SYSTEM_PROMPT = `You are a code expert specializing in code review, refactoring, and best practices across multiple programming languages.\n\n## Core Principles\n1. Write clean, readable, maintainable code\n2. Follow language-specific conventions and idioms\n3. Prioritize correctness, then clarity, then performance\n4. Apply SOLID principles and design patterns appropriately\n5. Consider edge cases and error handling\n\n## Output Format\nRespond with JSON matching this structure:\n{\n \"content\": \"Summary of code analysis\",\n \"issues\": [\n {\n \"severity\": \"error\" | \"warning\" | \"info\",\n \"type\": \"bug\" | \"style\" | \"performance\" | \"security\" | \"maintainability\",\n \"description\": \"Issue description\",\n \"location\": \"file:line\",\n \"suggestion\": \"How to fix\"\n }\n ],\n \"suggestions\": [\n {\n \"type\": \"refactor\" | \"optimize\" | \"simplify\",\n \"description\": \"Suggestion description\",\n \"before\": \"// current code\",\n \"after\": \"// improved code\"\n }\n ],\n \"recommendations\": [\"Code improvement 1\"],\n \"warnings\": [\"Code concern 1\"],\n \"confidence\": 0.0-1.0\n}\n\n## Code Quality Metrics\n- Readability and clarity\n- DRY (Don't Repeat Yourself)\n- Single Responsibility Principle\n- Proper error handling\n- Appropriate abstraction level`;\n","/**\n * @nexus-agents/agents - SecurityExpert Helpers\n *\n * Helper functions for the SecurityExpert agent including\n * vulnerability detection and heuristic analysis utilities.\n */\n\nimport type { Vulnerability, SecurityAnalysisResult } from './expert-types.js';\n\n// ============================================================================\n// Vulnerability Patterns\n// ============================================================================\n\ninterface VulnerabilityPattern {\n pattern: RegExp;\n severity: Vulnerability['severity'];\n type: string;\n description: string;\n remediation: string;\n cweId?: string;\n}\n\n/**\n * Common vulnerability patterns for heuristic detection.\n */\nexport const VULNERABILITY_PATTERNS: VulnerabilityPattern[] = [\n {\n pattern: /sql|query.*user|database.*input/i,\n severity: 'critical',\n type: 'A03:2021 - Injection',\n description: 'Potential SQL injection vulnerability detected',\n remediation: 'Use parameterized queries or prepared statements',\n cweId: 'CWE-89',\n },\n {\n pattern: /password|secret|api.?key|token/i,\n severity: 'high',\n type: 'A02:2021 - Cryptographic Failures',\n description: 'Potential exposure of sensitive credentials',\n remediation: 'Use secure secrets management and environment variables',\n cweId: 'CWE-798',\n },\n {\n pattern: /eval|exec|system|shell/i,\n severity: 'critical',\n type: 'A03:2021 - Injection',\n description: 'Potential code/command injection risk',\n remediation: 'Avoid dynamic code execution; sanitize all inputs',\n cweId: 'CWE-94',\n },\n {\n pattern: /auth|login|session/i,\n severity: 'high',\n type: 'A07:2021 - Authentication Failures',\n description: 'Authentication-related code requires careful review',\n remediation: 'Implement secure session management and MFA',\n cweId: 'CWE-287',\n },\n {\n pattern: /permission|role|access|admin/i,\n severity: 'high',\n type: 'A01:2021 - Broken Access Control',\n description: 'Access control code detected - verify authorization logic',\n remediation: 'Implement principle of least privilege and verify all access controls',\n cweId: 'CWE-284',\n },\n];\n\n// ============================================================================\n// Vulnerability Detection\n// ============================================================================\n\ninterface DetectionOptions {\n enableCweMapping?: boolean | undefined;\n minSeverity?: Vulnerability['severity'] | undefined;\n}\n\n/**\n * Detects vulnerabilities using heuristic patterns.\n */\nexport function detectHeuristicVulnerabilities(\n description: string,\n options: DetectionOptions = {}\n): Vulnerability[] {\n const vulnerabilities: Vulnerability[] = [];\n const desc = description.toLowerCase();\n let vulnId = 1;\n\n for (const p of VULNERABILITY_PATTERNS) {\n if (p.pattern.test(desc)) {\n const vuln: Vulnerability = {\n id: `VULN-${String(vulnId++).padStart(3, '0')}`,\n severity: p.severity,\n type: p.type,\n description: p.description,\n remediation: p.remediation,\n };\n if (options.enableCweMapping === true && p.cweId !== undefined) {\n vuln.cweId = p.cweId;\n }\n vulnerabilities.push(vuln);\n }\n }\n\n return filterBySeverity(vulnerabilities, options.minSeverity);\n}\n\n/**\n * Filters vulnerabilities by minimum severity.\n */\nfunction filterBySeverity(\n vulnerabilities: Vulnerability[],\n minSeverity: Vulnerability['severity'] = 'info'\n): Vulnerability[] {\n const severityOrder: Record<Vulnerability['severity'], number> = {\n critical: 5,\n high: 4,\n medium: 3,\n low: 2,\n info: 1,\n };\n\n const minLevel = severityOrder[minSeverity];\n return vulnerabilities.filter((v) => severityOrder[v.severity] >= minLevel);\n}\n\n// ============================================================================\n// Security Analysis Helpers\n// ============================================================================\n\n/**\n * Calculates security score based on vulnerabilities.\n */\nexport function calculateSecurityScore(vulnerabilities: Vulnerability[]): number {\n if (vulnerabilities.length === 0) return 100;\n\n const severityWeights: Record<Vulnerability['severity'], number> = {\n critical: 25,\n high: 15,\n medium: 8,\n low: 3,\n info: 1,\n };\n\n const totalDeduction = vulnerabilities.reduce((sum, v) => sum + severityWeights[v.severity], 0);\n\n return Math.max(0, 100 - totalDeduction);\n}\n\n/**\n * Generates recommendations based on vulnerabilities.\n */\nexport function generateHeuristicRecommendations(vulnerabilities: Vulnerability[]): string[] {\n const recommendations: string[] = [\n 'Perform regular security audits',\n 'Keep dependencies updated',\n 'Implement security headers',\n ];\n\n const hasCritical = vulnerabilities.some((v) => v.severity === 'critical');\n const hasHigh = vulnerabilities.some((v) => v.severity === 'high');\n\n if (hasCritical) {\n recommendations.unshift('URGENT: Address critical vulnerabilities immediately');\n }\n if (hasHigh) {\n recommendations.push('Schedule remediation for high-severity findings');\n }\n\n return recommendations;\n}\n\n/**\n * Generates security warnings.\n */\nexport function generateSecurityWarnings(vulnerabilities: Vulnerability[]): string[] {\n const warnings: string[] = [];\n\n const criticalCount = vulnerabilities.filter((v) => v.severity === 'critical').length;\n const highCount = vulnerabilities.filter((v) => v.severity === 'high').length;\n\n if (criticalCount > 0) {\n warnings.push(`Found ${String(criticalCount)} critical vulnerability(s)`);\n }\n if (highCount > 0) {\n warnings.push(`Found ${String(highCount)} high-severity vulnerability(s)`);\n }\n\n return warnings;\n}\n\n/**\n * Parses security result from model response.\n */\nexport function parseSecurityResult(\n text: string,\n calculateScore: (vulns: Vulnerability[]) => number,\n validator: (v: unknown) => { success: boolean; data?: Vulnerability }\n): SecurityAnalysisResult {\n try {\n const jsonText = extractJsonFromText(text);\n const parsed = JSON.parse(jsonText) as Partial<SecurityAnalysisResult>;\n\n // Validate vulnerabilities\n const validVulns = (parsed.vulnerabilities ?? [])\n .map((v) => validator(v))\n .filter((r) => r.success)\n .map((r) => r.data as Vulnerability);\n\n const result: SecurityAnalysisResult = {\n content: parsed.content ?? 'Security analysis completed',\n vulnerabilities: validVulns,\n securityScore: parsed.securityScore ?? calculateScore(validVulns),\n confidence: parsed.confidence ?? 0.7,\n };\n if (parsed.compliance !== undefined) result.compliance = parsed.compliance;\n if (parsed.recommendations !== undefined) result.recommendations = parsed.recommendations;\n if (parsed.warnings !== undefined) result.warnings = parsed.warnings;\n return result;\n } catch {\n return { content: text, vulnerabilities: [], securityScore: 50, confidence: 0.3 };\n }\n}\n\n/**\n * Extracts JSON from text that may contain markdown code blocks.\n */\nfunction extractJsonFromText(text: string): string {\n const match = text.match(/```(?:json)?\\s*([\\s\\S]*?)```/);\n return match?.[1]?.trim() ?? text.trim();\n}\n","/**\n * @nexus-agents/agents - SecurityExpert\n *\n * Expert agent specialized in security review, vulnerability detection,\n * and security hardening. Uses temperature 0.3 for precise analysis.\n */\n\nimport type {\n Result,\n Task,\n TaskResult,\n AgentCapability,\n CompletionRequest,\n Message,\n} from '../../core/index.js';\nimport { ok, err, AgentError } from '../../core/index.js';\nimport { BaseAgent, type BaseAgentOptions } from '../base-agent.js';\nimport {\n type ExpertOptions,\n type SecurityAnalysisResult,\n type Vulnerability,\n VulnerabilitySchema,\n EXPERT_DEFAULT_TEMPERATURES,\n EXPERT_DEFAULT_CAPABILITIES,\n} from './expert-types.js';\nimport { SECURITY_EXPERT_SYSTEM_PROMPT } from './expert-prompts.js';\nimport {\n detectHeuristicVulnerabilities,\n calculateSecurityScore,\n generateHeuristicRecommendations,\n generateSecurityWarnings,\n parseSecurityResult,\n} from './security-expert-helpers.js';\n\n/**\n * Configuration options for SecurityExpert.\n */\nexport interface SecurityExpertOptions extends ExpertOptions {\n /** Compliance frameworks to check */\n complianceFrameworks?: string[];\n /** Minimum severity to report */\n minSeverity?: 'critical' | 'high' | 'medium' | 'low' | 'info';\n /** Enable detailed CWE mappings */\n enableCweMapping?: boolean;\n /** Security focus areas */\n focusAreas?: SecurityFocusArea[];\n}\n\n/**\n * Security focus areas for targeted analysis.\n */\nexport type SecurityFocusArea =\n | 'authentication'\n | 'authorization'\n | 'input_validation'\n | 'cryptography'\n | 'injection'\n | 'secrets'\n | 'dependencies';\n\n/**\n * SecurityExpert - Expert agent for security-related tasks.\n */\nexport class SecurityExpert extends BaseAgent {\n private readonly expertOptions: SecurityExpertOptions;\n\n constructor(options: Partial<BaseAgentOptions> & { expertOptions?: SecurityExpertOptions } = {}) {\n const expertOpts = options.expertOptions ?? {};\n const baseOptions = buildBaseOptions(options, expertOpts);\n\n super(baseOptions);\n this.expertOptions = expertOpts;\n }\n\n protected async executeTask(task: Task): Promise<Result<TaskResult, AgentError>> {\n const startTime = Date.now();\n\n this.logger.info('Executing security task', {\n taskId: task.id,\n focusAreas: this.expertOptions.focusAreas,\n hasAdapter: this.adapter !== undefined,\n });\n\n if (this.adapter === undefined) {\n return this.executeHeuristic(task, startTime);\n }\n\n return this.executeWithModel(task, startTime);\n }\n\n protected buildPrompt(task: Task): Message[] {\n const contextInfo = this.buildContextInfo(task);\n\n return [\n {\n role: 'user',\n content: `${contextInfo}\n\n## Security Review Task\n${task.description}\n\nAnalyze for security vulnerabilities and provide findings in the specified JSON format.`,\n },\n ];\n }\n\n getExpertOptions(): Readonly<SecurityExpertOptions> {\n return { ...this.expertOptions };\n }\n\n private executeHeuristic(task: Task, startTime: number): Result<TaskResult, AgentError> {\n const vulnerabilities = detectHeuristicVulnerabilities(task.description, {\n enableCweMapping: this.expertOptions.enableCweMapping,\n minSeverity: this.expertOptions.minSeverity,\n });\n const securityScore = calculateSecurityScore(vulnerabilities);\n\n const result: SecurityAnalysisResult = {\n content: 'Heuristic security analysis. Model adapter required for comprehensive review.',\n vulnerabilities,\n securityScore,\n recommendations: generateHeuristicRecommendations(vulnerabilities),\n warnings: generateSecurityWarnings(vulnerabilities),\n confidence: 0.4,\n };\n\n return ok({\n taskId: task.id,\n output: result,\n metadata: {\n durationMs: Date.now() - startTime,\n tokensUsed: 0,\n toolsUsed: [],\n model: 'heuristic',\n },\n });\n }\n\n private async executeWithModel(\n task: Task,\n startTime: number\n ): Promise<Result<TaskResult, AgentError>> {\n const messages = this.buildPrompt(task);\n\n const request: CompletionRequest = {\n messages,\n systemPrompt: this.systemPrompt ?? SECURITY_EXPERT_SYSTEM_PROMPT,\n temperature: this.temperature,\n maxTokens: this.maxTokens,\n };\n\n const completionResult = await this.complete(request);\n if (!completionResult.ok) {\n return err(completionResult.error);\n }\n\n const response = completionResult.value;\n const textContent = this.extractTextContent(response.content);\n const validator = (v: unknown): { success: boolean; data?: Vulnerability } => {\n const parsed = VulnerabilitySchema.safeParse(v);\n return parsed.success\n ? { success: true, data: parsed.data as Vulnerability }\n : { success: false };\n };\n const result = parseSecurityResult(textContent, calculateSecurityScore, validator);\n\n return ok({\n taskId: task.id,\n output: result,\n metadata: {\n durationMs: Date.now() - startTime,\n tokensUsed: response.usage.totalTokens,\n toolsUsed: [],\n model: response.model,\n },\n });\n }\n\n private buildContextInfo(task: Task): string {\n const parts: string[] = [];\n\n if (task.context.files !== undefined && task.context.files.length > 0) {\n parts.push(`Files to Review:\\n${task.context.files.map((f) => `- ${f}`).join('\\n')}`);\n }\n\n if (this.expertOptions.focusAreas !== undefined && this.expertOptions.focusAreas.length > 0) {\n parts.push(`Focus Areas: ${this.expertOptions.focusAreas.join(', ')}`);\n }\n\n if (\n this.expertOptions.complianceFrameworks !== undefined &&\n this.expertOptions.complianceFrameworks.length > 0\n ) {\n parts.push(`Compliance Frameworks: ${this.expertOptions.complianceFrameworks.join(', ')}`);\n }\n\n if (this.expertOptions.minSeverity !== undefined) {\n parts.push(`Minimum Severity: ${this.expertOptions.minSeverity}`);\n }\n\n return parts.length > 0 ? `## Context\\n${parts.join('\\n')}\\n` : '';\n }\n\n private extractTextContent(content: Array<{ type: string; text?: string }>): string {\n return content\n .filter((block): block is { type: 'text'; text: string } => block.type === 'text')\n .map((block) => block.text)\n .join('\\n');\n }\n}\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\nfunction buildBaseOptions(\n options: Partial<BaseAgentOptions>,\n expertOpts: SecurityExpertOptions\n): BaseAgentOptions {\n const temperature = expertOpts.temperature ?? EXPERT_DEFAULT_TEMPERATURES.security;\n const baseCapabilities = EXPERT_DEFAULT_CAPABILITIES.security_expert;\n const additionalCaps = expertOpts.additionalCapabilities ?? [];\n\n const baseOptions: BaseAgentOptions = {\n id: options.id ?? 'security-expert',\n role: 'security_expert',\n capabilities: [...baseCapabilities, ...additionalCaps] as AgentCapability[],\n temperature,\n maxTokens: options.maxTokens ?? 8192,\n systemPrompt: expertOpts.systemPromptOverride ?? SECURITY_EXPERT_SYSTEM_PROMPT,\n };\n\n if (options.adapter !== undefined) baseOptions.adapter = options.adapter;\n if (options.logger !== undefined) baseOptions.logger = options.logger;\n\n return baseOptions;\n}\n\nexport function createSecurityExpert(\n options?: Partial<BaseAgentOptions> & { expertOptions?: SecurityExpertOptions }\n): SecurityExpert {\n return new SecurityExpert(options);\n}\n","/**\n * @nexus-agents/agents - ArchitectureExpert Helpers\n *\n * Helper functions for the ArchitectureExpert agent including\n * pattern identification and heuristic analysis utilities.\n */\n\nimport type {\n ArchitectureAnalysisResult,\n ArchitecturePattern,\n ArchitectureDecision,\n SystemComponent,\n} from './expert-types.js';\nimport type { Task } from '../../core/index.js';\n\n// ============================================================================\n// Pattern Definitions\n// ============================================================================\n\ninterface PatternMatch {\n pattern: RegExp;\n name: string;\n category: string;\n pros: string[];\n cons: string[];\n}\n\n/**\n * Architecture pattern matchers for heuristic detection.\n */\nexport const ARCHITECTURE_PATTERNS: PatternMatch[] = [\n {\n pattern: /microservice|distributed|service.?oriented/i,\n name: 'Microservices',\n category: 'Architectural',\n pros: ['Independent deployment', 'Technology flexibility', 'Scalability'],\n cons: ['Complexity', 'Network latency', 'Distributed data management'],\n },\n {\n pattern: /event|message|pub.?sub|async/i,\n name: 'Event-Driven',\n category: 'Architectural',\n pros: ['Loose coupling', 'Scalability', 'Resilience'],\n cons: ['Eventual consistency', 'Debugging complexity', 'Event ordering'],\n },\n {\n pattern: /layer|tier|mvc|presentation/i,\n name: 'Layered Architecture',\n category: 'Architectural',\n pros: ['Separation of concerns', 'Maintainability', 'Testability'],\n cons: ['Performance overhead', 'Rigidity', 'Monolithic tendency'],\n },\n {\n pattern: /domain|ddd|aggregate|bounded/i,\n name: 'Domain-Driven Design',\n category: 'Architectural',\n pros: ['Business alignment', 'Clear boundaries', 'Ubiquitous language'],\n cons: ['Learning curve', 'Overhead for simple domains', 'Initial cost'],\n },\n {\n pattern: /repository|factory|singleton/i,\n name: 'Repository Pattern',\n category: 'Structural',\n pros: ['Data access abstraction', 'Testability', 'Separation of concerns'],\n cons: ['Additional abstraction layer', 'Potential over-engineering'],\n },\n];\n\n// ============================================================================\n// Component Definitions\n// ============================================================================\n\ninterface ComponentPattern {\n pattern: RegExp;\n name: string;\n type: string;\n responsibilities: string[];\n}\n\n/**\n * Component pattern matchers for heuristic detection.\n */\nexport const COMPONENT_PATTERNS: ComponentPattern[] = [\n {\n pattern: /api|rest|endpoint/i,\n name: 'API Layer',\n type: 'Service',\n responsibilities: ['Request handling', 'Input validation', 'Response formatting'],\n },\n {\n pattern: /database|storage|persistence/i,\n name: 'Data Layer',\n type: 'Module',\n responsibilities: ['Data persistence', 'Query execution', 'Transaction management'],\n },\n {\n pattern: /auth|security|permission/i,\n name: 'Security Module',\n type: 'Module',\n responsibilities: ['Authentication', 'Authorization', 'Security enforcement'],\n },\n {\n pattern: /business|domain|core/i,\n name: 'Business Logic',\n type: 'Layer',\n responsibilities: ['Business rules', 'Domain operations', 'Workflow management'],\n },\n];\n\n// ============================================================================\n// Pattern Identification\n// ============================================================================\n\n/**\n * Identifies patterns using heuristic analysis.\n */\nexport function identifyHeuristicPatterns(description: string): ArchitecturePattern[] {\n const patterns: ArchitecturePattern[] = [];\n const desc = description.toLowerCase();\n\n for (const match of ARCHITECTURE_PATTERNS) {\n if (match.pattern.test(desc)) {\n patterns.push({\n name: match.name,\n category: match.category,\n applicability: 0.7,\n tradeoffs: { pros: match.pros, cons: match.cons },\n });\n }\n }\n\n return patterns.slice(0, 5);\n}\n\n/**\n * Identifies system components from description.\n */\nexport function identifyHeuristicComponents(description: string): SystemComponent[] {\n const components: SystemComponent[] = [];\n const desc = description.toLowerCase();\n\n for (const cp of COMPONENT_PATTERNS) {\n if (cp.pattern.test(desc)) {\n components.push({\n name: cp.name,\n type: cp.type,\n responsibilities: cp.responsibilities,\n dependencies: [],\n });\n }\n }\n\n return components;\n}\n\n// ============================================================================\n// ADR Generation\n// ============================================================================\n\n/**\n * Generates heuristic ADRs based on identified patterns.\n */\nexport function generateHeuristicADRs(\n task: Task,\n patterns: ArchitecturePattern[]\n): ArchitectureDecision[] {\n if (patterns.length === 0) return [];\n\n const primaryPattern = patterns[0];\n if (primaryPattern === undefined) return [];\n\n return [\n {\n id: 'ADR-001',\n title: `Adopt ${primaryPattern.name} Pattern`,\n context: `Based on the requirements in task ${task.id}`,\n decision: `Use ${primaryPattern.name} as the primary architectural pattern`,\n consequences: [\n ...primaryPattern.tradeoffs.pros.map((p) => `Pro: ${p}`),\n ...primaryPattern.tradeoffs.cons.map((c) => `Con: ${c}`),\n ],\n status: 'proposed',\n },\n ];\n}\n\n// ============================================================================\n// Analysis Type Inference\n// ============================================================================\n\n/**\n * Infers analysis type from task description.\n */\nexport function inferAnalysisType(description: string): ArchitectureAnalysisResult['analysisType'] {\n const desc = description.toLowerCase();\n\n if (desc.includes('pattern') || desc.includes('which approach')) {\n return 'pattern_selection';\n }\n if (desc.includes('review') || desc.includes('assess') || desc.includes('evaluate')) {\n return 'review';\n }\n return 'design';\n}\n\n// ============================================================================\n// Recommendations & Warnings\n// ============================================================================\n\n/**\n * Generates recommendations based on analysis type.\n */\nexport function generateHeuristicRecommendations(\n analysisType: ArchitectureAnalysisResult['analysisType']\n): string[] {\n const base = ['Document architecture decisions', 'Review with stakeholders'];\n\n switch (analysisType) {\n case 'design':\n return [...base, 'Create C4 diagrams', 'Define clear boundaries', 'Plan for evolution'];\n case 'review':\n return [...base, 'Identify technical debt', 'Assess scalability', 'Check security posture'];\n case 'pattern_selection':\n return [\n ...base,\n 'Prototype before committing',\n 'Consider team expertise',\n 'Evaluate trade-offs',\n ];\n default:\n return base;\n }\n}\n\n/**\n * Detects architecture warnings from description.\n */\nexport function detectArchitectureWarnings(description: string): string[] {\n const warnings: string[] = [];\n const desc = description.toLowerCase();\n\n if (desc.includes('monolith') && desc.includes('microservice')) {\n warnings.push('Migration from monolith to microservices is complex - plan carefully');\n }\n if (desc.includes('legacy')) {\n warnings.push('Legacy system integration requires careful boundary definition');\n }\n if (desc.includes('real-time') || desc.includes('low latency')) {\n warnings.push('Real-time requirements need specialized architecture considerations');\n }\n if (desc.includes('scale') || desc.includes('million')) {\n warnings.push('High-scale requirements need early capacity planning');\n }\n\n return warnings;\n}\n\n// ============================================================================\n// Result Parsing\n// ============================================================================\n\n/**\n * Parses architecture result from model response.\n */\nexport function parseArchitectureResult(\n text: string,\n defaultType: ArchitectureAnalysisResult['analysisType']\n): ArchitectureAnalysisResult {\n try {\n const jsonText = extractJsonFromText(text);\n const parsed = JSON.parse(jsonText) as Partial<ArchitectureAnalysisResult>;\n\n const result: ArchitectureAnalysisResult = {\n content: parsed.content ?? 'Architecture analysis completed',\n analysisType: parsed.analysisType ?? defaultType,\n confidence: parsed.confidence ?? 0.7,\n };\n if (parsed.patterns !== undefined) result.patterns = parsed.patterns;\n if (parsed.decisions !== undefined) result.decisions = parsed.decisions;\n if (parsed.components !== undefined) result.components = parsed.components;\n if (parsed.recommendations !== undefined) result.recommendations = parsed.recommendations;\n if (parsed.warnings !== undefined) result.warnings = parsed.warnings;\n return result;\n } catch {\n return { content: text, analysisType: defaultType, confidence: 0.5 };\n }\n}\n\n/**\n * Extracts JSON from text that may contain markdown code blocks.\n */\nfunction extractJsonFromText(text: string): string {\n const match = text.match(/```(?:json)?\\s*([\\s\\S]*?)```/);\n return match?.[1]?.trim() ?? text.trim();\n}\n","/**\n * @nexus-agents/agents - ArchitectureExpert\n *\n * Expert agent specialized in system design, design patterns,\n * and architecture decisions. Uses temperature 0.5 for balanced creativity.\n */\n\nimport type {\n Result,\n Task,\n TaskResult,\n AgentCapability,\n CompletionRequest,\n Message,\n} from '../../core/index.js';\nimport { ok, err, AgentError } from '../../core/index.js';\nimport { BaseAgent, type BaseAgentOptions } from '../base-agent.js';\nimport {\n type ExpertOptions,\n type ArchitectureAnalysisResult,\n EXPERT_DEFAULT_TEMPERATURES,\n EXPERT_DEFAULT_CAPABILITIES,\n} from './expert-types.js';\nimport { ARCHITECTURE_EXPERT_SYSTEM_PROMPT } from './expert-prompts.js';\nimport {\n identifyHeuristicPatterns,\n identifyHeuristicComponents,\n generateHeuristicADRs,\n inferAnalysisType,\n generateHeuristicRecommendations,\n detectArchitectureWarnings,\n parseArchitectureResult,\n} from './architecture-expert-helpers.js';\n\n/**\n * Configuration options for ArchitectureExpert.\n */\nexport interface ArchitectureExpertOptions extends ExpertOptions {\n /** Preferred architecture styles */\n preferredStyles?: ArchitectureStyle[];\n /** Generate ADRs automatically */\n generateADRs?: boolean;\n /** Include C4 diagram suggestions */\n includeC4Suggestions?: boolean;\n /** Quality attributes to prioritize */\n qualityPriorities?: QualityAttribute[];\n}\n\n/**\n * Architecture style options.\n */\nexport type ArchitectureStyle =\n | 'layered'\n | 'microservices'\n | 'event_driven'\n | 'hexagonal'\n | 'clean'\n | 'cqrs'\n | 'ddd';\n\n/**\n * Quality attributes for architecture decisions.\n */\nexport type QualityAttribute =\n | 'performance'\n | 'scalability'\n | 'maintainability'\n | 'security'\n | 'reliability'\n | 'testability';\n\n/**\n * ArchitectureExpert - Expert agent for architecture-related tasks.\n */\nexport class ArchitectureExpert extends BaseAgent {\n private readonly expertOptions: ArchitectureExpertOptions;\n\n constructor(\n options: Partial<BaseAgentOptions> & { expertOptions?: ArchitectureExpertOptions } = {}\n ) {\n const expertOpts = options.expertOptions ?? {};\n const baseOptions = buildBaseOptions(options, expertOpts);\n\n super(baseOptions);\n this.expertOptions = expertOpts;\n }\n\n protected async executeTask(task: Task): Promise<Result<TaskResult, AgentError>> {\n const startTime = Date.now();\n const analysisType = inferAnalysisType(task.description);\n\n this.logger.info('Executing architecture task', {\n taskId: task.id,\n analysisType,\n preferredStyles: this.expertOptions.preferredStyles,\n hasAdapter: this.adapter !== undefined,\n });\n\n if (this.adapter === undefined) {\n return this.executeHeuristic(task, analysisType, startTime);\n }\n\n return this.executeWithModel(task, analysisType, startTime);\n }\n\n protected buildPrompt(task: Task): Message[] {\n const contextInfo = this.buildContextInfo(task);\n\n return [\n {\n role: 'user',\n content: `${contextInfo}\n\n## Architecture Task\n${task.description}\n\nAnalyze and provide your architectural recommendations in the specified JSON format.`,\n },\n ];\n }\n\n getExpertOptions(): Readonly<ArchitectureExpertOptions> {\n return { ...this.expertOptions };\n }\n\n private executeHeuristic(\n task: Task,\n analysisType: ArchitectureAnalysisResult['analysisType'],\n startTime: number\n ): Result<TaskResult, AgentError> {\n const patterns = identifyHeuristicPatterns(task.description);\n const components = identifyHeuristicComponents(task.description);\n const decisions =\n this.expertOptions.generateADRs === true ? generateHeuristicADRs(task, patterns) : undefined;\n\n const result: ArchitectureAnalysisResult = {\n content: `Heuristic architecture analysis for ${analysisType}. Model adapter recommended.`,\n analysisType,\n patterns,\n components,\n decisions,\n recommendations: generateHeuristicRecommendations(analysisType),\n warnings: detectArchitectureWarnings(task.description),\n confidence: 0.4,\n };\n\n return ok({\n taskId: task.id,\n output: result,\n metadata: {\n durationMs: Date.now() - startTime,\n tokensUsed: 0,\n toolsUsed: [],\n model: 'heuristic',\n },\n });\n }\n\n private async executeWithModel(\n task: Task,\n analysisType: ArchitectureAnalysisResult['analysisType'],\n startTime: number\n ): Promise<Result<TaskResult, AgentError>> {\n const messages = this.buildPrompt(task);\n\n const request: CompletionRequest = {\n messages,\n systemPrompt: this.systemPrompt ?? ARCHITECTURE_EXPERT_SYSTEM_PROMPT,\n temperature: this.temperature,\n maxTokens: this.maxTokens,\n };\n\n const completionResult = await this.complete(request);\n if (!completionResult.ok) {\n return err(completionResult.error);\n }\n\n const response = completionResult.value;\n const textContent = this.extractTextContent(response.content);\n const result = parseArchitectureResult(textContent, analysisType);\n\n return ok({\n taskId: task.id,\n output: result,\n metadata: {\n durationMs: Date.now() - startTime,\n tokensUsed: response.usage.totalTokens,\n toolsUsed: [],\n model: response.model,\n },\n });\n }\n\n private buildContextInfo(task: Task): string {\n const parts: string[] = [];\n\n if (task.context.workingDirectory !== undefined) {\n parts.push(`Project: ${task.context.workingDirectory}`);\n }\n\n if (task.context.files !== undefined && task.context.files.length > 0) {\n parts.push(`Relevant Files:\\n${task.context.files.map((f) => `- ${f}`).join('\\n')}`);\n }\n\n if (this.expertOptions.preferredStyles !== undefined) {\n parts.push(`Preferred Styles: ${this.expertOptions.preferredStyles.join(', ')}`);\n }\n\n if (this.expertOptions.qualityPriorities !== undefined) {\n parts.push(`Quality Priorities: ${this.expertOptions.qualityPriorities.join(', ')}`);\n }\n\n if (this.expertOptions.includeC4Suggestions === true) {\n parts.push('Note: Include C4 diagram suggestions');\n }\n\n return parts.length > 0 ? `## Context\\n${parts.join('\\n')}\\n` : '';\n }\n\n private extractTextContent(content: Array<{ type: string; text?: string }>): string {\n return content\n .filter((block): block is { type: 'text'; text: string } => block.type === 'text')\n .map((block) => block.text)\n .join('\\n');\n }\n}\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\nfunction buildBaseOptions(\n options: Partial<BaseAgentOptions>,\n expertOpts: ArchitectureExpertOptions\n): BaseAgentOptions {\n const temperature = expertOpts.temperature ?? EXPERT_DEFAULT_TEMPERATURES.architecture;\n const baseCapabilities = EXPERT_DEFAULT_CAPABILITIES.architecture_expert;\n const additionalCaps = expertOpts.additionalCapabilities ?? [];\n\n const baseOptions: BaseAgentOptions = {\n id: options.id ?? 'architecture-expert',\n role: 'architecture_expert',\n capabilities: [...baseCapabilities, ...additionalCaps] as AgentCapability[],\n temperature,\n maxTokens: options.maxTokens ?? 8192,\n systemPrompt: expertOpts.systemPromptOverride ?? ARCHITECTURE_EXPERT_SYSTEM_PROMPT,\n };\n\n if (options.adapter !== undefined) baseOptions.adapter = options.adapter;\n if (options.logger !== undefined) baseOptions.logger = options.logger;\n\n return baseOptions;\n}\n\nexport function createArchitectureExpert(\n options?: Partial<BaseAgentOptions> & { expertOptions?: ArchitectureExpertOptions }\n): ArchitectureExpert {\n return new ArchitectureExpert(options);\n}\n","/**\n * @nexus-agents/agents - TestingExpert Helpers\n *\n * Helper functions for the TestingExpert agent including\n * test template generation and heuristic analysis utilities.\n */\n\nimport type {\n GeneratedTest,\n CoverageMetrics,\n TestQuality,\n TestingAnalysisResult,\n} from './expert-types.js';\n\n// ============================================================================\n// Test Template Generation\n// ============================================================================\n\n/**\n * Creates a unit test template for function testing.\n */\nexport function createUnitTestTemplate(framework: string): GeneratedTest {\n const importStatement =\n framework === 'jest'\n ? \"import { describe, it, expect } from '@jest/globals';\"\n : \"import { describe, it, expect } from 'vitest';\";\n\n return {\n name: 'should execute function correctly',\n type: 'unit',\n code: `${importStatement}\n\ndescribe('FunctionName', () => {\n it('should return expected result for valid input', () => {\n // Arrange\n const input = { /* test data */ };\n\n // Act\n const result = functionName(input);\n\n // Assert\n expect(result).toBeDefined();\n // Add specific assertions\n });\n\n it('should handle edge cases', () => {\n // Test edge cases\n });\n\n it('should throw error for invalid input', () => {\n expect(() => functionName(null)).toThrow();\n });\n});`,\n target: 'Function under test',\n scenarios: ['Valid input', 'Edge cases', 'Error handling'],\n };\n}\n\n/**\n * Creates an integration test template for API testing.\n */\nexport function createIntegrationTestTemplate(framework: string): GeneratedTest {\n return {\n name: 'should handle API request correctly',\n type: 'integration',\n code: `import { describe, it, expect, beforeAll, afterAll } from '${framework}';\nimport { createServer } from './server';\n\ndescribe('API Integration', () => {\n let server;\n\n beforeAll(async () => {\n server = await createServer();\n });\n\n afterAll(async () => {\n await server.close();\n });\n\n it('should return 200 for valid request', async () => {\n const response = await fetch('/api/endpoint', {\n method: 'POST',\n body: JSON.stringify({ data: 'test' }),\n });\n\n expect(response.status).toBe(200);\n const data = await response.json();\n expect(data).toMatchObject({ success: true });\n });\n});`,\n target: 'API endpoint',\n scenarios: ['Valid request', 'Error responses', 'Authentication'],\n };\n}\n\n/**\n * Creates a component test template for React components.\n */\nexport function createComponentTestTemplate(framework: string): GeneratedTest {\n return {\n name: 'should render component correctly',\n type: 'unit',\n code: `import { describe, it, expect } from '${framework}';\nimport { render, screen } from '@testing-library/react';\nimport { Component } from './Component';\n\ndescribe('Component', () => {\n it('should render with default props', () => {\n render(<Component />);\n expect(screen.getByRole('button')).toBeInTheDocument();\n });\n\n it('should handle user interaction', async () => {\n render(<Component />);\n const button = screen.getByRole('button');\n\n await userEvent.click(button);\n\n expect(screen.getByText('Clicked')).toBeInTheDocument();\n });\n});`,\n target: 'React component',\n scenarios: ['Rendering', 'User interaction', 'State changes'],\n };\n}\n\n/**\n * Creates a generic test template for general modules.\n */\nexport function createGenericTestTemplate(framework: string): GeneratedTest {\n return {\n name: 'should work as expected',\n type: 'unit',\n code: `import { describe, it, expect } from '${framework}';\n\ndescribe('Module', () => {\n it('should handle basic case', () => {\n // Arrange\n const input = {};\n\n // Act\n const result = moduleFunction(input);\n\n // Assert\n expect(result).toBeDefined();\n });\n});`,\n target: 'Module under test',\n scenarios: ['Basic functionality'],\n };\n}\n\n// ============================================================================\n// Heuristic Analysis Helpers\n// ============================================================================\n\n/**\n * Creates a heuristic coverage assessment.\n */\nexport function createHeuristicCoverage(): CoverageMetrics {\n return {\n line: 0,\n branch: 0,\n function: 0,\n statement: 0,\n uncoveredAreas: [\n 'Analysis requires actual code coverage data',\n 'Run tests with --coverage flag to collect metrics',\n ],\n };\n}\n\n/**\n * Assesses test quality using heuristic patterns.\n */\nexport function assessHeuristicQuality(description: string): TestQuality {\n const desc = description.toLowerCase();\n const issues: string[] = [];\n\n // Detect common issues from description\n if (desc.includes('flaky') || desc.includes('intermittent')) {\n issues.push('Flaky tests detected - improve test isolation');\n }\n if (desc.includes('slow') || desc.includes('timeout')) {\n issues.push('Slow tests - consider parallelization or mocking');\n }\n if (desc.includes('mock') && desc.includes('too many')) {\n issues.push('Over-mocking may indicate poor design');\n }\n\n return {\n score: issues.length === 0 ? 70 : Math.max(30, 70 - issues.length * 15),\n isolation: issues.some((i) => i.includes('isolation')) ? 'poor' : 'fair',\n assertionQuality: 'fair',\n issues: issues.length > 0 ? issues : ['Unable to assess without test code'],\n };\n}\n\n/**\n * Generates recommendations based on operation type.\n */\nexport function generateHeuristicRecommendations(\n operationType: TestingAnalysisResult['operationType']\n): string[] {\n const base = ['Follow AAA pattern', 'Test behavior, not implementation'];\n\n switch (operationType) {\n case 'generation':\n return [\n ...base,\n 'Start with happy path tests',\n 'Add edge case tests',\n 'Include error handling tests',\n ];\n case 'coverage_analysis':\n return [\n ...base,\n 'Focus on critical paths first',\n 'Use coverage as a guide, not a goal',\n 'Test boundary conditions',\n ];\n case 'quality_assessment':\n return [\n ...base,\n 'Ensure tests are independent',\n 'Use meaningful test names',\n 'Avoid testing implementation details',\n ];\n default:\n return base;\n }\n}\n\n/**\n * Detects testing warnings from description.\n */\nexport function detectTestingWarnings(description: string): string[] {\n const warnings: string[] = [];\n const desc = description.toLowerCase();\n\n if (desc.includes('database') || desc.includes('external')) {\n warnings.push('Integration tests with external dependencies need careful setup/teardown');\n }\n if (desc.includes('async') || desc.includes('promise')) {\n warnings.push('Async tests require proper await/assertion handling');\n }\n if (desc.includes('time') || desc.includes('date')) {\n warnings.push('Time-dependent tests may be flaky - consider mocking time');\n }\n if (desc.includes('random')) {\n warnings.push('Random data in tests can cause flakiness - use seeded randomness');\n }\n\n return warnings;\n}\n\n/**\n * Infers operation type from task description.\n */\nexport function inferOperationType(description: string): TestingAnalysisResult['operationType'] {\n const desc = description.toLowerCase();\n\n if (desc.includes('coverage') || desc.includes('uncovered')) {\n return 'coverage_analysis';\n }\n if (desc.includes('quality') || desc.includes('assess') || desc.includes('review test')) {\n return 'quality_assessment';\n }\n return 'generation';\n}\n","/**\n * @nexus-agents/agents - TestingExpert\n *\n * Expert agent specialized in test generation, coverage analysis,\n * and quality assurance. Uses temperature 0.3 for precise test output.\n */\n\nimport type {\n Result,\n Task,\n TaskResult,\n AgentCapability,\n CompletionRequest,\n Message,\n} from '../../core/index.js';\nimport { ok, err, AgentError } from '../../core/index.js';\nimport { BaseAgent, type BaseAgentOptions } from '../base-agent.js';\nimport {\n type ExpertOptions,\n type TestingAnalysisResult,\n type GeneratedTest,\n type CoverageMetrics,\n GeneratedTestSchema,\n CoverageMetricsSchema,\n EXPERT_DEFAULT_TEMPERATURES,\n EXPERT_DEFAULT_CAPABILITIES,\n} from './expert-types.js';\nimport { TESTING_EXPERT_SYSTEM_PROMPT } from './expert-prompts.js';\nimport {\n createUnitTestTemplate,\n createIntegrationTestTemplate,\n createComponentTestTemplate,\n createGenericTestTemplate,\n createHeuristicCoverage,\n assessHeuristicQuality,\n generateHeuristicRecommendations,\n detectTestingWarnings,\n inferOperationType,\n} from './testing-expert-helpers.js';\n\n/**\n * Configuration options for TestingExpert.\n */\nexport interface TestingExpertOptions extends ExpertOptions {\n /** Preferred testing framework */\n framework?: 'vitest' | 'jest' | 'mocha' | 'playwright' | 'cypress';\n /** Target coverage percentage */\n targetCoverage?: number;\n /** Include mocking strategies */\n includeMocking?: boolean;\n /** Test style preference */\n testStyle?: 'bdd' | 'tdd' | 'behavioral';\n /** Generate test data factories */\n generateFactories?: boolean;\n}\n\n/**\n * TestingExpert - Expert agent for testing-related tasks.\n */\nexport class TestingExpert extends BaseAgent {\n private readonly expertOptions: TestingExpertOptions;\n\n constructor(options: Partial<BaseAgentOptions> & { expertOptions?: TestingExpertOptions } = {}) {\n const expertOpts = options.expertOptions ?? {};\n const baseOptions = buildBaseOptions(options, expertOpts);\n\n super(baseOptions);\n this.expertOptions = expertOpts;\n }\n\n protected async executeTask(task: Task): Promise<Result<TaskResult, AgentError>> {\n const startTime = Date.now();\n const operationType = inferOperationType(task.description);\n\n this.logger.info('Executing testing task', {\n taskId: task.id,\n operationType,\n framework: this.expertOptions.framework,\n hasAdapter: this.adapter !== undefined,\n });\n\n if (this.adapter === undefined) {\n return this.executeHeuristic(task, operationType, startTime);\n }\n\n return this.executeWithModel(task, operationType, startTime);\n }\n\n protected buildPrompt(task: Task): Message[] {\n const contextInfo = this.buildContextInfo(task);\n\n return [\n {\n role: 'user',\n content: `${contextInfo}\n\n## Testing Task\n${task.description}\n\nAnalyze and provide testing recommendations in the specified JSON format.`,\n },\n ];\n }\n\n getExpertOptions(): Readonly<TestingExpertOptions> {\n return { ...this.expertOptions };\n }\n\n private executeHeuristic(\n task: Task,\n operationType: TestingAnalysisResult['operationType'],\n startTime: number\n ): Result<TaskResult, AgentError> {\n const tests = operationType === 'generation' ? this.generateHeuristicTests(task) : undefined;\n\n const coverage = operationType === 'coverage_analysis' ? createHeuristicCoverage() : undefined;\n\n const quality =\n operationType === 'quality_assessment' ? assessHeuristicQuality(task.description) : undefined;\n\n const result: TestingAnalysisResult = {\n content: `Heuristic testing analysis for ${operationType}. Model adapter recommended.`,\n operationType,\n tests,\n coverage,\n quality,\n recommendations: generateHeuristicRecommendations(operationType),\n warnings: detectTestingWarnings(task.description),\n confidence: 0.4,\n };\n\n return ok({\n taskId: task.id,\n output: result,\n metadata: {\n durationMs: Date.now() - startTime,\n tokensUsed: 0,\n toolsUsed: [],\n model: 'heuristic',\n },\n });\n }\n\n private async executeWithModel(\n task: Task,\n operationType: TestingAnalysisResult['operationType'],\n startTime: number\n ): Promise<Result<TaskResult, AgentError>> {\n const messages = this.buildPrompt(task);\n\n const request: CompletionRequest = {\n messages,\n systemPrompt: this.systemPrompt ?? TESTING_EXPERT_SYSTEM_PROMPT,\n temperature: this.temperature,\n maxTokens: this.maxTokens,\n };\n\n const completionResult = await this.complete(request);\n if (!completionResult.ok) {\n return err(completionResult.error);\n }\n\n const response = completionResult.value;\n const textContent = this.extractTextContent(response.content);\n const result = parseTestingResult(textContent, operationType);\n\n return ok({\n taskId: task.id,\n output: result,\n metadata: {\n durationMs: Date.now() - startTime,\n tokensUsed: response.usage.totalTokens,\n toolsUsed: [],\n model: response.model,\n },\n });\n }\n\n private buildContextInfo(task: Task): string {\n const parts: string[] = [];\n\n if (task.context.files !== undefined && task.context.files.length > 0) {\n parts.push(`Files to Test:\\n${task.context.files.map((f) => `- ${f}`).join('\\n')}`);\n }\n\n if (this.expertOptions.framework !== undefined) {\n parts.push(`Testing Framework: ${this.expertOptions.framework}`);\n }\n\n if (this.expertOptions.targetCoverage !== undefined) {\n parts.push(`Target Coverage: ${String(this.expertOptions.targetCoverage)}%`);\n }\n\n if (this.expertOptions.testStyle !== undefined) {\n parts.push(`Test Style: ${this.expertOptions.testStyle}`);\n }\n\n if (this.expertOptions.includeMocking === true) {\n parts.push('Note: Include mocking strategies');\n }\n\n if (this.expertOptions.generateFactories === true) {\n parts.push('Note: Generate test data factories');\n }\n\n return parts.length > 0 ? `## Context\\n${parts.join('\\n')}\\n` : '';\n }\n\n private generateHeuristicTests(task: Task): GeneratedTest[] {\n const tests: GeneratedTest[] = [];\n const desc = task.description.toLowerCase();\n const framework = this.expertOptions.framework ?? 'vitest';\n\n if (desc.includes('function') || desc.includes('util')) {\n tests.push(createUnitTestTemplate(framework));\n }\n\n if (desc.includes('api') || desc.includes('endpoint')) {\n tests.push(createIntegrationTestTemplate(framework));\n }\n\n if (desc.includes('component') || desc.includes('ui')) {\n tests.push(createComponentTestTemplate(framework));\n }\n\n if (tests.length === 0) {\n tests.push(createGenericTestTemplate(framework));\n }\n\n return tests;\n }\n\n private extractTextContent(content: Array<{ type: string; text?: string }>): string {\n return content\n .filter((block): block is { type: 'text'; text: string } => block.type === 'text')\n .map((block) => block.text)\n .join('\\n');\n }\n}\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\nfunction buildBaseOptions(\n options: Partial<BaseAgentOptions>,\n expertOpts: TestingExpertOptions\n): BaseAgentOptions {\n const temperature = expertOpts.temperature ?? EXPERT_DEFAULT_TEMPERATURES.testing;\n const baseCapabilities = EXPERT_DEFAULT_CAPABILITIES.testing_expert;\n const additionalCaps = expertOpts.additionalCapabilities ?? [];\n\n const baseOptions: BaseAgentOptions = {\n id: options.id ?? 'testing-expert',\n role: 'testing_expert',\n capabilities: [...baseCapabilities, ...additionalCaps] as AgentCapability[],\n temperature,\n maxTokens: options.maxTokens ?? 8192,\n systemPrompt: expertOpts.systemPromptOverride ?? TESTING_EXPERT_SYSTEM_PROMPT,\n };\n\n if (options.adapter !== undefined) baseOptions.adapter = options.adapter;\n if (options.logger !== undefined) baseOptions.logger = options.logger;\n\n return baseOptions;\n}\n\nfunction extractJsonFromText(text: string): string {\n const match = text.match(/```(?:json)?\\s*([\\s\\S]*?)```/);\n return match?.[1]?.trim() ?? text.trim();\n}\n\nfunction validateTests(tests: unknown[] | undefined): GeneratedTest[] {\n return (tests ?? [])\n .map((t) => GeneratedTestSchema.safeParse(t))\n .filter((r) => r.success)\n .map((r) => r.data as GeneratedTest);\n}\n\nfunction buildTestingResult(\n parsed: Partial<TestingAnalysisResult>,\n defaultType: TestingAnalysisResult['operationType']\n): TestingAnalysisResult {\n const validTests = validateTests(parsed.tests);\n const coverageResult = CoverageMetricsSchema.safeParse(parsed.coverage);\n\n const result: TestingAnalysisResult = {\n content: parsed.content ?? 'Testing analysis completed',\n operationType: parsed.operationType ?? defaultType,\n confidence: parsed.confidence ?? 0.7,\n };\n if (validTests.length > 0) result.tests = validTests;\n if (coverageResult.success) result.coverage = coverageResult.data as CoverageMetrics;\n if (parsed.quality !== undefined) result.quality = parsed.quality;\n if (parsed.recommendations !== undefined) result.recommendations = parsed.recommendations;\n if (parsed.warnings !== undefined) result.warnings = parsed.warnings;\n return result;\n}\n\nfunction parseTestingResult(\n text: string,\n defaultType: TestingAnalysisResult['operationType']\n): TestingAnalysisResult {\n try {\n const jsonText = extractJsonFromText(text);\n const parsed = JSON.parse(jsonText) as Partial<TestingAnalysisResult>;\n return buildTestingResult(parsed, defaultType);\n } catch {\n return { content: text, operationType: defaultType, confidence: 0.5 };\n }\n}\n\nexport function createTestingExpert(\n options?: Partial<BaseAgentOptions> & { expertOptions?: TestingExpertOptions }\n): TestingExpert {\n return new TestingExpert(options);\n}\n","/**\n * @nexus-agents/agents - DocumentationExpert Helpers\n *\n * Helper functions for the DocumentationExpert agent including\n * section generation and heuristic analysis utilities.\n */\n\nimport type { DocumentationResult, DocumentationSection } from './expert-types.js';\n\n// ============================================================================\n// Section Generation\n// ============================================================================\n\n/**\n * Generates README sections.\n */\nexport function generateReadmeSections(): DocumentationSection[] {\n return [\n { title: 'Overview', content: 'Brief description of the project and its purpose.' },\n { title: 'Installation', content: '```bash\\nnpm install package-name\\n```' },\n { title: 'Usage', content: 'Basic usage examples and quick start guide.' },\n { title: 'Configuration', content: 'Configuration options and environment variables.' },\n { title: 'API Reference', content: 'Link to detailed API documentation.' },\n { title: 'Contributing', content: 'Guidelines for contributing to the project.' },\n { title: 'License', content: 'Project license information.' },\n ];\n}\n\n/**\n * Generates API documentation sections.\n */\nexport function generateApiSections(): DocumentationSection[] {\n return [\n { title: 'API Overview', content: 'Overview of the API and its capabilities.' },\n {\n title: 'Functions',\n content: 'Detailed function documentation with parameters and return types.',\n },\n { title: 'Types', content: 'Type definitions and interfaces.' },\n { title: 'Examples', content: 'Usage examples for common scenarios.' },\n ];\n}\n\n/**\n * Generates guide sections.\n */\nexport function generateGuideSections(): DocumentationSection[] {\n return [\n { title: 'Introduction', content: 'What you will learn in this guide.' },\n { title: 'Prerequisites', content: 'Required knowledge and setup.' },\n { title: 'Step 1: Getting Started', content: 'First steps to begin.' },\n { title: 'Step 2: Implementation', content: 'Core implementation steps.' },\n { title: 'Step 3: Testing', content: 'How to verify your work.' },\n { title: 'Next Steps', content: 'Where to go from here.' },\n ];\n}\n\n/**\n * Generates reference sections.\n */\nexport function generateReferenceSections(): DocumentationSection[] {\n return [\n { title: 'Overview', content: 'Technical overview of the component.' },\n { title: 'Architecture', content: 'Architectural design and patterns.' },\n { title: 'API Reference', content: 'Complete API reference.' },\n { title: 'Configuration', content: 'All configuration options.' },\n { title: 'Troubleshooting', content: 'Common issues and solutions.' },\n ];\n}\n\n/**\n * Generates heuristic documentation sections based on type.\n */\nexport function generateHeuristicSections(\n docType: DocumentationResult['documentationType']\n): DocumentationSection[] {\n switch (docType) {\n case 'readme':\n return generateReadmeSections();\n case 'api':\n return generateApiSections();\n case 'guide':\n return generateGuideSections();\n case 'reference':\n return generateReferenceSections();\n default:\n return generateReferenceSections();\n }\n}\n\n// ============================================================================\n// Heuristic Analysis Helpers\n// ============================================================================\n\n/**\n * Generates recommendations based on documentation type.\n */\nexport function generateHeuristicRecommendations(\n docType: DocumentationResult['documentationType']\n): string[] {\n const base = ['Keep documentation up-to-date with code changes', 'Include practical examples'];\n\n switch (docType) {\n case 'readme':\n return [\n ...base,\n 'Add installation and quick start guide',\n 'Include badges for build status and coverage',\n 'Link to detailed documentation',\n ];\n case 'api':\n return [\n ...base,\n 'Document all public interfaces',\n 'Include parameter descriptions and types',\n 'Add return type documentation',\n ];\n case 'guide':\n return [\n ...base,\n 'Structure as step-by-step instructions',\n 'Include prerequisites section',\n 'Add troubleshooting tips',\n ];\n case 'reference':\n return [\n ...base,\n 'Be comprehensive but scannable',\n 'Use consistent formatting',\n 'Cross-reference related topics',\n ];\n default:\n return base;\n }\n}\n\n/**\n * Detects documentation warnings from description.\n */\nexport function detectDocumentationWarnings(description: string): string[] {\n const warnings: string[] = [];\n const desc = description.toLowerCase();\n\n if (desc.includes('internal') || desc.includes('private')) {\n warnings.push('Document internal APIs carefully - they may change');\n }\n if (desc.includes('deprecated')) {\n warnings.push('Mark deprecated features clearly with migration paths');\n }\n if (desc.includes('beta') || desc.includes('experimental')) {\n warnings.push('Flag experimental features with stability warnings');\n }\n if (desc.includes('security')) {\n warnings.push('Security-related docs need careful review');\n }\n\n return warnings;\n}\n\n/**\n * Infers documentation type from task description.\n */\nexport function inferDocumentationType(\n description: string\n): DocumentationResult['documentationType'] {\n const desc = description.toLowerCase();\n\n if (desc.includes('api') || desc.includes('endpoint') || desc.includes('function doc')) {\n return 'api';\n }\n if (desc.includes('readme') || desc.includes('project doc')) {\n return 'readme';\n }\n if (desc.includes('guide') || desc.includes('tutorial') || desc.includes('how to')) {\n return 'guide';\n }\n return 'reference';\n}\n\n// ============================================================================\n// Content Generation\n// ============================================================================\n\ninterface ContentGenerationOptions {\n includeBadges?: boolean | undefined;\n generateTOC?: boolean | undefined;\n}\n\n/**\n * Generates heuristic content for documentation.\n */\nexport function generateHeuristicContent(\n docType: DocumentationResult['documentationType'],\n sections: DocumentationSection[],\n options: ContentGenerationOptions\n): string {\n const parts: string[] = [];\n\n // Add badges for README if enabled\n if (docType === 'readme' && options.includeBadges === true) {\n parts.push('');\n parts.push('');\n parts.push('');\n }\n\n // Add TOC if enabled\n if (options.generateTOC === true) {\n parts.push('## Table of Contents\\n');\n for (const section of sections) {\n const anchor = section.title.toLowerCase().replace(/\\s+/g, '-');\n parts.push(`- [${section.title}](#${anchor})`);\n }\n parts.push('');\n }\n\n // Add note about heuristic generation\n parts.push(\n '> Note: This is a template. Model adapter required for detailed content generation.\\n'\n );\n\n // Add sections\n for (const section of sections) {\n parts.push(`## ${section.title}\\n`);\n parts.push(section.content);\n parts.push('');\n }\n\n return parts.join('\\n');\n}\n","/**\n * @nexus-agents/agents - DocumentationExpert\n *\n * Expert agent specialized in documentation generation, API documentation,\n * and README creation. Uses temperature 0.4 for clear yet engaging content.\n */\n\nimport type {\n Result,\n Task,\n TaskResult,\n AgentCapability,\n CompletionRequest,\n Message,\n} from '../../core/index.js';\nimport { ok, err, AgentError } from '../../core/index.js';\nimport { BaseAgent, type BaseAgentOptions } from '../base-agent.js';\nimport {\n type ExpertOptions,\n type DocumentationResult,\n EXPERT_DEFAULT_TEMPERATURES,\n EXPERT_DEFAULT_CAPABILITIES,\n} from './expert-types.js';\nimport { DOCUMENTATION_EXPERT_SYSTEM_PROMPT } from './expert-prompts.js';\nimport {\n generateHeuristicSections,\n generateHeuristicContent,\n generateHeuristicRecommendations,\n detectDocumentationWarnings,\n inferDocumentationType,\n} from './documentation-expert-helpers.js';\n\n/**\n * Configuration options for DocumentationExpert.\n */\nexport interface DocumentationExpertOptions extends ExpertOptions {\n /** Documentation format */\n format?: 'markdown' | 'jsdoc' | 'tsdoc' | 'rst';\n /** Include code examples */\n includeExamples?: boolean;\n /** Target audience level */\n audienceLevel?: 'beginner' | 'intermediate' | 'advanced';\n /** Generate table of contents */\n generateTOC?: boolean;\n /** Include badges in README */\n includeBadges?: boolean;\n}\n\n/**\n * DocumentationExpert - Expert agent for documentation-related tasks.\n */\nexport class DocumentationExpert extends BaseAgent {\n private readonly expertOptions: DocumentationExpertOptions;\n\n constructor(\n options: Partial<BaseAgentOptions> & { expertOptions?: DocumentationExpertOptions } = {}\n ) {\n const expertOpts = options.expertOptions ?? {};\n const baseOptions = buildBaseOptions(options, expertOpts);\n\n super(baseOptions);\n this.expertOptions = expertOpts;\n }\n\n protected async executeTask(task: Task): Promise<Result<TaskResult, AgentError>> {\n const startTime = Date.now();\n const docType = inferDocumentationType(task.description);\n\n this.logger.info('Executing documentation task', {\n taskId: task.id,\n documentationType: docType,\n format: this.expertOptions.format,\n hasAdapter: this.adapter !== undefined,\n });\n\n if (this.adapter === undefined) {\n return this.executeHeuristic(task, docType, startTime);\n }\n\n return this.executeWithModel(task, docType, startTime);\n }\n\n protected buildPrompt(task: Task): Message[] {\n const contextInfo = this.buildContextInfo(task);\n\n return [\n {\n role: 'user',\n content: `${contextInfo}\n\n## Documentation Task\n${task.description}\n\nGenerate documentation in the specified JSON format.`,\n },\n ];\n }\n\n getExpertOptions(): Readonly<DocumentationExpertOptions> {\n return { ...this.expertOptions };\n }\n\n private executeHeuristic(\n task: Task,\n docType: DocumentationResult['documentationType'],\n startTime: number\n ): Result<TaskResult, AgentError> {\n const sections = generateHeuristicSections(docType);\n const content = generateHeuristicContent(docType, sections, {\n includeBadges: this.expertOptions.includeBadges,\n generateTOC: this.expertOptions.generateTOC,\n });\n\n const result: DocumentationResult = {\n content,\n documentationType: docType,\n sections,\n recommendations: generateHeuristicRecommendations(docType),\n warnings: detectDocumentationWarnings(task.description),\n confidence: 0.4,\n };\n\n return ok({\n taskId: task.id,\n output: result,\n metadata: {\n durationMs: Date.now() - startTime,\n tokensUsed: 0,\n toolsUsed: [],\n model: 'heuristic',\n },\n });\n }\n\n private async executeWithModel(\n task: Task,\n docType: DocumentationResult['documentationType'],\n startTime: number\n ): Promise<Result<TaskResult, AgentError>> {\n const messages = this.buildPrompt(task);\n\n const request: CompletionRequest = {\n messages,\n systemPrompt: this.systemPrompt ?? DOCUMENTATION_EXPERT_SYSTEM_PROMPT,\n temperature: this.temperature,\n maxTokens: this.maxTokens,\n };\n\n const completionResult = await this.complete(request);\n if (!completionResult.ok) {\n return err(completionResult.error);\n }\n\n const response = completionResult.value;\n const textContent = this.extractTextContent(response.content);\n const result = parseDocumentationResult(textContent, docType);\n\n return ok({\n taskId: task.id,\n output: result,\n metadata: {\n durationMs: Date.now() - startTime,\n tokensUsed: response.usage.totalTokens,\n toolsUsed: [],\n model: response.model,\n },\n });\n }\n\n private buildContextInfo(task: Task): string {\n const parts: string[] = [];\n\n if (task.context.workingDirectory !== undefined) {\n parts.push(`Project: ${task.context.workingDirectory}`);\n }\n\n if (task.context.files !== undefined && task.context.files.length > 0) {\n parts.push(`Files to Document:\\n${task.context.files.map((f) => `- ${f}`).join('\\n')}`);\n }\n\n if (this.expertOptions.format !== undefined) {\n parts.push(`Format: ${this.expertOptions.format}`);\n }\n\n if (this.expertOptions.audienceLevel !== undefined) {\n parts.push(`Target Audience: ${this.expertOptions.audienceLevel}`);\n }\n\n if (this.expertOptions.includeExamples === true) {\n parts.push('Note: Include code examples');\n }\n\n if (this.expertOptions.generateTOC === true) {\n parts.push('Note: Generate table of contents');\n }\n\n if (this.expertOptions.includeBadges === true) {\n parts.push('Note: Include badges for README');\n }\n\n return parts.length > 0 ? `## Context\\n${parts.join('\\n')}\\n` : '';\n }\n\n private extractTextContent(content: Array<{ type: string; text?: string }>): string {\n return content\n .filter((block): block is { type: 'text'; text: string } => block.type === 'text')\n .map((block) => block.text)\n .join('\\n');\n }\n}\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\nfunction buildBaseOptions(\n options: Partial<BaseAgentOptions>,\n expertOpts: DocumentationExpertOptions\n): BaseAgentOptions {\n const temperature = expertOpts.temperature ?? EXPERT_DEFAULT_TEMPERATURES.documentation;\n const baseCapabilities = EXPERT_DEFAULT_CAPABILITIES.documentation_expert;\n const additionalCaps = expertOpts.additionalCapabilities ?? [];\n\n const baseOptions: BaseAgentOptions = {\n id: options.id ?? 'documentation-expert',\n role: 'documentation_expert',\n capabilities: [...baseCapabilities, ...additionalCaps] as AgentCapability[],\n temperature,\n maxTokens: options.maxTokens ?? 8192,\n systemPrompt: expertOpts.systemPromptOverride ?? DOCUMENTATION_EXPERT_SYSTEM_PROMPT,\n };\n\n if (options.adapter !== undefined) baseOptions.adapter = options.adapter;\n if (options.logger !== undefined) baseOptions.logger = options.logger;\n\n return baseOptions;\n}\n\nfunction extractJsonFromText(text: string): string {\n const match = text.match(/```(?:json)?\\s*([\\s\\S]*?)```/);\n if (match?.[1] !== undefined) {\n return match[1].trim();\n }\n return text.trim();\n}\n\nfunction parseDocumentationResult(\n text: string,\n defaultType: DocumentationResult['documentationType']\n): DocumentationResult {\n try {\n const jsonText = extractJsonFromText(text);\n const parsed = JSON.parse(jsonText) as Partial<DocumentationResult>;\n\n const result: DocumentationResult = {\n content: parsed.content ?? 'Documentation generated',\n documentationType: parsed.documentationType ?? defaultType,\n confidence: parsed.confidence ?? 0.7,\n };\n if (parsed.sections !== undefined) result.sections = parsed.sections;\n if (parsed.apiDocs !== undefined) result.apiDocs = parsed.apiDocs;\n if (parsed.recommendations !== undefined) result.recommendations = parsed.recommendations;\n if (parsed.warnings !== undefined) result.warnings = parsed.warnings;\n return result;\n } catch {\n return { content: text, documentationType: defaultType, confidence: 0.5 };\n }\n}\n\nexport function createDocumentationExpert(\n options?: Partial<BaseAgentOptions> & { expertOptions?: DocumentationExpertOptions }\n): DocumentationExpert {\n return new DocumentationExpert(options);\n}\n","/**\n * @nexus-agents/agents - Expert Configuration\n *\n * Configuration schema and types for dynamically creating expert agents.\n * Experts are specialized agents with specific capabilities and prompts.\n */\n\nimport { z } from 'zod';\nimport type { AgentRole, AgentCapability } from '../../core/index.js';\n\n/**\n * Model preference configuration for an expert.\n */\nexport interface ModelPreference {\n /** Provider ID (e.g., 'anthropic', 'openai') */\n provider?: string;\n /** Specific model ID */\n modelId?: string;\n /** Temperature for generation (0.0 - 2.0) */\n temperature?: number;\n /** Maximum tokens for responses */\n maxTokens?: number;\n}\n\n/**\n * Configuration for creating a dynamic expert agent.\n */\nexport interface ExpertConfig {\n /** Unique identifier for this expert */\n id: string;\n /** Human-readable name */\n name: string;\n /** Role classification */\n role: AgentRole;\n /** System prompt defining the expert's behavior */\n systemPrompt: string;\n /** List of capabilities this expert has */\n capabilities: AgentCapability[];\n /** Optional model preferences */\n modelPreference?: ModelPreference;\n /** Optional metadata for extensions */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Built-in expert type identifiers.\n */\nexport type BuiltInExpertType = 'code' | 'architecture' | 'security' | 'documentation' | 'testing';\n\n/**\n * Zod schema for ModelPreference.\n */\nexport const ModelPreferenceSchema = z.object({\n provider: z.string().min(1).optional(),\n modelId: z.string().min(1).optional(),\n temperature: z.number().min(0).max(2).optional(),\n maxTokens: z.number().min(1).max(200000).optional(),\n});\n\n/**\n * Zod schema for AgentRole enum values.\n */\nconst AgentRoleSchema = z.enum([\n 'tech_lead',\n 'code_expert',\n 'architecture_expert',\n 'security_expert',\n 'documentation_expert',\n 'testing_expert',\n 'custom',\n]);\n\n/**\n * Zod schema for AgentCapability enum values.\n */\nconst AgentCapabilitySchema = z.enum([\n 'task_execution',\n 'delegation',\n 'collaboration',\n 'tool_use',\n 'code_generation',\n 'code_review',\n 'research',\n]);\n\n/**\n * Zod schema for ExpertConfig.\n */\nexport const ExpertConfigSchema = z.object({\n id: z.string().min(1, 'Expert ID is required'),\n name: z.string().min(1, 'Expert name is required'),\n role: AgentRoleSchema,\n systemPrompt: z.string().min(1, 'System prompt is required'),\n capabilities: z.array(AgentCapabilitySchema).min(1, 'At least one capability required'),\n modelPreference: ModelPreferenceSchema.optional(),\n metadata: z.record(z.unknown()).optional(),\n});\n\n/**\n * Zod schema for BuiltInExpertType.\n */\nexport const BuiltInExpertTypeSchema = z.enum([\n 'code',\n 'architecture',\n 'security',\n 'documentation',\n 'testing',\n]);\n\n/**\n * Built-in expert configurations.\n * These provide sensible defaults for common expert types.\n */\nexport const BUILT_IN_EXPERTS: Readonly<Record<BuiltInExpertType, ExpertConfig>> = {\n code: {\n id: 'code-expert',\n name: 'Code Expert',\n role: 'code_expert',\n systemPrompt: `You are a senior software engineer specialized in writing clean, maintainable, and efficient code.\n\n## Core Responsibilities\n1. Write production-quality code that meets requirements\n2. Follow best practices and design patterns\n3. Implement robust error handling\n4. Optimize performance while maintaining readability\n\n## Guidelines\n- Use clear, descriptive naming conventions\n- Apply SOLID principles when designing classes\n- Write self-documenting code with comments for complex logic\n- Keep functions small and focused (single responsibility)\n- Validate all inputs at boundaries\n- Handle errors explicitly with proper error types\n\n## Output Format\nWhen providing code:\n1. Include necessary imports\n2. Add JSDoc comments for public APIs\n3. Handle edge cases explicitly\n4. Provide brief explanation of key decisions`,\n capabilities: ['task_execution', 'code_generation', 'code_review', 'tool_use'],\n modelPreference: {\n temperature: 0.2,\n },\n },\n\n architecture: {\n id: 'architecture-expert',\n name: 'Architecture Expert',\n role: 'architecture_expert',\n systemPrompt: `You are a software architect specialized in system design and architectural decisions.\n\n## Core Responsibilities\n1. Design scalable and maintainable system architectures\n2. Make informed technology and pattern choices\n3. Document architectural decisions (ADRs)\n4. Guide teams on best practices\n\n## Guidelines\n- Consider trade-offs explicitly (CAP, latency vs throughput)\n- Design for change and extensibility\n- Apply appropriate patterns (microservices, event-driven, etc.)\n- Consider operational aspects (monitoring, scaling, deployment)\n- Document assumptions and constraints\n\n## Output Format\nWhen providing architectural guidance:\n1. State the problem/context clearly\n2. List options considered with trade-offs\n3. Recommend a solution with rationale\n4. Note implementation considerations`,\n capabilities: ['task_execution', 'research', 'collaboration'],\n modelPreference: {\n temperature: 0.3,\n },\n },\n\n security: {\n id: 'security-expert',\n name: 'Security Expert',\n role: 'security_expert',\n systemPrompt: `You are a security engineer specialized in application and infrastructure security.\n\n## Core Responsibilities\n1. Identify security vulnerabilities and risks\n2. Review code for security issues\n3. Recommend security controls and mitigations\n4. Guide secure development practices\n\n## Guidelines\n- Reference OWASP Top 10 and CWE when applicable\n- Consider attack vectors and threat models\n- Prioritize risks by severity and likelihood\n- Provide actionable remediation steps\n- Never expose sensitive information in examples\n\n## Output Format\nWhen providing security guidance:\n1. Describe the vulnerability/risk\n2. Explain potential impact\n3. Provide remediation steps\n4. Reference relevant standards (OWASP, CWE, etc.)`,\n capabilities: ['task_execution', 'code_review', 'research'],\n modelPreference: {\n temperature: 0.1,\n },\n },\n\n documentation: {\n id: 'documentation-expert',\n name: 'Documentation Expert',\n role: 'documentation_expert',\n systemPrompt: `You are a technical writer specialized in creating clear, comprehensive documentation.\n\n## Core Responsibilities\n1. Write clear and accurate documentation\n2. Create API documentation and guides\n3. Document architecture and design decisions\n4. Maintain consistency across documentation\n\n## Guidelines\n- Write for the target audience (developers, users, operators)\n- Use clear, concise language\n- Include practical examples\n- Structure content logically with headings\n- Keep documentation up-to-date with code\n\n## Output Format\nWhen providing documentation:\n1. Use appropriate markdown formatting\n2. Include code examples where helpful\n3. Add cross-references to related docs\n4. Note any prerequisites or assumptions`,\n capabilities: ['task_execution', 'research'],\n modelPreference: {\n temperature: 0.4,\n },\n },\n\n testing: {\n id: 'testing-expert',\n name: 'Testing Expert',\n role: 'testing_expert',\n systemPrompt: `You are a QA engineer specialized in testing strategies and test implementation.\n\n## Core Responsibilities\n1. Design comprehensive test strategies\n2. Write unit, integration, and e2e tests\n3. Identify edge cases and failure scenarios\n4. Improve test coverage and reliability\n\n## Guidelines\n- Follow the testing pyramid (unit > integration > e2e)\n- Test behavior, not implementation details\n- Use meaningful test descriptions (given/when/then)\n- Mock external dependencies appropriately\n- Cover error cases and edge conditions\n\n## Output Format\nWhen providing tests:\n1. Include arrange/act/assert structure\n2. Use descriptive test names\n3. Cover happy path and error cases\n4. Note any test fixtures or setup needed`,\n capabilities: ['task_execution', 'code_generation', 'tool_use'],\n modelPreference: {\n temperature: 0.2,\n },\n },\n};\n\n/**\n * Maps built-in expert types to their AgentRole.\n */\nexport const EXPERT_TYPE_TO_ROLE: Readonly<Record<BuiltInExpertType, AgentRole>> = {\n code: 'code_expert',\n architecture: 'architecture_expert',\n security: 'security_expert',\n documentation: 'documentation_expert',\n testing: 'testing_expert',\n};\n\n/**\n * Validates an expert configuration.\n * @param config - Configuration to validate\n * @returns Parsed config or throws on validation error\n */\nexport function validateExpertConfig(config: unknown): ExpertConfig {\n return ExpertConfigSchema.parse(config) as ExpertConfig;\n}\n\n/**\n * Safely validates an expert configuration.\n * @param config - Configuration to validate\n * @returns Safe parse result with success/error\n */\nexport function safeValidateExpertConfig(\n config: unknown\n): { success: true; data: ExpertConfig } | { success: false; error: z.ZodError } {\n const result = ExpertConfigSchema.safeParse(config);\n if (result.success) {\n return { success: true, data: result.data as ExpertConfig };\n }\n return { success: false, error: result.error };\n}\n","/**\n * @nexus-agents/agents - Expert Factory\n *\n * Factory for creating expert agents from configuration.\n * Supports both built-in expert types and custom configurations.\n */\n\nimport type { Result, IModelAdapter, AgentCapability } from '../../core/index.js';\nimport { ok, err, AgentError } from '../../core/index.js';\nimport { SimpleAgent } from '../simple-agent.js';\nimport type { BaseAgentOptions } from '../base-agent.js';\nimport {\n type ExpertConfig,\n type BuiltInExpertType,\n type ModelPreference,\n ExpertConfigSchema,\n BuiltInExpertTypeSchema,\n BUILT_IN_EXPERTS,\n} from './expert-config.js';\n\n/**\n * Error specific to factory operations.\n */\nexport class FactoryError extends AgentError {\n constructor(message: string, options?: { cause?: Error; context?: Record<string, unknown> }) {\n super(message, options);\n this.name = 'FactoryError';\n }\n}\n\n/**\n * Options for creating an expert.\n */\nexport interface CreateExpertOptions {\n /** Model adapter to use */\n adapter?: IModelAdapter;\n /** Override model preferences from config */\n modelOverrides?: Partial<ModelPreference>;\n /** Additional capabilities to add */\n additionalCapabilities?: AgentCapability[];\n}\n\n/**\n * Expert agent extending SimpleAgent with configuration-based setup.\n */\nexport class Expert extends SimpleAgent {\n readonly expertConfig: ExpertConfig;\n\n constructor(options: BaseAgentOptions, config: ExpertConfig) {\n super(options);\n this.expertConfig = config;\n }\n\n /**\n * Get the expert's name.\n */\n get name(): string {\n return this.expertConfig.name;\n }\n\n /**\n * Get the expert's metadata.\n */\n get metadata(): Record<string, unknown> | undefined {\n return this.expertConfig.metadata;\n }\n}\n\n/**\n * Build validation error message from Zod issues.\n */\nfunction buildValidationError(issues: { path: (string | number)[]; message: string }[]): string {\n return issues.map((issue) => `${issue.path.join('.')}: ${issue.message}`).join('; ');\n}\n\n/**\n * Default values for model preferences.\n */\nconst DEFAULT_TEMPERATURE = 0.3;\nconst DEFAULT_MAX_TOKENS = 4096;\n\n/**\n * Merge capabilities from config and options.\n */\nfunction mergeCapabilities(\n configCaps: AgentCapability[],\n additionalCaps?: AgentCapability[]\n): AgentCapability[] {\n if (additionalCaps === undefined) {\n return configCaps;\n }\n return [...configCaps, ...additionalCaps];\n}\n\n/**\n * Resolve temperature from overrides, config, or default.\n */\nfunction resolveTemperature(\n overrides?: Partial<ModelPreference>,\n configPreference?: ModelPreference\n): number {\n return overrides?.temperature ?? configPreference?.temperature ?? DEFAULT_TEMPERATURE;\n}\n\n/**\n * Resolve maxTokens from overrides, config, or default.\n */\nfunction resolveMaxTokens(\n overrides?: Partial<ModelPreference>,\n configPreference?: ModelPreference\n): number {\n return overrides?.maxTokens ?? configPreference?.maxTokens ?? DEFAULT_MAX_TOKENS;\n}\n\n/**\n * Build agent options from validated config.\n */\nfunction buildAgentOptions(\n validConfig: ExpertConfig,\n options?: CreateExpertOptions\n): BaseAgentOptions {\n const capabilities = mergeCapabilities(validConfig.capabilities, options?.additionalCapabilities);\n\n const baseOptions: BaseAgentOptions = {\n id: validConfig.id,\n role: validConfig.role,\n capabilities: capabilities as readonly AgentCapability[],\n systemPrompt: validConfig.systemPrompt,\n temperature: resolveTemperature(options?.modelOverrides, validConfig.modelPreference),\n maxTokens: resolveMaxTokens(options?.modelOverrides, validConfig.modelPreference),\n };\n\n if (options?.adapter !== undefined) {\n baseOptions.adapter = options.adapter;\n }\n\n return baseOptions;\n}\n\n/**\n * Copy a built-in config to avoid mutation.\n */\nfunction copyBuiltInConfig(type: BuiltInExpertType): ExpertConfig {\n const builtInConfig = BUILT_IN_EXPERTS[type];\n const config: ExpertConfig = {\n ...builtInConfig,\n capabilities: [...builtInConfig.capabilities],\n };\n if (builtInConfig.modelPreference !== undefined) {\n config.modelPreference = { ...builtInConfig.modelPreference };\n }\n return config;\n}\n\n/**\n * Create an expert agent from a configuration object.\n *\n * @param config - Expert configuration\n * @param options - Creation options including adapter\n * @returns Result with Expert or FactoryError\n */\nexport function createExpert(\n config: ExpertConfig,\n options?: CreateExpertOptions\n): Result<Expert, FactoryError> {\n const validationResult = ExpertConfigSchema.safeParse(config);\n\n if (!validationResult.success) {\n const issues = buildValidationError(validationResult.error.issues);\n return err(\n new FactoryError(`Invalid expert configuration: ${issues}`, {\n context: { configId: config.id, validationErrors: validationResult.error.issues },\n })\n );\n }\n\n const validConfig = validationResult.data as ExpertConfig;\n const agentOptions = buildAgentOptions(validConfig, options);\n\n try {\n const expert = new Expert(agentOptions, validConfig);\n return ok(expert);\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error';\n const errorOptions: { cause?: Error; context: Record<string, unknown> } = {\n context: { configId: validConfig.id },\n };\n if (error instanceof Error) {\n errorOptions.cause = error;\n }\n return err(new FactoryError(`Failed to create expert: ${message}`, errorOptions));\n }\n}\n\n/**\n * Create a built-in expert by type.\n *\n * Built-in types include: 'code', 'architecture', 'security',\n * 'documentation', and 'testing'.\n *\n * @param type - Built-in expert type\n * @param options - Creation options including adapter\n * @returns Result with Expert or FactoryError\n */\nexport function createBuiltInExpert(\n type: BuiltInExpertType,\n options?: CreateExpertOptions\n): Result<Expert, FactoryError> {\n const typeValidation = BuiltInExpertTypeSchema.safeParse(type);\n\n if (!typeValidation.success) {\n const typeStr = typeof type === 'string' ? type : 'unknown';\n return err(\n new FactoryError(`Invalid built-in expert type: ${typeStr}`, {\n context: {\n providedType: type,\n validTypes: ['code', 'architecture', 'security', 'documentation', 'testing'],\n },\n })\n );\n }\n\n const config = copyBuiltInConfig(type);\n return createExpert(config, options);\n}\n\n/**\n * Create multiple experts from configurations.\n *\n * @param configs - Array of expert configurations\n * @param options - Creation options applied to all experts\n * @returns Result with array of Experts or first FactoryError\n */\nexport function createManyExperts(\n configs: ExpertConfig[],\n options?: CreateExpertOptions\n): Result<Expert[], FactoryError> {\n const experts: Expert[] = [];\n\n for (const config of configs) {\n const result = createExpert(config, options);\n if (!result.ok) {\n return result as Result<never, FactoryError>;\n }\n experts.push(result.value);\n }\n\n return ok(experts);\n}\n\n/**\n * Create all built-in experts.\n *\n * @param options - Creation options applied to all experts\n * @returns Result with array of all built-in Experts\n */\nexport function createAllBuiltInExperts(\n options?: CreateExpertOptions\n): Result<Expert[], FactoryError> {\n const types: BuiltInExpertType[] = [\n 'code',\n 'architecture',\n 'security',\n 'documentation',\n 'testing',\n ];\n\n const experts: Expert[] = [];\n\n for (const type of types) {\n const result = createBuiltInExpert(type, options);\n if (!result.ok) {\n return result as Result<never, FactoryError>;\n }\n experts.push(result.value);\n }\n\n return ok(experts);\n}\n\n/**\n * Validate a configuration without creating an expert.\n *\n * @param config - Configuration to validate\n * @returns Result with validated config or FactoryError\n */\nexport function validateExpertConfigStrict(config: unknown): Result<ExpertConfig, FactoryError> {\n const result = ExpertConfigSchema.safeParse(config);\n\n if (!result.success) {\n const issues = buildValidationError(result.error.issues);\n return err(\n new FactoryError(`Invalid expert configuration: ${issues}`, {\n context: { validationErrors: result.error.issues },\n })\n );\n }\n\n return ok(result.data as ExpertConfig);\n}\n\n/**\n * Get the configuration for a built-in expert type.\n *\n * @param type - Built-in expert type\n * @returns Result with config or FactoryError if type invalid\n */\nexport function getBuiltInExpertConfig(\n type: BuiltInExpertType\n): Result<ExpertConfig, FactoryError> {\n const typeValidation = BuiltInExpertTypeSchema.safeParse(type);\n\n if (!typeValidation.success) {\n const typeStr = typeof type === 'string' ? type : 'unknown';\n return err(\n new FactoryError(`Invalid built-in expert type: ${typeStr}`, {\n context: {\n providedType: type,\n validTypes: ['code', 'architecture', 'security', 'documentation', 'testing'],\n },\n })\n );\n }\n\n return ok(copyBuiltInConfig(type));\n}\n\n/**\n * Factory namespace for creating expert agents.\n * Provides static methods for backward compatibility.\n */\nexport const ExpertFactory = {\n create: createExpert,\n createBuiltIn: createBuiltInExpert,\n createMany: createManyExperts,\n createAllBuiltIn: createAllBuiltInExperts,\n validate: validateExpertConfigStrict,\n getBuiltInConfig: getBuiltInExpertConfig,\n} as const;\n","/**\n * @nexus-agents/agents - Expert Registry\n *\n * Singleton registry for managing expert agents.\n * Provides registration, lookup, and query capabilities.\n */\n\nimport type { Result, AgentCapability } from '../../core/index.js';\nimport { ok, err, AgentError } from '../../core/index.js';\nimport type { Expert } from './expert-factory.js';\n\n/**\n * Error specific to registry operations.\n */\nexport class RegistryError extends AgentError {\n constructor(message: string, options?: { cause?: Error; context?: Record<string, unknown> }) {\n super(message, options);\n this.name = 'RegistryError';\n }\n}\n\n/**\n * Options for registering an expert.\n */\nexport interface RegisterOptions {\n /** Whether to replace if expert with same ID exists */\n replace?: boolean;\n}\n\n/**\n * Query options for finding experts.\n */\nexport interface QueryOptions {\n /** Filter by role */\n role?: string;\n /** Filter by capability (expert must have all specified) */\n capabilities?: AgentCapability[];\n /** Filter by capability (expert must have at least one) */\n anyCapability?: AgentCapability[];\n /** Maximum number of results */\n limit?: number;\n}\n\n/**\n * Statistics about the registry.\n */\nexport interface RegistryStats {\n /** Total number of registered experts */\n totalExperts: number;\n /** Count by role */\n byRole: Record<string, number>;\n /** Count by capability */\n byCapability: Record<string, number>;\n}\n\n/**\n * Singleton registry for managing expert agents.\n *\n * Provides thread-safe registration and lookup of experts.\n * Supports querying by ID, role, and capabilities.\n */\nexport class ExpertRegistry {\n private static instance: ExpertRegistry | undefined;\n private readonly experts: Map<string, Expert>;\n\n private constructor() {\n this.experts = new Map();\n }\n\n /**\n * Get the singleton instance.\n */\n static getInstance(): ExpertRegistry {\n ExpertRegistry.instance ??= new ExpertRegistry();\n return ExpertRegistry.instance;\n }\n\n /**\n * Reset the singleton instance (for testing).\n */\n static resetInstance(): void {\n if (ExpertRegistry.instance !== undefined) {\n ExpertRegistry.instance.clear();\n ExpertRegistry.instance = undefined;\n }\n }\n\n /**\n * Register an expert in the registry.\n *\n * @param expert - Expert to register\n * @param options - Registration options\n * @returns Result with void or RegistryError\n */\n register(expert: Expert, options?: RegisterOptions): Result<void, RegistryError> {\n const existingExpert = this.experts.get(expert.id);\n\n if (existingExpert !== undefined && options?.replace !== true) {\n return err(\n new RegistryError(`Expert with ID '${expert.id}' already registered`, {\n context: {\n existingId: existingExpert.id,\n existingName: existingExpert.name,\n },\n })\n );\n }\n\n this.experts.set(expert.id, expert);\n return ok(undefined);\n }\n\n /**\n * Register multiple experts.\n *\n * @param experts - Experts to register\n * @param options - Registration options\n * @returns Result with void or first RegistryError\n */\n registerMany(experts: Expert[], options?: RegisterOptions): Result<void, RegistryError> {\n for (const expert of experts) {\n const result = this.register(expert, options);\n if (!result.ok) {\n return result;\n }\n }\n return ok(undefined);\n }\n\n /**\n * Unregister an expert by ID.\n *\n * @param id - Expert ID to unregister\n * @returns Result with the removed Expert or RegistryError\n */\n unregister(id: string): Result<Expert, RegistryError> {\n const expert = this.experts.get(id);\n\n if (expert === undefined) {\n return err(\n new RegistryError(`Expert with ID '${id}' not found`, {\n context: { requestedId: id },\n })\n );\n }\n\n this.experts.delete(id);\n return ok(expert);\n }\n\n /**\n * Get an expert by ID.\n *\n * @param id - Expert ID to retrieve\n * @returns Result with Expert or RegistryError\n */\n get(id: string): Result<Expert, RegistryError> {\n const expert = this.experts.get(id);\n\n if (expert === undefined) {\n return err(\n new RegistryError(`Expert with ID '${id}' not found`, {\n context: {\n requestedId: id,\n availableIds: Array.from(this.experts.keys()),\n },\n })\n );\n }\n\n return ok(expert);\n }\n\n /**\n * Check if an expert is registered.\n *\n * @param id - Expert ID to check\n * @returns True if expert is registered\n */\n has(id: string): boolean {\n return this.experts.has(id);\n }\n\n /**\n * Get experts by capability.\n *\n * Returns all experts that have the specified capability.\n *\n * @param capability - Capability to search for\n * @returns Array of matching experts\n */\n getByCapability(capability: AgentCapability): Expert[] {\n return Array.from(this.experts.values()).filter((expert) =>\n expert.capabilities.includes(capability)\n );\n }\n\n /**\n * Get experts by role.\n *\n * @param role - Role to search for\n * @returns Array of matching experts\n */\n getByRole(role: string): Expert[] {\n return Array.from(this.experts.values()).filter((expert) => expert.role === role);\n }\n\n /**\n * Query experts with multiple criteria.\n *\n * @param options - Query options\n * @returns Array of matching experts\n */\n query(options: QueryOptions): Expert[] {\n let results = Array.from(this.experts.values());\n\n // Filter by role\n if (options.role !== undefined) {\n results = results.filter((expert) => expert.role === options.role);\n }\n\n // Filter by all capabilities\n if (options.capabilities !== undefined && options.capabilities.length > 0) {\n const requiredCaps = options.capabilities;\n results = results.filter((expert) =>\n requiredCaps.every((cap) => expert.capabilities.includes(cap))\n );\n }\n\n // Filter by any capability\n if (options.anyCapability !== undefined && options.anyCapability.length > 0) {\n const anyCaps = options.anyCapability;\n results = results.filter((expert) =>\n anyCaps.some((cap) => expert.capabilities.includes(cap))\n );\n }\n\n // Apply limit\n if (options.limit !== undefined && options.limit > 0) {\n results = results.slice(0, options.limit);\n }\n\n return results;\n }\n\n /**\n * List all registered experts.\n *\n * @returns Array of all registered experts\n */\n list(): Expert[] {\n return Array.from(this.experts.values());\n }\n\n /**\n * List all registered expert IDs.\n *\n * @returns Array of all registered expert IDs\n */\n listIds(): string[] {\n return Array.from(this.experts.keys());\n }\n\n /**\n * Get the number of registered experts.\n */\n get size(): number {\n return this.experts.size;\n }\n\n /**\n * Check if the registry is empty.\n */\n get isEmpty(): boolean {\n return this.experts.size === 0;\n }\n\n /**\n * Clear all registered experts.\n */\n clear(): void {\n this.experts.clear();\n }\n\n /**\n * Get statistics about the registry.\n */\n getStats(): RegistryStats {\n const byRole: Record<string, number> = {};\n const byCapability: Record<string, number> = {};\n\n for (const expert of this.experts.values()) {\n // Count by role\n byRole[expert.role] = (byRole[expert.role] ?? 0) + 1;\n\n // Count by capability\n for (const capability of expert.capabilities) {\n byCapability[capability] = (byCapability[capability] ?? 0) + 1;\n }\n }\n\n return {\n totalExperts: this.experts.size,\n byRole,\n byCapability,\n };\n }\n\n /**\n * Find the best expert for a set of required capabilities.\n *\n * Returns the expert that matches the most capabilities.\n *\n * @param requiredCapabilities - Capabilities needed\n * @returns Result with best Expert or RegistryError if none found\n */\n findBestMatch(requiredCapabilities: AgentCapability[]): Result<Expert, RegistryError> {\n if (this.isEmpty) {\n return err(\n new RegistryError('No experts registered', {\n context: { requiredCapabilities },\n })\n );\n }\n\n let bestExpert: Expert | undefined;\n let bestScore = -1;\n\n for (const expert of this.experts.values()) {\n const score = requiredCapabilities.filter((cap) => expert.capabilities.includes(cap)).length;\n\n if (score > bestScore) {\n bestScore = score;\n bestExpert = expert;\n }\n }\n\n if (bestExpert === undefined || bestScore === 0) {\n return err(\n new RegistryError('No expert matches the required capabilities', {\n context: {\n requiredCapabilities,\n availableExperts: this.listIds(),\n },\n })\n );\n }\n\n return ok(bestExpert);\n }\n}\n\n/**\n * Get the global expert registry instance.\n */\nexport function getExpertRegistry(): ExpertRegistry {\n return ExpertRegistry.getInstance();\n}\n","/**\n * @nexus-agents/agents - Task Analyzer Types\n *\n * Type definitions for task analysis.\n */\n\nimport { z } from 'zod';\nimport { NexusError, ErrorCode } from '../../core/index.js';\n\n// ============================================================================\n// Error Types\n// ============================================================================\n\n/**\n * Error thrown when task analysis fails.\n */\nexport class AnalysisError extends NexusError {\n constructor(message: string, options?: { cause?: Error; context?: Record<string, unknown> }) {\n super(message, { code: ErrorCode.VALIDATION_ERROR, ...options });\n this.name = 'AnalysisError';\n }\n}\n\n// ============================================================================\n// Types and Constants\n// ============================================================================\n\n/**\n * Task domains for expert matching.\n */\nexport const TaskDomain = {\n CODE: 'code',\n SECURITY: 'security',\n ARCHITECTURE: 'architecture',\n DOCUMENTATION: 'documentation',\n TESTING: 'testing',\n GENERAL: 'general',\n} as const;\n\nexport type TaskDomain = (typeof TaskDomain)[keyof typeof TaskDomain];\n\n/**\n * Task complexity levels.\n */\nexport const TaskComplexity = {\n LOW: 'low',\n MEDIUM: 'medium',\n HIGH: 'high',\n} as const;\n\nexport type TaskComplexity = (typeof TaskComplexity)[keyof typeof TaskComplexity];\n\n/**\n * Result of analyzing a task for expert matching.\n */\nexport interface TaskAnalysisResult {\n /** Primary domain of the task */\n domain: TaskDomain;\n /** Task complexity level */\n complexity: TaskComplexity;\n /** Required capabilities for the task */\n requiredCapabilities: string[];\n /** Keywords extracted from the task */\n keywords: string[];\n /** Estimated effort on 1-10 scale */\n estimatedEffort: number;\n /** Secondary domains if task spans multiple areas */\n secondaryDomains: TaskDomain[];\n /** Confidence in the analysis (0-1) */\n confidence: number;\n}\n\n/**\n * Zod schema for TaskAnalysisResult.\n */\nexport const TaskAnalysisResultSchema = z.object({\n domain: z.enum(['code', 'security', 'architecture', 'documentation', 'testing', 'general']),\n complexity: z.enum(['low', 'medium', 'high']),\n requiredCapabilities: z.array(z.string()),\n keywords: z.array(z.string()),\n estimatedEffort: z.number().min(1).max(10),\n secondaryDomains: z.array(\n z.enum(['code', 'security', 'architecture', 'documentation', 'testing', 'general'])\n ),\n confidence: z.number().min(0).max(1),\n});\n","/**\n * @nexus-agents/agents - Task Analyzer Keywords\n *\n * Keyword patterns and constants for task analysis.\n */\n\nimport type { TaskDomain } from './task-analyzer-types.js';\n\n// ============================================================================\n// Stop Words\n// ============================================================================\n\n/**\n * Common stop words to filter out during keyword extraction.\n */\nexport const STOP_WORDS = new Set([\n 'a',\n 'an',\n 'the',\n 'is',\n 'are',\n 'was',\n 'were',\n 'be',\n 'been',\n 'being',\n 'have',\n 'has',\n 'had',\n 'do',\n 'does',\n 'did',\n 'will',\n 'would',\n 'could',\n 'should',\n 'may',\n 'might',\n 'must',\n 'shall',\n 'can',\n 'need',\n 'to',\n 'of',\n 'in',\n 'for',\n 'on',\n 'with',\n 'at',\n 'by',\n 'from',\n 'as',\n 'into',\n 'through',\n 'during',\n 'before',\n 'after',\n 'above',\n 'below',\n 'between',\n 'under',\n 'again',\n 'further',\n 'then',\n 'once',\n 'here',\n 'there',\n 'when',\n 'where',\n 'why',\n 'how',\n 'all',\n 'each',\n 'few',\n 'more',\n 'most',\n 'other',\n 'some',\n 'such',\n 'no',\n 'nor',\n 'not',\n 'only',\n 'own',\n 'same',\n 'so',\n 'than',\n 'too',\n 'very',\n 's',\n 't',\n 'just',\n 'don',\n 'now',\n 'and',\n 'but',\n 'or',\n 'if',\n 'because',\n 'while',\n 'although',\n 'this',\n 'that',\n 'these',\n 'those',\n 'i',\n 'me',\n 'my',\n 'we',\n 'our',\n 'you',\n 'your',\n 'it',\n 'its',\n 'they',\n 'them',\n 'their',\n 'please',\n]);\n\n// ============================================================================\n// Domain Keywords\n// ============================================================================\n\n/**\n * Keyword patterns for domain detection.\n * Each domain has primary (high weight) and secondary (lower weight) keywords.\n */\nexport const DOMAIN_KEYWORDS: Record<TaskDomain, { primary: string[]; secondary: string[] }> = {\n code: {\n primary: [\n 'implement',\n 'code',\n 'function',\n 'class',\n 'method',\n 'refactor',\n 'debug',\n 'fix',\n 'bug',\n 'feature',\n 'api',\n 'endpoint',\n 'module',\n 'component',\n 'typescript',\n 'javascript',\n 'python',\n 'rust',\n 'java',\n ],\n secondary: [\n 'logic',\n 'algorithm',\n 'data',\n 'parse',\n 'validate',\n 'convert',\n 'transform',\n 'handle',\n 'process',\n 'create',\n 'build',\n 'develop',\n ],\n },\n security: {\n primary: [\n 'security',\n 'vulnerability',\n 'auth',\n 'authentication',\n 'authorization',\n 'encrypt',\n 'decrypt',\n 'secret',\n 'token',\n 'credential',\n 'owasp',\n 'cwe',\n 'injection',\n 'xss',\n 'csrf',\n 'audit',\n ],\n secondary: [\n 'permission',\n 'access',\n 'sanitize',\n 'validate',\n 'escape',\n 'hash',\n 'password',\n 'session',\n 'ssl',\n 'tls',\n 'certificate',\n ],\n },\n architecture: {\n primary: [\n 'architecture',\n 'design',\n 'pattern',\n 'structure',\n 'system',\n 'scale',\n 'microservice',\n 'monolith',\n 'distributed',\n 'event-driven',\n 'cqrs',\n 'ddd',\n 'adr',\n ],\n secondary: [\n 'component',\n 'service',\n 'layer',\n 'module',\n 'interface',\n 'dependency',\n 'coupling',\n 'cohesion',\n 'boundary',\n 'domain',\n ],\n },\n documentation: {\n primary: [\n 'document',\n 'documentation',\n 'readme',\n 'guide',\n 'tutorial',\n 'jsdoc',\n 'comment',\n 'explain',\n 'describe',\n 'api-doc',\n 'changelog',\n ],\n secondary: [\n 'write',\n 'update',\n 'clarify',\n 'example',\n 'usage',\n 'reference',\n 'spec',\n 'specification',\n ],\n },\n testing: {\n primary: [\n 'test',\n 'testing',\n 'unit',\n 'integration',\n 'e2e',\n 'coverage',\n 'mock',\n 'stub',\n 'assertion',\n 'vitest',\n 'jest',\n 'cypress',\n 'playwright',\n ],\n secondary: [\n 'verify',\n 'validate',\n 'check',\n 'expect',\n 'assert',\n 'fixture',\n 'scenario',\n 'case',\n 'spec',\n ],\n },\n general: {\n primary: ['help', 'assist', 'general', 'question', 'answer', 'explain'],\n secondary: ['how', 'what', 'why', 'when', 'where', 'which'],\n },\n};\n\n// ============================================================================\n// Capability Keywords\n// ============================================================================\n\n/**\n * Capability keywords for determining required capabilities.\n */\nexport const CAPABILITY_KEYWORDS: Record<string, string[]> = {\n code_generation: ['implement', 'create', 'build', 'write', 'generate', 'add', 'new'],\n code_review: ['review', 'audit', 'check', 'analyze', 'inspect', 'evaluate', 'assess'],\n research: ['research', 'investigate', 'explore', 'find', 'discover', 'learn', 'understand'],\n tool_use: ['run', 'execute', 'deploy', 'install', 'configure', 'setup', 'migrate'],\n collaboration: ['collaborate', 'coordinate', 'discuss', 'plan', 'decide', 'team'],\n delegation: ['delegate', 'assign', 'distribute', 'orchestrate', 'manage'],\n task_execution: ['do', 'perform', 'complete', 'finish', 'accomplish'],\n};\n\n// ============================================================================\n// Complexity Indicators\n// ============================================================================\n\n/**\n * Complexity indicators - words/patterns that suggest higher complexity.\n */\nexport const COMPLEXITY_INDICATORS = {\n high: [\n 'complex',\n 'difficult',\n 'challenging',\n 'comprehensive',\n 'complete',\n 'full',\n 'entire',\n 'all',\n 'multiple',\n 'various',\n 'many',\n 'distributed',\n 'microservice',\n 'architecture',\n 'refactor',\n 'migration',\n 'redesign',\n ],\n medium: [\n 'moderate',\n 'several',\n 'some',\n 'few',\n 'update',\n 'modify',\n 'change',\n 'improve',\n 'enhance',\n 'extend',\n 'add',\n ],\n low: ['simple', 'basic', 'quick', 'small', 'minor', 'single', 'one', 'fix', 'typo', 'tweak'],\n};\n","/**\n * @nexus-agents/agents - Task Analyzer\n *\n * Analyzes tasks to extract features for expert matching.\n * Uses keyword extraction and pattern matching to determine domain, complexity,\n * and required capabilities.\n */\n\nimport type { Task, Result } from '../../core/index.js';\nimport { ok, err } from '../../core/index.js';\nimport {\n type TaskAnalysisResult,\n type TaskDomain,\n type TaskComplexity,\n TaskDomain as TaskDomainConst,\n TaskComplexity as TaskComplexityConst,\n TaskAnalysisResultSchema,\n AnalysisError,\n} from './task-analyzer-types.js';\nimport {\n STOP_WORDS,\n DOMAIN_KEYWORDS,\n CAPABILITY_KEYWORDS,\n COMPLEXITY_INDICATORS,\n} from './task-analyzer-keywords.js';\n\n// Re-export types\nexport {\n AnalysisError,\n TaskDomain,\n TaskComplexity,\n type TaskAnalysisResult,\n TaskAnalysisResultSchema,\n} from './task-analyzer-types.js';\n\n// ============================================================================\n// Keyword Extraction\n// ============================================================================\n\n/**\n * Extracts keywords from task description.\n * Removes stop words and normalizes text.\n */\nfunction extractKeywords(text: string): string[] {\n // Normalize text: lowercase, remove punctuation, split on whitespace\n const words = text\n .toLowerCase()\n .replace(/[^\\w\\s-]/g, ' ')\n .split(/\\s+/)\n .filter((word) => word.length > 1 && !STOP_WORDS.has(word));\n\n // Return unique keywords\n return [...new Set(words)];\n}\n\n// ============================================================================\n// Domain Analysis\n// ============================================================================\n\n/**\n * Calculates domain scores based on keyword matching.\n */\nfunction calculateDomainScores(keywords: string[]): Map<TaskDomain, number> {\n const scores = new Map<TaskDomain, number>();\n const domains = Object.keys(DOMAIN_KEYWORDS) as TaskDomain[];\n\n for (const domain of domains) {\n const { primary, secondary } = DOMAIN_KEYWORDS[domain];\n let score = 0;\n\n for (const keyword of keywords) {\n if (primary.some((p) => keyword.includes(p) || p.includes(keyword))) {\n score += 2; // Primary keywords have higher weight\n } else if (secondary.some((s) => keyword.includes(s) || s.includes(keyword))) {\n score += 1; // Secondary keywords have lower weight\n }\n }\n\n scores.set(domain, score);\n }\n\n return scores;\n}\n\n/**\n * Determines primary and secondary domains from scores.\n */\nfunction determineDomains(scores: Map<TaskDomain, number>): {\n primary: TaskDomain;\n secondary: TaskDomain[];\n} {\n const entries = [...scores.entries()].sort((a, b) => b[1] - a[1]);\n const firstEntry = entries[0];\n\n if (entries.length === 0 || firstEntry === undefined || firstEntry[1] === 0) {\n return { primary: TaskDomainConst.GENERAL, secondary: [] };\n }\n\n const primary = firstEntry[0];\n const threshold = firstEntry[1] * 0.5; // Secondary domains need at least 50% of primary score\n\n const secondary = entries\n .slice(1)\n .filter(([, score]) => score >= threshold && score > 0)\n .map(([domain]) => domain);\n\n return { primary, secondary };\n}\n\n// ============================================================================\n// Capability Analysis\n// ============================================================================\n\n/**\n * Determines required capabilities based on keywords.\n */\nfunction determineCapabilities(keywords: string[]): string[] {\n const capabilities: Set<string> = new Set();\n\n for (const [capability, capKeywords] of Object.entries(CAPABILITY_KEYWORDS)) {\n for (const keyword of keywords) {\n if (capKeywords.some((ck) => keyword.includes(ck) || ck.includes(keyword))) {\n capabilities.add(capability);\n break;\n }\n }\n }\n\n // Always include task_execution as base capability\n capabilities.add('task_execution');\n\n return [...capabilities];\n}\n\n// ============================================================================\n// Complexity Analysis\n// ============================================================================\n\n/**\n * Calculates complexity scores from text.\n */\nfunction calculateComplexityScores(lowerText: string): {\n high: number;\n medium: number;\n low: number;\n} {\n let highScore = 0;\n let mediumScore = 0;\n let lowScore = 0;\n\n for (const indicator of COMPLEXITY_INDICATORS.high) {\n if (lowerText.includes(indicator)) {\n highScore += 2;\n }\n }\n\n for (const indicator of COMPLEXITY_INDICATORS.medium) {\n if (lowerText.includes(indicator)) {\n mediumScore += 1;\n }\n }\n\n for (const indicator of COMPLEXITY_INDICATORS.low) {\n if (lowerText.includes(indicator)) {\n lowScore += 2;\n }\n }\n\n return { high: highScore, medium: mediumScore, low: lowScore };\n}\n\n/**\n * Determines task complexity based on indicators.\n */\nfunction determineComplexity(text: string, keywords: string[]): TaskComplexity {\n const lowerText = text.toLowerCase();\n const scores = calculateComplexityScores(lowerText);\n\n // Consider text length as a factor\n const wordCount = keywords.length;\n if (wordCount > 50) {\n scores.high += 2;\n } else if (wordCount > 20) {\n scores.medium += 1;\n }\n\n // Determine complexity based on scores\n if (scores.high > scores.medium && scores.high > scores.low) {\n return TaskComplexityConst.HIGH;\n } else if (scores.low > scores.medium) {\n return TaskComplexityConst.LOW;\n }\n\n return TaskComplexityConst.MEDIUM;\n}\n\n// ============================================================================\n// Effort Estimation\n// ============================================================================\n\n/**\n * Gets base effort from complexity level.\n */\nfunction getBaseEffort(complexity: TaskComplexity): number {\n switch (complexity) {\n case TaskComplexityConst.HIGH:\n return 7;\n case TaskComplexityConst.MEDIUM:\n return 4;\n case TaskComplexityConst.LOW:\n return 2;\n }\n}\n\n/**\n * Estimates effort on 1-10 scale.\n */\nfunction estimateEffort(\n complexity: TaskComplexity,\n keywords: string[],\n secondaryDomains: TaskDomain[]\n): number {\n let baseEffort = getBaseEffort(complexity);\n\n // Adjust based on keyword count\n const keywordFactor = Math.min(keywords.length / 20, 1); // Max 1 point for many keywords\n baseEffort += keywordFactor;\n\n // Adjust for multiple domains\n baseEffort += secondaryDomains.length * 0.5;\n\n // Clamp to 1-10 range\n return Math.max(1, Math.min(10, Math.round(baseEffort)));\n}\n\n// ============================================================================\n// Confidence Calculation\n// ============================================================================\n\n/**\n * Calculates confidence in the analysis.\n */\nfunction calculateConfidence(domainScores: Map<TaskDomain, number>, keywords: string[]): number {\n const scores = [...domainScores.values()];\n const maxScore = Math.max(...scores);\n const totalScore = scores.reduce((a, b) => a + b, 0);\n\n if (totalScore === 0 || keywords.length === 0) {\n return 0.3; // Low confidence for tasks with no matching keywords\n }\n\n // Confidence is higher when one domain clearly dominates\n const dominance = maxScore / totalScore;\n const keywordCoverage = Math.min(keywords.length / 10, 1); // More keywords = higher confidence\n\n return Math.min(0.95, dominance * 0.6 + keywordCoverage * 0.4);\n}\n\n// ============================================================================\n// Full Text Building\n// ============================================================================\n\n/**\n * Builds full text for analysis from task.\n */\nfunction buildFullText(task: Task): string {\n let fullText = task.description;\n\n const workingDir = task.context.workingDirectory;\n if (workingDir !== undefined && workingDir !== '') {\n fullText += ` ${workingDir}`;\n }\n\n if (task.context.files !== undefined && task.context.files.length > 0) {\n fullText += ` ${task.context.files.join(' ')}`;\n }\n\n return fullText;\n}\n\n// ============================================================================\n// Main Analysis Function\n// ============================================================================\n\n/**\n * Analyzes a task to extract features for expert matching.\n *\n * @param task - The task to analyze\n * @returns Result containing TaskAnalysisResult or AnalysisError\n */\nexport function analyzeTask(task: Task): Result<TaskAnalysisResult, AnalysisError> {\n // Validate task input\n if (task.description.trim().length === 0) {\n return err(\n new AnalysisError('Task description is required for analysis', {\n context: { taskId: task.id },\n })\n );\n }\n\n try {\n // Combine description with context for analysis\n const fullText = buildFullText(task);\n\n // Extract keywords\n const keywords = extractKeywords(fullText);\n\n // Calculate domain scores\n const domainScores = calculateDomainScores(keywords);\n\n // Determine primary and secondary domains\n const { primary: domain, secondary: secondaryDomains } = determineDomains(domainScores);\n\n // Determine required capabilities\n const requiredCapabilities = determineCapabilities(keywords);\n\n // Determine complexity\n const complexity = determineComplexity(fullText, keywords);\n\n // Estimate effort\n const estimatedEffort = estimateEffort(complexity, keywords, secondaryDomains);\n\n // Calculate confidence\n const confidence = calculateConfidence(domainScores, keywords);\n\n const result: TaskAnalysisResult = {\n domain,\n complexity,\n requiredCapabilities,\n keywords,\n estimatedEffort,\n secondaryDomains,\n confidence,\n };\n\n // Validate result against schema\n const validation = TaskAnalysisResultSchema.safeParse(result);\n if (!validation.success) {\n return err(\n new AnalysisError('Analysis result validation failed', {\n context: { taskId: task.id, validationErrors: validation.error.issues },\n })\n );\n }\n\n return ok(result);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n const options: { cause?: Error; context: { taskId: string } } = {\n context: { taskId: task.id },\n };\n if (error instanceof Error) {\n options.cause = error;\n }\n return err(new AnalysisError(`Task analysis failed: ${message}`, options));\n }\n}\n","/**\n * @nexus-agents/agents - Expert Selector\n *\n * Selects the best experts for a task based on capability matching,\n * domain alignment, and scoring algorithms.\n */\n\nimport { z } from 'zod';\nimport type { Task, AgentRole } from '../../core/index.js';\nimport { ok, err, NexusError, ErrorCode } from '../../core/index.js';\nimport type { Result } from '../../core/index.js';\nimport {\n analyzeTask,\n type TaskAnalysisResult,\n type TaskDomain,\n TaskComplexity,\n} from './task-analyzer.js';\nimport { DEFAULT_EXPERTS } from './expert-defaults.js';\n\n/** Error thrown when expert selection fails. */\nexport class SelectionError extends NexusError {\n constructor(message: string, options?: { cause?: Error; context?: Record<string, unknown> }) {\n super(message, { code: ErrorCode.AGENT_NOT_FOUND, ...options });\n this.name = 'SelectionError';\n }\n}\n\n/** Collaboration patterns for multi-expert tasks. */\nexport const ExpertCollaborationPattern = {\n SEQUENTIAL: 'sequential',\n PARALLEL: 'parallel',\n REVIEW_CHAIN: 'review_chain',\n PAIR: 'pair',\n} as const;\n\nexport type ExpertCollaborationPatternType =\n (typeof ExpertCollaborationPattern)[keyof typeof ExpertCollaborationPattern];\n\n/** Definition of an expert's capabilities and metadata. */\nexport interface ExpertDefinition {\n id: string;\n role: AgentRole;\n name: string;\n description: string;\n capabilities: string[];\n primaryDomain: TaskDomain;\n secondaryDomains: TaskDomain[];\n weight: number;\n available: boolean;\n}\n\n/** Registry of available experts. */\nexport interface ExpertRegistry {\n getAll(): ExpertDefinition[];\n getById(id: string): ExpertDefinition | undefined;\n getByRole(role: AgentRole): ExpertDefinition[];\n getByDomain(domain: TaskDomain): ExpertDefinition[];\n getAvailable(): ExpertDefinition[];\n}\n\n/** Breakdown of how the match score was calculated. */\nexport interface ScoreBreakdown {\n capabilityScore: number;\n domainScore: number;\n weightScore: number;\n finalScore: number;\n}\n\n/** Match result for a single expert. */\nexport interface ExpertMatch {\n expertId: string;\n score: number;\n matchedCapabilities: string[];\n reasoning: string;\n scoreBreakdown: ScoreBreakdown;\n}\n\n/** Result of expert selection. */\nexport interface SelectionResult {\n primary: ExpertMatch;\n alternatives: ExpertMatch[];\n requiresCollaboration: boolean;\n suggestedPattern?: ExpertCollaborationPatternType;\n confidence: number;\n}\n\n/** Options for expert selection. */\nexport interface SelectionOptions {\n minScore?: number;\n maxAlternatives?: number;\n capabilityWeights?: Record<string, number>;\n preferredDomains?: TaskDomain[];\n excludeExperts?: string[];\n forceCollaboration?: boolean;\n}\n\n// ============================================================================\n// Zod Schemas\n// ============================================================================\n\nexport const ScoreBreakdownSchema = z.object({\n capabilityScore: z.number().min(0).max(1),\n domainScore: z.number().min(0).max(1),\n weightScore: z.number().min(0).max(1),\n finalScore: z.number().min(0).max(1),\n});\n\nexport const ExpertMatchSchema = z.object({\n expertId: z.string().min(1),\n score: z.number().min(0).max(1),\n matchedCapabilities: z.array(z.string()),\n reasoning: z.string(),\n scoreBreakdown: ScoreBreakdownSchema,\n});\n\nexport const SelectionResultSchema = z.object({\n primary: ExpertMatchSchema,\n alternatives: z.array(ExpertMatchSchema),\n requiresCollaboration: z.boolean(),\n suggestedPattern: z.enum(['sequential', 'parallel', 'review_chain', 'pair']).optional(),\n confidence: z.number().min(0).max(1),\n});\n\nexport const SelectionOptionsSchema = z.object({\n minScore: z.number().min(0).max(1).optional(),\n maxAlternatives: z.number().min(0).max(10).optional(),\n capabilityWeights: z.record(z.number().min(0).max(10)).optional(),\n preferredDomains: z\n .array(z.enum(['code', 'security', 'architecture', 'documentation', 'testing', 'general']))\n .optional(),\n excludeExperts: z.array(z.string()).optional(),\n forceCollaboration: z.boolean().optional(),\n});\n\n// ============================================================================\n// Default Expert Registry\n// ============================================================================\n\n/** Cached default registry singleton for performance optimization. */\nlet cachedDefaultRegistry: ExpertRegistry | null = null;\n\n/**\n * Gets the cached default expert registry, creating it if needed.\n * This avoids recreating the registry on every call to quickSelect().\n */\nfunction getDefaultRegistry(): ExpertRegistry {\n cachedDefaultRegistry ??= createDefaultRegistry();\n return cachedDefaultRegistry;\n}\n\n/**\n * Resets the cached default registry.\n * Primarily useful for testing to ensure test isolation.\n */\nexport function resetDefaultRegistry(): void {\n cachedDefaultRegistry = null;\n}\n\n/**\n * Creates a default expert registry with built-in experts.\n */\nexport function createDefaultRegistry(): ExpertRegistry {\n const experts = [...DEFAULT_EXPERTS];\n\n return {\n getAll: () => [...experts],\n getById: (id: string) => experts.find((e) => e.id === id),\n getByRole: (role: AgentRole) => experts.filter((e) => e.role === role),\n getByDomain: (domain: TaskDomain) =>\n experts.filter((e) => e.primaryDomain === domain || e.secondaryDomains.includes(domain)),\n getAvailable: () => experts.filter((e) => e.available),\n };\n}\n\n// ============================================================================\n// Scoring Functions\n// ============================================================================\n\nconst DEFAULT_MIN_SCORE = 0.1;\nconst DEFAULT_MAX_ALTERNATIVES = 3;\nconst CAPABILITY_WEIGHT = 0.4;\nconst DOMAIN_WEIGHT = 0.4;\nconst EXPERT_WEIGHT = 0.2;\n\nfunction calculateCapabilityScore(\n expert: ExpertDefinition,\n requiredCapabilities: string[],\n customWeights?: Record<string, number>\n): { score: number; matched: string[] } {\n if (requiredCapabilities.length === 0) return { score: 0.5, matched: [] };\n const matched: string[] = [];\n let totalWeight = 0,\n matchedWeight = 0;\n for (const req of requiredCapabilities) {\n const w = customWeights?.[req] ?? 1;\n totalWeight += w;\n if (expert.capabilities.includes(req)) {\n matched.push(req);\n matchedWeight += w;\n }\n }\n return { score: totalWeight > 0 ? matchedWeight / totalWeight : 0, matched };\n}\n\nfunction calculateDomainScore(\n expert: ExpertDefinition,\n primaryDomain: TaskDomain,\n secondaryDomains: TaskDomain[],\n preferredDomains?: TaskDomain[]\n): number {\n let score = 0;\n if (expert.primaryDomain === primaryDomain) score = 1.0;\n else if (expert.secondaryDomains.includes(primaryDomain)) score = 0.7;\n else if (expert.primaryDomain === 'general') score = 0.3;\n for (const sec of secondaryDomains) {\n if (expert.primaryDomain === sec) score += 0.15;\n else if (expert.secondaryDomains.includes(sec)) score += 0.1;\n }\n if (\n preferredDomains !== undefined &&\n preferredDomains.length > 0 &&\n preferredDomains.includes(expert.primaryDomain)\n )\n score += 0.1;\n return Math.min(1.0, score);\n}\n\nfunction generateReasoning(\n expert: ExpertDefinition,\n analysis: TaskAnalysisResult,\n matchedCaps: string[],\n domainScore: number\n): string {\n const parts: string[] = [];\n if (expert.primaryDomain === analysis.domain)\n parts.push(`Primary expertise in ${analysis.domain} domain`);\n else if (expert.secondaryDomains.includes(analysis.domain))\n parts.push(`Secondary expertise in ${analysis.domain} domain`);\n else if (domainScore > 0)\n parts.push(`Can handle ${analysis.domain} tasks with general knowledge`);\n if (matchedCaps.length > 0)\n parts.push(`Matched capabilities: ${matchedCaps.slice(0, 3).join(', ')}`);\n if (analysis.complexity === TaskComplexity.HIGH && expert.capabilities.includes('collaboration'))\n parts.push('Suited for complex tasks requiring collaboration');\n return parts.join('. ') + '.';\n}\n\nfunction scoreExpert(\n expert: ExpertDefinition,\n analysis: TaskAnalysisResult,\n options?: SelectionOptions\n): ExpertMatch {\n const { score: capabilityScore, matched } = calculateCapabilityScore(\n expert,\n analysis.requiredCapabilities,\n options?.capabilityWeights\n );\n const domainScore = calculateDomainScore(\n expert,\n analysis.domain,\n analysis.secondaryDomains,\n options?.preferredDomains\n );\n const finalScore =\n capabilityScore * CAPABILITY_WEIGHT +\n domainScore * DOMAIN_WEIGHT +\n expert.weight * EXPERT_WEIGHT;\n return {\n expertId: expert.id,\n score: finalScore,\n matchedCapabilities: matched,\n reasoning: generateReasoning(expert, analysis, matched, domainScore),\n scoreBreakdown: { capabilityScore, domainScore, weightScore: expert.weight, finalScore },\n };\n}\n\nfunction isHighComplexityMultiDomain(a: TaskAnalysisResult): boolean {\n return a.complexity === TaskComplexity.HIGH && a.secondaryDomains.length > 0;\n}\nfunction isCodeSecurityTask(a: TaskAnalysisResult): boolean {\n return a.domain === 'code' && a.secondaryDomains.includes('security' as TaskDomain);\n}\nfunction isCodeTestingTask(a: TaskAnalysisResult): boolean {\n return a.domain === 'code' && a.secondaryDomains.includes('testing' as TaskDomain);\n}\nfunction isHighEffortMultiDomain(a: TaskAnalysisResult): boolean {\n return a.estimatedEffort >= 7 && a.secondaryDomains.length >= 2;\n}\n\n/** Determines if collaboration is needed based on task analysis. */\nfunction shouldCollaborate(\n analysis: TaskAnalysisResult,\n options?: SelectionOptions\n): { needed: boolean; pattern?: ExpertCollaborationPatternType } {\n // Handle forceCollaboration explicitly to avoid nullable boolean issue\n if (options?.forceCollaboration === true) {\n return { needed: true, pattern: ExpertCollaborationPattern.PARALLEL };\n }\n\n if (isHighComplexityMultiDomain(analysis)) {\n return { needed: true, pattern: ExpertCollaborationPattern.SEQUENTIAL };\n }\n\n if (isCodeSecurityTask(analysis)) {\n return { needed: true, pattern: ExpertCollaborationPattern.REVIEW_CHAIN };\n }\n\n if (isCodeTestingTask(analysis)) {\n return { needed: true, pattern: ExpertCollaborationPattern.PARALLEL };\n }\n\n if (isHighEffortMultiDomain(analysis)) {\n return { needed: true, pattern: ExpertCollaborationPattern.SEQUENTIAL };\n }\n\n return { needed: false };\n}\n\n// ============================================================================\n// Selection Helper Functions\n// ============================================================================\n\n/** Validates selection options. */\nfunction validateOptions(options: SelectionOptions): Result<void, SelectionError> {\n const result = SelectionOptionsSchema.safeParse(options);\n if (!result.success) {\n return err(\n new SelectionError('Invalid selection options', {\n context: { validationErrors: result.error.issues },\n })\n );\n }\n return ok(undefined);\n}\n\n/** Gets filtered list of available experts. */\nfunction getFilteredExperts(\n registry: ExpertRegistry,\n excludeExperts?: string[]\n): ExpertDefinition[] {\n const experts = registry.getAvailable();\n if (!excludeExperts || excludeExperts.length === 0) return experts;\n const excluded = new Set(excludeExperts);\n return experts.filter((e) => !excluded.has(e.id));\n}\n\n/** Scores and sorts all experts. */\nfunction scoreAndSortExperts(\n experts: ExpertDefinition[],\n analysis: TaskAnalysisResult,\n options?: SelectionOptions\n): ExpertMatch[] {\n return experts.map((e) => scoreExpert(e, analysis, options)).sort((a, b) => b.score - a.score);\n}\n\n/** Creates a fallback result when no matches meet minimum score. */\nfunction createFallbackResult(bestMatch: ExpertMatch, confidence: number): SelectionResult {\n return { primary: bestMatch, alternatives: [], requiresCollaboration: false, confidence };\n}\n\n/** Builds the final selection result. */\nfunction buildSelectionResult(\n primary: ExpertMatch,\n filteredMatches: ExpertMatch[],\n analysis: TaskAnalysisResult,\n options?: SelectionOptions\n): SelectionResult {\n const maxAlternatives = options?.maxAlternatives ?? DEFAULT_MAX_ALTERNATIVES;\n const alternatives = filteredMatches.slice(1, maxAlternatives + 1);\n const { needed: requiresCollaboration, pattern: suggestedPattern } = shouldCollaborate(\n analysis,\n options\n );\n const scoreSpread = primary.score - (alternatives[0]?.score ?? 0);\n const confidence = Math.min(0.95, analysis.confidence * (0.7 + scoreSpread * 0.3));\n const result: SelectionResult = { primary, alternatives, requiresCollaboration, confidence };\n if (suggestedPattern !== undefined) result.suggestedPattern = suggestedPattern;\n return result;\n}\n\n/** Handles the case when no filtered matches exist. */\nfunction handleNoFilteredMatches(\n matches: ExpertMatch[],\n analysis: TaskAnalysisResult,\n taskId: string\n): Result<SelectionResult, SelectionError> {\n const bestMatch = matches[0];\n if (bestMatch === undefined) {\n return err(new SelectionError('No experts available for matching', { context: { taskId } }));\n }\n return ok(createFallbackResult(bestMatch, analysis.confidence * 0.5));\n}\n\n/** Processes filtered matches to produce final result. */\nfunction processFilteredMatches(\n filteredMatches: ExpertMatch[],\n analysis: TaskAnalysisResult,\n options: SelectionOptions | undefined,\n taskId: string\n): Result<SelectionResult, SelectionError> {\n const primary = filteredMatches[0];\n if (primary === undefined) {\n return err(new SelectionError('No experts available for matching', { context: { taskId } }));\n }\n return ok(buildSelectionResult(primary, filteredMatches, analysis, options));\n}\n\n// ============================================================================\n// Main Selection Function\n// ============================================================================\n\n/**\n * Selects the best experts for a task.\n * @param task - The task to select experts for\n * @param registry - Registry of available experts\n * @param options - Optional selection configuration\n */\nexport function selectExperts(\n task: Task,\n registry: ExpertRegistry,\n options?: SelectionOptions\n): Result<SelectionResult, SelectionError> {\n if (options !== undefined) {\n const validation = validateOptions(options);\n if (!validation.ok) {\n return validation;\n }\n }\n\n const analysisResult = analyzeTask(task);\n if (!analysisResult.ok) {\n return err(\n new SelectionError(`Task analysis failed: ${analysisResult.error.message}`, {\n cause: analysisResult.error,\n context: { taskId: task.id },\n })\n );\n }\n\n const analysis = analysisResult.value;\n const experts = getFilteredExperts(registry, options?.excludeExperts);\n if (experts.length === 0) {\n return err(new SelectionError('No available experts found', { context: { taskId: task.id } }));\n }\n\n const matches = scoreAndSortExperts(experts, analysis, options);\n const minScore = options?.minScore ?? DEFAULT_MIN_SCORE;\n const filteredMatches = matches.filter((m) => m.score >= minScore);\n\n if (filteredMatches.length === 0) {\n return handleNoFilteredMatches(matches, analysis, task.id);\n }\n return processFilteredMatches(filteredMatches, analysis, options, task.id);\n}\n\n/**\n * Quick selection using default registry.\n * Convenience function for simple use cases.\n * Uses a cached registry for performance optimization.\n */\nexport function quickSelect(\n task: Task,\n options?: SelectionOptions\n): Result<SelectionResult, SelectionError> {\n const registry = getDefaultRegistry();\n return selectExperts(task, registry, options);\n}\n","/**\n * @nexus-agents/agents - Default Expert Registry\n *\n * Default expert definitions for the expert selector.\n */\n\nimport type { ExpertDefinition } from './expert-selector-types.js';\n\n/**\n * Default expert definitions for built-in experts.\n */\nexport const DEFAULT_EXPERTS: ExpertDefinition[] = [\n {\n id: 'code-expert',\n role: 'code_expert',\n name: 'Code Expert',\n description: 'Specialized in code implementation, refactoring, and debugging',\n capabilities: ['task_execution', 'code_generation', 'code_review', 'tool_use'],\n primaryDomain: 'code',\n secondaryDomains: ['testing'],\n weight: 1.0,\n available: true,\n },\n {\n id: 'security-expert',\n role: 'security_expert',\n name: 'Security Expert',\n description: 'Specialized in security analysis, vulnerability assessment, and audits',\n capabilities: ['task_execution', 'code_review', 'research'],\n primaryDomain: 'security',\n secondaryDomains: ['code'],\n weight: 1.0,\n available: true,\n },\n {\n id: 'architecture-expert',\n role: 'architecture_expert',\n name: 'Architecture Expert',\n description: 'Specialized in system design, patterns, and architectural decisions',\n capabilities: ['task_execution', 'research', 'collaboration'],\n primaryDomain: 'architecture',\n secondaryDomains: ['code', 'documentation'],\n weight: 1.0,\n available: true,\n },\n {\n id: 'documentation-expert',\n role: 'documentation_expert',\n name: 'Documentation Expert',\n description: 'Specialized in technical writing and API documentation',\n capabilities: ['task_execution', 'research'],\n primaryDomain: 'documentation',\n secondaryDomains: [],\n weight: 0.9,\n available: true,\n },\n {\n id: 'testing-expert',\n role: 'testing_expert',\n name: 'Testing Expert',\n description: 'Specialized in test strategies, coverage, and quality assurance',\n capabilities: ['task_execution', 'code_generation', 'tool_use'],\n primaryDomain: 'testing',\n secondaryDomains: ['code'],\n weight: 1.0,\n available: true,\n },\n];\n","/**\n * @nexus-agents/agents - Collaboration Schemas\n *\n * Zod schemas for collaboration protocol validation.\n */\n\nimport { z } from 'zod';\n\n/**\n * Zod schema for CollaborationPattern.\n */\nexport const CollaborationPatternSchema = z.enum(['sequential', 'parallel', 'review', 'consensus']);\n\n/**\n * Zod schema for SessionStatus.\n */\nexport const SessionStatusSchema = z.enum([\n 'pending',\n 'in_progress',\n 'awaiting_review',\n 'voting',\n 'finalizing',\n 'completed',\n 'failed',\n 'timed_out',\n]);\n\n/**\n * Zod schema for VoteDecision.\n */\nexport const VoteDecisionSchema = z.enum(['approve', 'reject', 'abstain']);\n\n/**\n * Zod schema for CollaborationConfig.\n */\nexport const CollaborationConfigSchema = z.object({\n sessionId: z.string().min(1, 'Session ID is required'),\n pattern: CollaborationPatternSchema,\n experts: z.array(z.string().min(1)).min(1, 'At least one expert is required'),\n task: z.object({\n id: z.string().min(1),\n description: z.string().min(1),\n context: z.record(z.unknown()),\n constraints: z\n .object({\n maxDuration: z.number().positive().optional(),\n maxTokens: z.number().positive().optional(),\n outputFormat: z.enum(['text', 'json', 'markdown']).optional(),\n allowedTools: z.array(z.string()).optional(),\n })\n .optional(),\n priority: z.number().optional(),\n }),\n timeout: z.number().positive().optional(),\n minVotes: z.number().positive().optional(),\n requireUnanimous: z.boolean().optional(),\n maxRetries: z.number().min(0).max(5).optional(),\n});\n\n/**\n * Zod schema for ExpertParticipation.\n */\nexport const ExpertParticipationSchema = z.object({\n expertId: z.string().min(1),\n role: z.enum([\n 'tech_lead',\n 'code_expert',\n 'architecture_expert',\n 'security_expert',\n 'documentation_expert',\n 'testing_expert',\n 'custom',\n ]),\n joinedAt: z.string().datetime(),\n status: z.enum(['pending', 'working', 'submitted', 'reviewing', 'voted', 'failed']),\n submittedAt: z.string().datetime().optional(),\n retryCount: z.number().min(0),\n});\n\n/**\n * Zod schema for VoteMessage.\n */\nexport const VoteMessageSchema = z.object({\n type: z.literal('vote'),\n expertId: z.string().min(1),\n decision: VoteDecisionSchema,\n reasoning: z.string().min(1, 'Vote reasoning is required'),\n conditions: z.array(z.string()).optional(),\n});\n\n/**\n * Zod schema for ReviewResponseMessage.\n */\nexport const ReviewResponseMessageSchema = z.object({\n type: z.literal('review_response'),\n reviewerId: z.string().min(1),\n requesterId: z.string().min(1),\n approved: z.boolean(),\n feedback: z.string().min(1),\n suggestions: z.array(z.string()).optional(),\n severity: z.enum(['none', 'minor', 'major', 'critical']).optional(),\n});\n\n/**\n * Default collaboration timeouts.\n */\nexport const DEFAULT_TIMEOUTS = {\n sequential: 5 * 60 * 1000, // 5 minutes\n parallel: 3 * 60 * 1000, // 3 minutes\n review: 2 * 60 * 1000, // 2 minutes\n consensus: 5 * 60 * 1000, // 5 minutes\n} as const;\n\n/**\n * Default retry counts.\n */\nexport const DEFAULT_MAX_RETRIES = 2;\n\n/**\n * Minimum number of experts for each pattern.\n */\nexport const MIN_EXPERTS_FOR_PATTERN = {\n sequential: 1,\n parallel: 2,\n review: 2,\n consensus: 3,\n} as const;\n","/**\n * @nexus-agents/agents - Session Helpers\n *\n * Helper functions for collaboration session operations.\n * Extracted to keep the main session class under 400 lines.\n */\n\nimport type { Result, TaskResult, AgentRole } from '../../core/index.js';\nimport { ok, err, AgentError } from '../../core/index.js';\nimport type {\n CollaborationConfig,\n CollaborationPattern,\n ExpertParticipation,\n SessionState,\n TaskAssignmentMessage,\n VoteMessage,\n ReviewResponseMessage,\n ExpertResultSummary,\n ResultConflict,\n AggregatedResult,\n} from './collaboration-types.js';\nimport { CollaborationConfigSchema, MIN_EXPERTS_FOR_PATTERN } from './collaboration-types.js';\n\n/**\n * Gets task assignments for sequential pattern.\n */\nexport function getSequentialAssignments(\n config: CollaborationConfig,\n participants: ExpertParticipation[],\n results: Map<string, TaskResult>\n): TaskAssignmentMessage[] {\n const assignments: TaskAssignmentMessage[] = [];\n const previousResults: TaskResult[] = [];\n\n for (let i = 0; i < participants.length; i++) {\n const participant = participants[i];\n if (participant?.status !== 'pending') {\n const result = results.get(participant?.expertId ?? '');\n if (result !== undefined) {\n previousResults.push(result);\n }\n continue;\n }\n\n // Only assign if all previous experts have completed\n if (i > 0 && results.size < i) {\n break;\n }\n\n assignments.push({\n type: 'task_assignment',\n expertId: participant.expertId,\n task: config.task,\n sequencePosition: i,\n previousResults: [...previousResults],\n });\n break; // Only one assignment at a time for sequential\n }\n\n return assignments;\n}\n\n/**\n * Gets task assignments for parallel pattern.\n */\nexport function getParallelAssignments(\n config: CollaborationConfig,\n participants: ExpertParticipation[]\n): TaskAssignmentMessage[] {\n return participants\n .filter((p) => p.status === 'pending')\n .map((p) => ({\n type: 'task_assignment' as const,\n expertId: p.expertId,\n task: config.task,\n }));\n}\n\n/**\n * Gets task assignments for review pattern.\n */\nexport function getReviewAssignments(\n config: CollaborationConfig,\n participants: ExpertParticipation[],\n results: Map<string, TaskResult>\n): TaskAssignmentMessage[] {\n const pending = participants.filter((p) => p.status === 'pending');\n if (pending.length === 0) {\n return [];\n }\n\n // If no results yet, assign to first pending expert\n if (results.size === 0 && pending.length > 0) {\n const first = pending[0];\n if (first !== undefined) {\n return [\n {\n type: 'task_assignment',\n expertId: first.expertId,\n task: config.task,\n },\n ];\n }\n }\n\n return [];\n}\n\n/**\n * Gets task assignments for consensus pattern.\n */\nexport function getConsensusAssignments(\n config: CollaborationConfig,\n participants: ExpertParticipation[]\n): TaskAssignmentMessage[] {\n return participants\n .filter((p) => p.status === 'pending')\n .map((p) => ({\n type: 'task_assignment' as const,\n expertId: p.expertId,\n task: config.task,\n }));\n}\n\n/**\n * Session success evaluation input.\n */\nexport interface SessionSuccessInput {\n pattern: CollaborationPattern;\n participants: ExpertParticipation[];\n results: Map<string, TaskResult>;\n votes: VoteMessage[];\n reviews: ReviewResponseMessage[];\n requireUnanimous: boolean;\n minVotes?: number | undefined;\n}\n\n/**\n * Determines if session succeeded based on pattern and results.\n */\nexport function isSessionSuccessful(input: SessionSuccessInput): boolean {\n const { pattern, participants, results, votes, reviews, requireUnanimous, minVotes } = input;\n\n switch (pattern) {\n case 'sequential':\n case 'parallel':\n return results.size > 0;\n case 'review':\n return reviews.some((r) => r.approved);\n case 'consensus': {\n const approveCount = votes.filter((v) => v.decision === 'approve').length;\n const threshold = minVotes ?? Math.ceil(participants.length / 2);\n if (requireUnanimous) {\n return approveCount === participants.length;\n }\n return approveCount >= threshold;\n }\n default:\n return false;\n }\n}\n\n/**\n * Aggregates outputs from multiple results.\n */\nexport function aggregateOutputs(results: TaskResult[]): unknown {\n if (results.length === 0) {\n return null;\n }\n\n if (results.length === 1) {\n return results[0]?.output;\n }\n\n return results.map((r) => ({\n taskId: r.taskId,\n output: r.output,\n }));\n}\n\n/**\n * Determines aggregation strategy from pattern.\n */\nexport function getAggregationStrategy(\n pattern: CollaborationPattern\n): 'merge' | 'select_best' | 'consensus' | 'sequential_chain' {\n switch (pattern) {\n case 'sequential':\n return 'sequential_chain';\n case 'consensus':\n return 'consensus';\n case 'review':\n return 'select_best';\n case 'parallel':\n default:\n return 'merge';\n }\n}\n\n/**\n * Calculates quality score for session.\n */\nexport function calculateQualityScore(\n pattern: CollaborationPattern,\n participants: ExpertParticipation[],\n votes: VoteMessage[],\n reviews: ReviewResponseMessage[]\n): number {\n const submittedCount = participants.filter((p) => p.status === 'submitted').length;\n const totalCount = participants.length;\n\n if (totalCount === 0) {\n return 0;\n }\n\n let score = submittedCount / totalCount;\n\n if (pattern === 'consensus' && votes.length > 0) {\n const approveRatio = votes.filter((v) => v.decision === 'approve').length / votes.length;\n score = (score + approveRatio) / 2;\n }\n\n if (pattern === 'review' && reviews.length > 0) {\n const approvedCount = reviews.filter((r) => r.approved).length;\n const reviewScore = approvedCount / reviews.length;\n score = (score + reviewScore) / 2;\n }\n\n return Math.round(score * 100) / 100;\n}\n\n/**\n * Builds expert result summaries.\n */\nexport function buildExpertResults(\n participants: ExpertParticipation[],\n results: Map<string, TaskResult>\n): ExpertResultSummary[] {\n return participants.map((p) => {\n const result = results.get(p.expertId);\n const base = {\n expertId: p.expertId,\n role: p.role,\n contributionScore: result !== undefined ? 1.0 : 0.0,\n executionTimeMs: result?.metadata.durationMs ?? 0,\n success: p.status === 'submitted' || p.status === 'voted',\n };\n\n if (result !== undefined) {\n if (p.status === 'failed') {\n return { ...base, result, error: 'Expert failed to complete task' };\n }\n return { ...base, result };\n }\n\n if (p.status === 'failed') {\n return { ...base, error: 'Expert failed to complete task' };\n }\n\n return base;\n });\n}\n\n/**\n * Aggregated result builder input.\n */\nexport interface AggregatedResultInput {\n pattern: CollaborationPattern;\n results: TaskResult[];\n participants: ExpertParticipation[];\n votes: VoteMessage[];\n reviews: ReviewResponseMessage[];\n endTime: Date;\n}\n\n/**\n * Builds aggregated result for collaboration.\n */\nexport function buildAggregatedResult(input: AggregatedResultInput): AggregatedResult {\n const { pattern, results, participants, votes, reviews, endTime } = input;\n\n return {\n output: aggregateOutputs(results),\n strategy: getAggregationStrategy(pattern),\n qualityScore: calculateQualityScore(pattern, participants, votes, reviews),\n conflicts: [] as ResultConflict[],\n metadata: {\n resultCount: results.length,\n conflictCount: 0,\n averageConfidence: 1.0,\n totalTokensUsed: results.reduce((sum, r) => sum + r.metadata.tokensUsed, 0),\n aggregatedAt: endTime.toISOString(),\n },\n };\n}\n\n/**\n * Validates collaboration config.\n */\nexport function validateConfig(config: CollaborationConfig): Result<void, AgentError> {\n const validation = CollaborationConfigSchema.safeParse(config);\n if (!validation.success) {\n const issues = validation.error.issues\n .map((issue) => `${issue.path.join('.')}: ${issue.message}`)\n .join('; ');\n return err(\n new AgentError(`Invalid collaboration config: ${issues}`, {\n context: { sessionId: config.sessionId, validationErrors: validation.error.issues },\n })\n );\n }\n\n const minExperts = MIN_EXPERTS_FOR_PATTERN[config.pattern];\n if (config.experts.length < minExperts) {\n return err(\n new AgentError(\n `Pattern '${config.pattern}' requires at least ${String(minExperts)} experts`,\n { context: { pattern: config.pattern, expertCount: config.experts.length } }\n )\n );\n }\n\n return ok(undefined);\n}\n\n/**\n * Creates initial session state.\n */\nexport function createSessionState(\n config: CollaborationConfig,\n roleResolver: (expertId: string) => AgentRole\n): SessionState {\n const now = new Date().toISOString();\n const participants: ExpertParticipation[] = config.experts.map((expertId) => ({\n expertId,\n role: roleResolver(expertId),\n joinedAt: now,\n status: 'pending' as const,\n retryCount: 0,\n }));\n\n return {\n config,\n status: 'pending',\n participants,\n results: new Map(),\n reviews: [],\n votes: [],\n startedAt: now,\n messageLog: [],\n };\n}\n\n/**\n * Checks if session should transition to finalizing.\n */\nexport function shouldFinalize(\n pattern: CollaborationPattern,\n participants: ExpertParticipation[],\n results: Map<string, TaskResult>,\n votes: VoteMessage[],\n reviews: ReviewResponseMessage[]\n): boolean {\n switch (pattern) {\n case 'sequential':\n case 'parallel':\n return results.size === participants.length;\n case 'review':\n return reviews.length > 0 && results.size > 0;\n case 'consensus':\n return votes.length === participants.length;\n default:\n return false;\n }\n}\n","/**\n * @nexus-agents/agents - Collaboration Session\n *\n * Manages collaboration sessions between multiple experts.\n * Handles session lifecycle, message routing, and result collection.\n */\n\nimport type { Result, TaskResult, ILogger, AgentRole } from '../../core/index.js';\nimport { ok, err, AgentError, createLogger } from '../../core/index.js';\nimport type {\n CollaborationConfig,\n SessionState,\n SessionStatus,\n CollaborationMessage,\n CollaborationResult,\n VoteMessage,\n ReviewResponseMessage,\n TaskAssignmentMessage,\n} from './collaboration-types.js';\nimport { DEFAULT_TIMEOUTS, DEFAULT_MAX_RETRIES } from './collaboration-types.js';\nimport {\n getSequentialAssignments,\n getParallelAssignments,\n getReviewAssignments,\n getConsensusAssignments,\n isSessionSuccessful,\n buildExpertResults,\n buildAggregatedResult,\n validateConfig,\n createSessionState,\n shouldFinalize,\n} from './session-helpers.js';\n\n/**\n * Maximum number of event listeners allowed per session.\n * Prevents memory issues from unbounded listener growth.\n */\nconst MAX_EVENT_LISTENERS = 50;\n\n/** Options for creating a CollaborationSession. */\nexport interface CollaborationSessionOptions {\n logger?: ILogger;\n onStatusChange?: (status: SessionStatus) => void;\n onMessage?: (message: CollaborationMessage) => void;\n roleResolver?: (expertId: string) => AgentRole;\n}\n\n/** Session event types for callbacks. */\nexport type SessionEvent =\n | { type: 'status_change'; status: SessionStatus }\n | { type: 'expert_joined'; expertId: string }\n | { type: 'result_submitted'; expertId: string; result: TaskResult }\n | { type: 'review_completed'; reviewerId: string; approved: boolean }\n | { type: 'vote_received'; expertId: string; decision: string }\n | { type: 'timeout'; expertId?: string }\n | { type: 'error'; error: AgentError };\n\n/** Manages a collaboration session between multiple experts. */\nexport class CollaborationSession {\n private readonly logger: ILogger;\n private readonly onStatusChange: ((status: SessionStatus) => void) | undefined;\n private readonly onMessage: ((message: CollaborationMessage) => void) | undefined;\n private readonly roleResolver: (expertId: string) => AgentRole;\n private state: SessionState | null = null;\n private timeoutHandle: ReturnType<typeof setTimeout> | null = null;\n private readonly eventListeners: Array<(event: SessionEvent) => void> = [];\n\n constructor(options: CollaborationSessionOptions = {}) {\n this.logger = options.logger ?? createLogger({ component: 'CollaborationSession' });\n this.onStatusChange = options.onStatusChange;\n this.onMessage = options.onMessage;\n this.roleResolver = options.roleResolver ?? (() => 'custom' as AgentRole);\n }\n\n /** Starts a new collaboration session. */\n start(config: CollaborationConfig): Result<string, AgentError> {\n const validation = validateConfig(config);\n if (!validation.ok) return err(validation.error);\n\n if (this.state !== null) {\n return err(\n new AgentError('Session already in progress', {\n context: { existingSessionId: this.state.config.sessionId },\n })\n );\n }\n\n this.logger.info('Starting collaboration session', {\n sessionId: config.sessionId,\n pattern: config.pattern,\n expertCount: config.experts.length,\n });\n\n this.state = createSessionState(config, this.roleResolver);\n this.setStatus('in_progress');\n this.startTimeout(config.timeout ?? DEFAULT_TIMEOUTS[config.pattern]);\n\n return ok(config.sessionId);\n }\n\n /** Submits a result from an expert. */\n submitResult(expertId: string, result: TaskResult): Result<void, AgentError> {\n if (this.state === null) return err(new AgentError('No active session'));\n\n const participant = this.state.participants.find((p) => p.expertId === expertId);\n if (participant === undefined) {\n return err(new AgentError('Expert not in session', { context: { expertId } }));\n }\n if (participant.status === 'submitted') {\n return err(new AgentError('Expert already submitted result', { context: { expertId } }));\n }\n\n this.logger.info('Expert submitted result', { expertId, taskId: result.taskId });\n\n participant.status = 'submitted';\n participant.submittedAt = new Date().toISOString();\n this.state.results.set(expertId, result);\n\n this.logMessage({ type: 'result_submission', expertId, result });\n this.emitEvent({ type: 'result_submitted', expertId, result });\n this.checkProgress();\n\n return ok(undefined);\n }\n\n /** Requests a review from one expert to another. */\n requestReview(fromExpert: string, toExpert: string, artifact: unknown): Result<void, AgentError> {\n if (this.state === null) return err(new AgentError('No active session'));\n if (this.state.config.pattern !== 'review') {\n return err(new AgentError('Review requests only allowed in review pattern'));\n }\n\n const fromP = this.state.participants.find((p) => p.expertId === fromExpert);\n const toP = this.state.participants.find((p) => p.expertId === toExpert);\n if (fromP === undefined || toP === undefined) {\n return err(new AgentError('Expert not in session', { context: { fromExpert, toExpert } }));\n }\n\n this.logger.debug('Review requested', { fromExpert, toExpert });\n toP.status = 'reviewing';\n this.setStatus('awaiting_review');\n this.logMessage({ type: 'review_request', fromExpert, toExpert, artifact });\n\n return ok(undefined);\n }\n\n /** Submits a review response. */\n submitReview(\n reviewerId: string,\n requesterId: string,\n approved: boolean,\n feedback: string\n ): Result<void, AgentError> {\n if (this.state === null) return err(new AgentError('No active session'));\n\n const reviewer = this.state.participants.find((p) => p.expertId === reviewerId);\n if (reviewer === undefined) {\n return err(new AgentError('Reviewer not in session', { context: { reviewerId } }));\n }\n\n this.logger.info('Review submitted', { reviewerId, requesterId, approved });\n const response: ReviewResponseMessage = {\n type: 'review_response',\n reviewerId,\n requesterId,\n approved,\n feedback,\n };\n this.state.reviews.push(response);\n this.logMessage(response);\n this.emitEvent({ type: 'review_completed', reviewerId, approved });\n this.checkProgress();\n\n return ok(undefined);\n }\n\n /** Submits a vote for consensus protocol. */\n vote(\n expertId: string,\n decision: 'approve' | 'reject' | 'abstain',\n reasoning: string\n ): Result<void, AgentError> {\n if (this.state === null) return err(new AgentError('No active session'));\n if (this.state.config.pattern !== 'consensus') {\n return err(new AgentError('Voting only allowed in consensus pattern'));\n }\n\n const participant = this.state.participants.find((p) => p.expertId === expertId);\n if (participant === undefined) {\n return err(new AgentError('Expert not in session', { context: { expertId } }));\n }\n if (participant.status === 'voted') {\n return err(new AgentError('Expert already voted', { context: { expertId } }));\n }\n if (reasoning.trim().length === 0) {\n return err(new AgentError('Vote reasoning is required'));\n }\n\n this.logger.info('Vote submitted', { expertId, decision });\n participant.status = 'voted';\n const voteMessage: VoteMessage = { type: 'vote', expertId, decision, reasoning };\n this.state.votes.push(voteMessage);\n this.logMessage(voteMessage);\n\n if (this.state.status !== 'voting') this.setStatus('voting');\n this.emitEvent({ type: 'vote_received', expertId, decision });\n this.checkProgress();\n\n return ok(undefined);\n }\n\n getStatus(): SessionState | null {\n return this.state === null ? null : { ...this.state };\n }\n getSessionId(): string | null {\n return this.state?.config.sessionId ?? null;\n }\n\n /** Marks an expert as failed. */\n markExpertFailed(expertId: string, _error: string): Result<void, AgentError> {\n if (this.state === null) return err(new AgentError('No active session'));\n\n const participant = this.state.participants.find((p) => p.expertId === expertId);\n if (participant === undefined) {\n return err(new AgentError('Expert not in session', { context: { expertId } }));\n }\n\n const maxRetries = this.state.config.maxRetries ?? DEFAULT_MAX_RETRIES;\n participant.retryCount += 1;\n\n if (participant.retryCount > maxRetries) {\n this.logger.warn('Expert failed after max retries', { expertId });\n participant.status = 'failed';\n } else {\n this.logger.info('Expert failed, will retry', {\n expertId,\n retryCount: participant.retryCount,\n });\n participant.status = 'pending';\n }\n\n this.checkProgress();\n return ok(undefined);\n }\n\n /** Gets task assignments for experts based on pattern. */\n getTaskAssignments(): TaskAssignmentMessage[] {\n if (this.state === null) return [];\n const { config, participants, results } = this.state;\n\n switch (config.pattern) {\n case 'sequential':\n return getSequentialAssignments(config, participants, results);\n case 'parallel':\n return getParallelAssignments(config, participants);\n case 'review':\n return getReviewAssignments(config, participants, results);\n case 'consensus':\n return getConsensusAssignments(config, participants);\n default:\n return [];\n }\n }\n\n /** Finalizes the session and returns aggregated result. */\n finalize(): Result<CollaborationResult, AgentError> {\n if (this.state === null) return err(new AgentError('No active session'));\n\n this.clearTimeout();\n const endTime = new Date();\n const durationMs = endTime.getTime() - new Date(this.state.startedAt).getTime();\n\n const { config, participants, results, votes, reviews } = this.state;\n const allResults = Array.from(results.values());\n\n const success = isSessionSuccessful({\n pattern: config.pattern,\n participants,\n results,\n votes,\n reviews,\n requireUnanimous: config.requireUnanimous === true,\n minVotes: config.minVotes,\n });\n const baseResult = {\n sessionId: config.sessionId,\n pattern: config.pattern,\n aggregatedResult: buildAggregatedResult({\n pattern: config.pattern,\n results: allResults,\n participants,\n votes,\n reviews,\n endTime,\n }),\n expertResults: buildExpertResults(participants, results),\n durationMs,\n success,\n };\n\n const collaborationResult: CollaborationResult = success\n ? baseResult\n : { ...baseResult, error: this.state.error ?? 'Unknown error' };\n\n this.setStatus(success ? 'completed' : 'failed');\n this.state.completedAt = endTime.toISOString();\n this.logger.info('Session finalized', { sessionId: config.sessionId, success, durationMs });\n\n this.state = null;\n return ok(collaborationResult);\n }\n\n cancel(reason: string): void {\n if (this.state === null) return;\n this.clearTimeout();\n this.state.error = reason;\n this.setStatus('failed');\n this.logger.warn('Session cancelled', { sessionId: this.state.config.sessionId, reason });\n }\n\n addEventListener(listener: (event: SessionEvent) => void): void {\n if (this.eventListeners.length >= MAX_EVENT_LISTENERS) {\n throw new AgentError(\n `Maximum event listener limit (${String(MAX_EVENT_LISTENERS)}) reached`,\n {\n context: { currentCount: this.eventListeners.length, limit: MAX_EVENT_LISTENERS },\n }\n );\n }\n this.eventListeners.push(listener);\n }\n removeEventListener(listener: (event: SessionEvent) => void): void {\n const index = this.eventListeners.indexOf(listener);\n if (index !== -1) this.eventListeners.splice(index, 1);\n }\n\n private setStatus(status: SessionStatus): void {\n if (this.state === null) return;\n this.state.status = status;\n this.onStatusChange?.(status);\n this.emitEvent({ type: 'status_change', status });\n }\n\n private logMessage(message: CollaborationMessage): void {\n if (this.state !== null) this.state.messageLog.push(message);\n this.onMessage?.(message);\n }\n\n private startTimeout(timeoutMs: number): void {\n this.clearTimeout();\n this.timeoutHandle = setTimeout(() => {\n if (this.state !== null) {\n this.logger.warn('Session timed out', { sessionId: this.state.config.sessionId });\n this.state.error = 'Session timed out';\n this.setStatus('timed_out');\n this.emitEvent({ type: 'timeout' });\n }\n }, timeoutMs);\n }\n\n private clearTimeout(): void {\n if (this.timeoutHandle !== null) {\n clearTimeout(this.timeoutHandle);\n this.timeoutHandle = null;\n }\n }\n\n private checkProgress(): void {\n if (this.state === null) return;\n const { config, participants, results, votes, reviews } = this.state;\n\n if (shouldFinalize(config.pattern, participants, results, votes, reviews)) {\n this.setStatus('finalizing');\n }\n\n if (participants.every((p) => p.status === 'failed')) {\n this.state.error = 'All experts failed';\n this.setStatus('failed');\n }\n }\n\n private emitEvent(event: SessionEvent): void {\n for (const listener of this.eventListeners) {\n try {\n listener(event);\n } catch (e) {\n const errorObj = e instanceof Error ? e : new Error(String(e));\n this.logger.error('Event listener error', errorObj, { eventType: event.type });\n }\n }\n }\n}\n\nexport function createCollaborationSession(\n options?: CollaborationSessionOptions\n): CollaborationSession {\n return new CollaborationSession(options);\n}\n","/**\n * @nexus-agents/agents - Protocol Helpers\n *\n * Helper functions for collaboration protocol operations.\n * Extracted to keep the main protocol classes under 400 lines.\n */\n\nimport type { Task } from '../../core/index.js';\n\n/**\n * Extracts approval status from review output.\n */\nexport function extractApproval(output: unknown): boolean {\n if (typeof output === 'object' && output !== null && 'approved' in output) {\n return Boolean((output as Record<string, unknown>).approved);\n }\n if (typeof output === 'string') {\n const lowerOutput = output.toLowerCase();\n return lowerOutput.includes('approved') || lowerOutput.includes('lgtm');\n }\n return true;\n}\n\n/**\n * Extracts feedback from review output.\n */\nexport function extractFeedback(output: unknown): string {\n if (typeof output === 'object' && output !== null && 'feedback' in output) {\n return String((output as Record<string, unknown>).feedback);\n }\n if (typeof output === 'string') {\n return output;\n }\n return JSON.stringify(output);\n}\n\n/**\n * Vote decision type.\n */\nexport interface ParsedVote {\n decision: 'approve' | 'reject' | 'abstain';\n reasoning: string;\n}\n\ntype VoteDecision = 'approve' | 'reject' | 'abstain';\n\n/**\n * Checks if a string is a valid vote decision.\n */\nfunction isValidVoteDecision(value: string): value is VoteDecision {\n return value === 'approve' || value === 'reject' || value === 'abstain';\n}\n\n/**\n * Attempts to parse vote from an object with decision/reasoning fields.\n */\nfunction parseVoteFromDecisionField(obj: Record<string, unknown>): ParsedVote | null {\n if (!('decision' in obj && 'reasoning' in obj)) return null;\n const decision = String(obj.decision).toLowerCase();\n if (!isValidVoteDecision(decision)) return null;\n return { decision, reasoning: String(obj.reasoning) };\n}\n\n/**\n * Attempts to parse vote from an object with vote field.\n */\nfunction parseVoteFromVoteField(obj: Record<string, unknown>): ParsedVote | null {\n if (!('vote' in obj)) return null;\n const vote = String(obj.vote).toLowerCase();\n if (!isValidVoteDecision(vote)) return null;\n const reasoning = 'reasoning' in obj ? String(obj.reasoning) : 'No reasoning provided';\n return { decision: vote, reasoning };\n}\n\n/**\n * Determines vote decision from string content.\n */\nfunction determineVoteFromString(text: string): VoteDecision {\n const lower = text.toLowerCase();\n if (lower.includes('approve') || lower.includes('yes')) return 'approve';\n if (lower.includes('reject') || lower.includes('no')) return 'reject';\n return 'abstain';\n}\n\n/**\n * Extracts vote from output.\n */\nexport function extractVote(output: unknown): ParsedVote {\n if (typeof output === 'object' && output !== null) {\n const obj = output as Record<string, unknown>;\n const fromDecision = parseVoteFromDecisionField(obj);\n if (fromDecision !== null) return fromDecision;\n const fromVote = parseVoteFromVoteField(obj);\n if (fromVote !== null) return fromVote;\n }\n\n if (typeof output === 'string') {\n return { decision: determineVoteFromString(output), reasoning: output };\n }\n\n return { decision: 'abstain', reasoning: 'Could not parse vote from output' };\n}\n\n/**\n * Creates a review task from production output.\n */\nexport function createReviewTask(\n originalTask: Task,\n productionOutput: unknown,\n producerId: string\n): Task {\n return {\n id: `${originalTask.id}-review`,\n description: `Review the following work and provide feedback:\\n\\n${JSON.stringify(productionOutput, null, 2)}`,\n context: {\n ...originalTask.context,\n metadata: {\n ...originalTask.context.metadata,\n reviewContext: {\n originalTaskId: originalTask.id,\n producerId,\n productionOutput,\n },\n },\n },\n };\n}\n\n/**\n * Creates a voting task from original task.\n */\nexport function createVotingTask(originalTask: Task): Task {\n return {\n ...originalTask,\n description: `${originalTask.description}\\n\\nPlease analyze this task and provide your vote (approve/reject/abstain) with reasoning.`,\n };\n}\n\n/**\n * Sleep utility for delays.\n */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n","/**\n * @nexus-agents/agents - Review Collaboration Protocol\n *\n * Protocol implementation for review collaboration pattern where\n * one expert produces work and another reviews it.\n */\n\nimport type { Result, TaskResult, ILogger, IAgent, Task } from '../../core/index.js';\nimport { ok, err, AgentError, createLogger } from '../../core/index.js';\nimport type { CollaborationConfig, CollaborationResult } from './collaboration-types.js';\nimport { CollaborationSession, createCollaborationSession } from './collaboration-session.js';\nimport { extractApproval, extractFeedback, createReviewTask } from './protocol-helpers.js';\nimport type { ICollaborationProtocol, ProtocolOptions } from './collaboration-protocol.js';\n\n/**\n * Review collaboration protocol.\n */\nexport class ReviewProtocol implements ICollaborationProtocol {\n readonly pattern = 'review' as const;\n protected readonly logger: ILogger;\n protected session: CollaborationSession | null = null;\n protected cancelled = false;\n protected readonly options: ProtocolOptions;\n\n constructor(options: ProtocolOptions = {}) {\n this.options = options;\n this.logger = options.logger ?? createLogger({ component: 'ReviewProtocol' });\n }\n\n cancel(reason: string): void {\n this.cancelled = true;\n this.session?.cancel(reason);\n this.logger.info('Protocol cancelled', { reason });\n }\n\n async execute(\n config: CollaborationConfig,\n agents: Map<string, IAgent>\n ): Promise<Result<CollaborationResult, AgentError>> {\n const initResult = this.initReviewSession(config, agents);\n if (!initResult.ok) return err(initResult.error);\n\n const { session, producer, reviewer, producerId, reviewerId } = initResult.value;\n\n const productionResult = await this.executeProduction(\n session,\n producer,\n config.task,\n producerId\n );\n if (!productionResult.ok) return err(productionResult.error);\n\n const reviewResult = await this.executeReview(\n { session, reviewer, task: config.task, producerId, reviewerId },\n productionResult.value\n );\n if (!reviewResult.ok) return err(reviewResult.error);\n\n return session.finalize();\n }\n\n private initReviewSession(\n config: CollaborationConfig,\n agents: Map<string, IAgent>\n ): Result<\n {\n session: CollaborationSession;\n producer: IAgent;\n reviewer: IAgent;\n producerId: string;\n reviewerId: string;\n },\n AgentError\n > {\n const validation = this.validateAgents(config, agents);\n if (!validation.ok) return err(validation.error);\n\n if (config.experts.length < 2) {\n return err(new AgentError('Review protocol requires at least 2 experts'));\n }\n\n const producerId = config.experts[0];\n const reviewerId = config.experts[1];\n\n if (producerId === undefined || reviewerId === undefined) {\n return err(new AgentError('Invalid expert configuration'));\n }\n\n const producer = agents.get(producerId);\n const reviewer = agents.get(reviewerId);\n\n if (producer === undefined || reviewer === undefined) {\n return err(new AgentError('Required agents not found'));\n }\n\n this.cancelled = false;\n this.session = createCollaborationSession(this.options.sessionOptions);\n\n const startResult = this.session.start(config);\n if (!startResult.ok) return err(startResult.error);\n\n this.logger.info('Starting review protocol', {\n sessionId: config.sessionId,\n producerId,\n reviewerId,\n });\n\n return ok({ session: this.session, producer, reviewer, producerId, reviewerId });\n }\n\n private validateAgents(\n config: CollaborationConfig,\n agents: Map<string, IAgent>\n ): Result<void, AgentError> {\n for (const expertId of config.experts) {\n if (!agents.has(expertId)) {\n return err(\n new AgentError(`Agent not found: ${expertId}`, {\n context: { expertId, availableAgents: Array.from(agents.keys()) },\n })\n );\n }\n }\n return ok(undefined);\n }\n\n private async executeAgentTask(\n agent: IAgent,\n task: Task\n ): Promise<Result<TaskResult, AgentError>> {\n if (this.cancelled) {\n return err(new AgentError('Protocol cancelled'));\n }\n return agent.execute(task);\n }\n\n private async executeProduction(\n session: CollaborationSession,\n producer: IAgent,\n task: Task,\n producerId: string\n ): Promise<Result<TaskResult, AgentError>> {\n const productionResult = await this.executeAgentTask(producer, task);\n if (!productionResult.ok) {\n session.cancel(productionResult.error.message);\n return err(productionResult.error);\n }\n\n session.submitResult(producerId, productionResult.value);\n return ok(productionResult.value);\n }\n\n private async executeReview(\n ctx: ReviewContext,\n productionResult: TaskResult\n ): Promise<Result<TaskResult, AgentError>> {\n const { session, reviewer, task, producerId, reviewerId } = ctx;\n session.requestReview(producerId, reviewerId, productionResult.output);\n\n const reviewTask = createReviewTask(task, productionResult.output, producerId);\n\n const reviewResult = await this.executeAgentTask(reviewer, reviewTask);\n if (!reviewResult.ok) {\n session.cancel(reviewResult.error.message);\n return err(reviewResult.error);\n }\n\n session.submitResult(reviewerId, reviewResult.value);\n\n const reviewOutput = reviewResult.value.output;\n const approved = extractApproval(reviewOutput);\n const feedback = extractFeedback(reviewOutput);\n\n session.submitReview(reviewerId, producerId, approved, feedback);\n\n return ok(reviewResult.value);\n }\n}\n\n/**\n * Context for review execution.\n */\ninterface ReviewContext {\n session: CollaborationSession;\n reviewer: IAgent;\n task: Task;\n producerId: string;\n reviewerId: string;\n}\n","/**\n * @nexus-agents/agents - Consensus Collaboration Protocol\n *\n * Protocol implementation for consensus-based collaboration pattern where\n * multiple experts vote on decisions.\n */\n\nimport type { Result, TaskResult, ILogger, IAgent, Task } from '../../core/index.js';\nimport { ok, err, AgentError, createLogger } from '../../core/index.js';\nimport type { CollaborationConfig, CollaborationResult } from './collaboration-types.js';\nimport { CollaborationSession, createCollaborationSession } from './collaboration-session.js';\nimport { extractVote, createVotingTask } from './protocol-helpers.js';\nimport type { ICollaborationProtocol, ProtocolOptions } from './collaboration-protocol.js';\n\n/**\n * Consensus collaboration protocol.\n */\nexport class ConsensusProtocol implements ICollaborationProtocol {\n readonly pattern = 'consensus' as const;\n protected readonly logger: ILogger;\n protected session: CollaborationSession | null = null;\n protected cancelled = false;\n protected readonly options: ProtocolOptions;\n\n constructor(options: ProtocolOptions = {}) {\n this.options = options;\n this.logger = options.logger ?? createLogger({ component: 'ConsensusProtocol' });\n }\n\n cancel(reason: string): void {\n this.cancelled = true;\n this.session?.cancel(reason);\n this.logger.info('Protocol cancelled', { reason });\n }\n\n async execute(\n config: CollaborationConfig,\n agents: Map<string, IAgent>\n ): Promise<Result<CollaborationResult, AgentError>> {\n const validation = this.validateAgents(config, agents);\n if (!validation.ok) {\n return err(validation.error);\n }\n\n if (config.experts.length < 3) {\n return err(new AgentError('Consensus protocol requires at least 3 experts'));\n }\n\n this.cancelled = false;\n this.session = createCollaborationSession(this.options.sessionOptions);\n\n const startResult = this.session.start(config);\n if (!startResult.ok) {\n return err(startResult.error);\n }\n\n this.logger.info('Starting consensus protocol', {\n sessionId: config.sessionId,\n expertCount: config.experts.length,\n requireUnanimous: config.requireUnanimous,\n });\n\n const votingTask = createVotingTask(config.task);\n\n const promises = config.experts.map(async (expertId) => {\n const agent = agents.get(expertId);\n if (agent === undefined) {\n return { expertId, result: err(new AgentError(`Agent not found: ${expertId}`)) };\n }\n const result = await this.executeAgentTask(agent, votingTask);\n return { expertId, result };\n });\n\n const results = await Promise.all(promises);\n\n for (const { expertId, result } of results) {\n if (result.ok) {\n this.session.submitResult(expertId, result.value);\n const vote = extractVote(result.value.output);\n this.session.vote(expertId, vote.decision, vote.reasoning);\n } else {\n this.logger.warn('Expert failed in consensus voting', {\n expertId,\n error: result.error.message,\n });\n this.session.markExpertFailed(expertId, result.error.message);\n }\n }\n\n return this.session.finalize();\n }\n\n private validateAgents(\n config: CollaborationConfig,\n agents: Map<string, IAgent>\n ): Result<void, AgentError> {\n for (const expertId of config.experts) {\n if (!agents.has(expertId)) {\n return err(\n new AgentError(`Agent not found: ${expertId}`, {\n context: { expertId, availableAgents: Array.from(agents.keys()) },\n })\n );\n }\n }\n return ok(undefined);\n }\n\n private async executeAgentTask(\n agent: IAgent,\n task: Task\n ): Promise<Result<TaskResult, AgentError>> {\n if (this.cancelled) {\n return err(new AgentError('Protocol cancelled'));\n }\n return agent.execute(task);\n }\n}\n","/**\n * @nexus-agents/agents - Collaboration Protocols\n *\n * Protocol implementations for different collaboration patterns:\n * - Sequential: Experts work in order, passing results forward\n * - Parallel: Experts work simultaneously\n * - Review: One expert reviews another's work\n * - Consensus: Voting-based decision making\n */\n\nimport type { Result, TaskResult, ILogger, IAgent, Task } from '../../core/index.js';\nimport { ok, err, AgentError, createLogger } from '../../core/index.js';\nimport type { CollaborationConfig, CollaborationResult } from './collaboration-types.js';\nimport {\n CollaborationSession,\n createCollaborationSession,\n type CollaborationSessionOptions,\n} from './collaboration-session.js';\nimport { sleep } from './protocol-helpers.js';\n\n// Import and re-export ReviewProtocol and ConsensusProtocol from their dedicated modules\nimport { ReviewProtocol } from './review-protocol.js';\nimport { ConsensusProtocol } from './consensus-protocol.js';\nexport { ReviewProtocol, ConsensusProtocol };\n\n/**\n * Base interface for collaboration protocols.\n */\nexport interface ICollaborationProtocol {\n readonly pattern: CollaborationConfig['pattern'];\n execute(\n config: CollaborationConfig,\n agents: Map<string, IAgent>\n ): Promise<Result<CollaborationResult, AgentError>>;\n cancel(reason: string): void;\n}\n\n/**\n * Options for protocol execution.\n */\nexport interface ProtocolOptions {\n logger?: ILogger;\n sessionOptions?: CollaborationSessionOptions;\n sequentialDelay?: number;\n continueOnFailure?: boolean;\n}\n\n/**\n * Abstract base class for collaboration protocols.\n */\nabstract class BaseProtocol implements ICollaborationProtocol {\n abstract readonly pattern: CollaborationConfig['pattern'];\n protected readonly logger: ILogger;\n protected session: CollaborationSession | null = null;\n protected cancelled = false;\n\n constructor(protected readonly options: ProtocolOptions = {}) {\n this.logger = options.logger ?? createLogger({ component: 'CollaborationProtocol' });\n }\n\n abstract execute(\n config: CollaborationConfig,\n agents: Map<string, IAgent>\n ): Promise<Result<CollaborationResult, AgentError>>;\n\n cancel(reason: string): void {\n this.cancelled = true;\n this.session?.cancel(reason);\n this.logger.info('Protocol cancelled', { reason });\n }\n\n protected createSession(): CollaborationSession {\n this.session = createCollaborationSession(this.options.sessionOptions);\n return this.session;\n }\n\n protected async executeAgentTask(\n agent: IAgent,\n task: Task,\n previousResults?: TaskResult[]\n ): Promise<Result<TaskResult, AgentError>> {\n if (this.cancelled) {\n return err(new AgentError('Protocol cancelled'));\n }\n\n const enrichedTask: Task = {\n ...task,\n context: {\n ...task.context,\n metadata: {\n ...task.context.metadata,\n previousResults: previousResults?.map((r) => ({ taskId: r.taskId, output: r.output })),\n },\n },\n };\n\n return agent.execute(enrichedTask);\n }\n\n protected validateAgents(\n config: CollaborationConfig,\n agents: Map<string, IAgent>\n ): Result<void, AgentError> {\n for (const expertId of config.experts) {\n if (!agents.has(expertId)) {\n return err(\n new AgentError(`Agent not found: ${expertId}`, {\n context: { expertId, availableAgents: Array.from(agents.keys()) },\n })\n );\n }\n }\n return ok(undefined);\n }\n}\n\n/**\n * Sequential collaboration protocol.\n */\nexport class SequentialProtocol extends BaseProtocol {\n readonly pattern = 'sequential' as const;\n\n async execute(\n config: CollaborationConfig,\n agents: Map<string, IAgent>\n ): Promise<Result<CollaborationResult, AgentError>> {\n const initResult = this.initSession(config, agents);\n if (!initResult.ok) return err(initResult.error);\n\n const session = initResult.value;\n\n this.logger.info('Starting sequential protocol', {\n sessionId: config.sessionId,\n expertCount: config.experts.length,\n });\n\n const previousResults: TaskResult[] = [];\n const delay = this.options.sequentialDelay ?? 0;\n\n for (const [i, expertId] of config.experts.entries()) {\n if (this.checkCancelled(session)) break;\n\n const agent = agents.get(expertId);\n if (agent === undefined) continue;\n\n this.logger.debug('Executing sequential step', {\n step: i + 1,\n expertId,\n previousResultCount: previousResults.length,\n });\n\n const stepResult = await this.executeSequentialStep(\n session,\n agent,\n config.task,\n expertId,\n previousResults\n );\n if (!stepResult.ok) return err(stepResult.error);\n\n if (stepResult.value !== undefined) {\n previousResults.push(stepResult.value);\n }\n\n if (delay > 0 && i < config.experts.length - 1) {\n await sleep(delay);\n }\n }\n\n return session.finalize();\n }\n\n private initSession(\n config: CollaborationConfig,\n agents: Map<string, IAgent>\n ): Result<CollaborationSession, AgentError> {\n const validation = this.validateAgents(config, agents);\n if (!validation.ok) return err(validation.error);\n\n this.cancelled = false;\n const session = this.createSession();\n\n const startResult = session.start(config);\n if (!startResult.ok) return err(startResult.error);\n\n return ok(session);\n }\n\n private checkCancelled(session: CollaborationSession): boolean {\n if (this.cancelled) {\n session.cancel('Protocol cancelled');\n return true;\n }\n return false;\n }\n\n private async executeSequentialStep(\n session: CollaborationSession,\n agent: IAgent,\n task: Task,\n expertId: string,\n previousResults: TaskResult[]\n ): Promise<Result<TaskResult | undefined, AgentError>> {\n const result = await this.executeAgentTask(agent, task, previousResults);\n\n if (!result.ok) {\n if (this.options.continueOnFailure === true) {\n this.logger.warn('Expert failed, continuing', { expertId, error: result.error.message });\n session.markExpertFailed(expertId, result.error.message);\n return ok(undefined);\n }\n session.cancel(result.error.message);\n return err(result.error);\n }\n\n session.submitResult(expertId, result.value);\n return ok(result.value);\n }\n}\n\n/**\n * Parallel collaboration protocol.\n */\nexport class ParallelProtocol extends BaseProtocol {\n readonly pattern = 'parallel' as const;\n\n async execute(\n config: CollaborationConfig,\n agents: Map<string, IAgent>\n ): Promise<Result<CollaborationResult, AgentError>> {\n const validation = this.validateAgents(config, agents);\n if (!validation.ok) {\n return err(validation.error);\n }\n\n this.cancelled = false;\n const session = this.createSession();\n\n const startResult = session.start(config);\n if (!startResult.ok) {\n return err(startResult.error);\n }\n\n this.logger.info('Starting parallel protocol', {\n sessionId: config.sessionId,\n expertCount: config.experts.length,\n });\n\n const promises = config.experts.map(async (expertId) => {\n const agent = agents.get(expertId);\n if (agent === undefined) {\n return { expertId, result: err(new AgentError(`Agent not found: ${expertId}`)) };\n }\n const result = await this.executeAgentTask(agent, config.task);\n return { expertId, result };\n });\n\n const results = await Promise.all(promises);\n\n for (const { expertId, result } of results) {\n if (result.ok) {\n session.submitResult(expertId, result.value);\n } else {\n this.logger.warn('Expert failed in parallel execution', {\n expertId,\n error: result.error.message,\n });\n session.markExpertFailed(expertId, result.error.message);\n }\n }\n\n return session.finalize();\n }\n}\n\n/**\n * Factory for creating collaboration protocols.\n */\nexport class ProtocolFactory {\n private readonly options: ProtocolOptions;\n\n constructor(options: ProtocolOptions = {}) {\n this.options = options;\n }\n\n create(pattern: CollaborationConfig['pattern']): ICollaborationProtocol {\n switch (pattern) {\n case 'sequential':\n return new SequentialProtocol(this.options);\n case 'parallel':\n return new ParallelProtocol(this.options);\n case 'review':\n return new ReviewProtocol(this.options);\n case 'consensus':\n return new ConsensusProtocol(this.options);\n default:\n throw new AgentError(`Unknown protocol pattern: ${String(pattern)}`);\n }\n }\n\n async execute(\n config: CollaborationConfig,\n agents: Map<string, IAgent>\n ): Promise<Result<CollaborationResult, AgentError>> {\n const protocol = this.create(config.pattern);\n return protocol.execute(config, agents);\n }\n}\n\n/**\n * Creates a protocol factory.\n */\nexport function createProtocolFactory(options?: ProtocolOptions): ProtocolFactory {\n return new ProtocolFactory(options);\n}\n","/**\n * @nexus-agents/agents - Aggregator Helpers\n *\n * Helper functions for result aggregation operations.\n * Extracted to keep the main aggregator class under 400 lines.\n */\n\nimport type {\n CollaborationPattern,\n VoteMessage,\n ReviewResponseMessage,\n ResultConflict,\n} from './collaboration-types.js';\nimport type { AggregationStrategy, ExpertResult, ConflictResolver } from './result-aggregator.js';\n\n/**\n * Default conflict resolver - prefers higher confidence.\n */\nexport const defaultConflictResolver: ConflictResolver = (_conflict, result1, result2) => {\n const confidence1 = result1.confidence ?? 0.5;\n const confidence2 = result2.confidence ?? 0.5;\n return confidence1 >= confidence2 ? 'expert1' : 'expert2';\n};\n\n/**\n * Default quality scorer - based on result completeness.\n */\nexport function defaultQualityScorer(results: ExpertResult[], aggregatedOutput: unknown): number {\n if (results.length === 0) {\n return 0;\n }\n\n const avgConfidence = results.reduce((sum, r) => sum + (r.confidence ?? 0.5), 0) / results.length;\n const hasOutput = aggregatedOutput !== null && aggregatedOutput !== undefined;\n const outputScore = hasOutput ? 1 : 0;\n\n return (avgConfidence + outputScore) / 2;\n}\n\n/**\n * Determines aggregation strategy from pattern.\n */\nexport function determineStrategy(pattern: CollaborationPattern): AggregationStrategy {\n switch (pattern) {\n case 'sequential':\n return 'sequential_chain';\n case 'parallel':\n return 'merge';\n case 'review':\n return 'select_best';\n case 'consensus':\n return 'consensus';\n default:\n return 'merge';\n }\n}\n\n/**\n * Type guard for string arrays.\n */\nexport function areAllStrings(outputs: unknown[]): outputs is string[] {\n return outputs.every((o) => typeof o === 'string');\n}\n\n/**\n * Type guard for object arrays.\n */\nexport function areAllObjects(outputs: unknown[]): outputs is Record<string, unknown>[] {\n return outputs.every((o) => typeof o === 'object' && o !== null && !Array.isArray(o));\n}\n\n/**\n * Type guard for array arrays.\n */\nexport function areAllArrays(outputs: unknown[]): outputs is unknown[][] {\n return outputs.every((o) => Array.isArray(o));\n}\n\n/**\n * Merges string outputs.\n */\nexport function mergeStrings(outputs: string[]): string {\n const uniqueLines = new Set<string>();\n\n for (const output of outputs) {\n const lines = output\n .split('\\n')\n .map((l) => l.trim())\n .filter((l) => l.length > 0);\n for (const line of lines) {\n uniqueLines.add(line);\n }\n }\n\n return Array.from(uniqueLines).join('\\n');\n}\n\n/**\n * Merges array outputs.\n */\nexport function mergeArrays(outputs: unknown[][]): unknown[] {\n const seen = new Set<string>();\n const merged: unknown[] = [];\n\n for (const output of outputs) {\n for (const item of output) {\n const key = JSON.stringify(item);\n if (!seen.has(key)) {\n seen.add(key);\n merged.push(item);\n }\n }\n }\n\n return merged;\n}\n\n/**\n * Deep equality check.\n */\nexport function deepEquals(a: unknown, b: unknown): boolean {\n if (a === b) {\n return true;\n }\n\n if (typeof a !== typeof b) {\n return false;\n }\n\n if (typeof a !== 'object' || a === null || b === null) {\n return false;\n }\n\n const aObj = a as Record<string, unknown>;\n const bObj = b as Record<string, unknown>;\n\n const aKeys = Object.keys(aObj);\n const bKeys = Object.keys(bObj);\n\n if (aKeys.length !== bKeys.length) {\n return false;\n }\n\n return aKeys.every((key) => deepEquals(aObj[key], bObj[key]));\n}\n\ninterface ConflictContext {\n existing: { expertId: string; value: unknown };\n newResult: ExpertResult;\n key: string;\n value: unknown;\n results: ExpertResult[];\n conflictResolver: ConflictResolver;\n}\n\n/**\n * Handles a single field conflict.\n */\nfunction handleFieldConflict(ctx: ConflictContext): ResultConflict {\n const conflict: ResultConflict = {\n expert1Id: ctx.existing.expertId,\n expert2Id: ctx.newResult.expertId,\n field: ctx.key,\n description: `Conflicting values for field '${ctx.key}'`,\n resolution: 'unresolved',\n };\n\n const result1 = ctx.results.find((r) => r.expertId === ctx.existing.expertId);\n if (result1 !== undefined) {\n const resolution = ctx.conflictResolver(conflict, result1, ctx.newResult);\n conflict.resolution = resolution;\n const resolutionDesc = resolution === 'merged' ? 'merge' : `${resolution} value`;\n conflict.resolutionReason = `Resolved using ${resolutionDesc}`;\n }\n\n return conflict;\n}\n\n/**\n * Merges object outputs with conflict detection.\n */\nexport function mergeObjects(\n results: ExpertResult[],\n outputs: Record<string, unknown>[],\n conflictResolver: ConflictResolver\n): { output: unknown; conflicts: ResultConflict[] } {\n const merged: Record<string, unknown> = {};\n const conflicts: ResultConflict[] = [];\n const keyOwners = new Map<string, { expertId: string; value: unknown }>();\n\n for (let i = 0; i < outputs.length; i++) {\n const output = outputs[i];\n const result = results[i];\n if (output === undefined || result === undefined) continue;\n\n for (const [key, value] of Object.entries(output)) {\n const existing = keyOwners.get(key);\n\n if (existing === undefined) {\n keyOwners.set(key, { expertId: result.expertId, value });\n merged[key] = value;\n continue;\n }\n\n if (deepEquals(existing.value, value)) continue;\n\n const conflict = handleFieldConflict({\n existing,\n newResult: result,\n key,\n value,\n results,\n conflictResolver,\n });\n\n if (conflict.resolution === 'expert2') {\n merged[key] = value;\n keyOwners.set(key, { expertId: result.expertId, value });\n }\n\n conflicts.push(conflict);\n }\n }\n\n return { output: merged, conflicts };\n}\n\n/**\n * Selects the best result based on reviews and confidence.\n */\nexport function selectBest(results: ExpertResult[], reviews?: ReviewResponseMessage[]): unknown {\n if (results.length === 1) {\n return results[0]?.result.output;\n }\n\n if (reviews !== undefined && reviews.length > 0) {\n const approvedReview = reviews.find((r) => r.approved);\n if (approvedReview !== undefined) {\n const approvedResult = results.find((r) => r.expertId === approvedReview.requesterId);\n if (approvedResult !== undefined) {\n return approvedResult.result.output;\n }\n }\n }\n\n const sortedByConfidence = [...results].sort(\n (a, b) => (b.confidence ?? 0.5) - (a.confidence ?? 0.5)\n );\n\n return sortedByConfidence[0]?.result.output;\n}\n\n/**\n * Builds consensus from votes and results.\n */\nexport function buildConsensus(results: ExpertResult[], votes?: VoteMessage[]): unknown {\n if (votes === undefined || votes.length === 0) {\n return selectBest(results);\n }\n\n const approveVotes = votes.filter((v) => v.decision === 'approve');\n const rejectVotes = votes.filter((v) => v.decision === 'reject');\n\n const consensusDecision = approveVotes.length > rejectVotes.length ? 'approved' : 'rejected';\n\n const reasonings = votes.map((v) => ({\n expertId: v.expertId,\n decision: v.decision,\n reasoning: v.reasoning,\n }));\n\n return {\n decision: consensusDecision,\n approveCount: approveVotes.length,\n rejectCount: rejectVotes.length,\n abstainCount: votes.length - approveVotes.length - rejectVotes.length,\n reasonings,\n outputs: results.map((r) => ({\n expertId: r.expertId,\n output: r.result.output,\n })),\n };\n}\n\n/**\n * Chains sequential results together.\n */\nexport function chainSequential(results: ExpertResult[]): unknown {\n const sortedResults = [...results].sort((a, b) => (a.order ?? 0) - (b.order ?? 0));\n\n if (sortedResults.length === 1) {\n return sortedResults[0]?.result.output;\n }\n\n const lastResult = sortedResults[sortedResults.length - 1];\n\n return {\n finalOutput: lastResult?.result.output,\n chain: sortedResults.map((r, index) => ({\n step: index + 1,\n expertId: r.expertId,\n output: r.result.output,\n })),\n };\n}\n","/**\n * @nexus-agents/agents - Result Aggregator\n *\n * Aggregates results from multiple experts into a final output.\n * Handles merging, conflict detection, and quality scoring.\n */\n\nimport type { Result, TaskResult, ILogger } from '../../core/index.js';\nimport { ok, err, AgentError, createLogger } from '../../core/index.js';\nimport type {\n AggregatedResult,\n ResultConflict,\n CollaborationPattern,\n VoteMessage,\n ReviewResponseMessage,\n} from './collaboration-types.js';\nimport {\n defaultConflictResolver,\n defaultQualityScorer,\n determineStrategy,\n areAllStrings,\n areAllObjects,\n areAllArrays,\n mergeStrings,\n mergeArrays,\n mergeObjects,\n selectBest,\n buildConsensus,\n chainSequential,\n} from './aggregator-helpers.js';\n\n/**\n * Aggregation strategy types.\n */\nexport type AggregationStrategy = 'merge' | 'select_best' | 'consensus' | 'sequential_chain';\n\n/**\n * Options for result aggregation.\n */\nexport interface AggregatorOptions {\n logger?: ILogger;\n conflictResolver?: ConflictResolver;\n qualityScorer?: QualityScorer;\n minQualityScore?: number;\n}\n\n/**\n * Input for aggregation.\n */\nexport interface AggregatorInput {\n pattern: CollaborationPattern;\n results: ExpertResult[];\n votes?: VoteMessage[];\n reviews?: ReviewResponseMessage[];\n}\n\n/**\n * Expert result with metadata.\n */\nexport interface ExpertResult {\n expertId: string;\n result: TaskResult;\n confidence?: number;\n order?: number;\n}\n\n/**\n * Conflict resolver function type.\n */\nexport type ConflictResolver = (\n conflict: ResultConflict,\n result1: ExpertResult,\n result2: ExpertResult\n) => 'expert1' | 'expert2' | 'merged';\n\n/**\n * Quality scorer function type.\n */\nexport type QualityScorer = (results: ExpertResult[], aggregatedOutput: unknown) => number;\n\n/**\n * Aggregates results from multiple experts.\n */\nexport class ResultAggregator {\n private readonly logger: ILogger;\n private readonly conflictResolver: ConflictResolver;\n private readonly qualityScorer: QualityScorer;\n private readonly minQualityScore: number;\n\n constructor(options: AggregatorOptions = {}) {\n this.logger = options.logger ?? createLogger({ component: 'ResultAggregator' });\n this.conflictResolver = options.conflictResolver ?? defaultConflictResolver;\n this.qualityScorer = options.qualityScorer ?? defaultQualityScorer;\n this.minQualityScore = options.minQualityScore ?? 0;\n }\n\n /**\n * Aggregates expert results into a final result.\n */\n aggregate(input: AggregatorInput): Result<AggregatedResult, AgentError> {\n if (input.results.length === 0) {\n return err(new AgentError('No results to aggregate'));\n }\n\n this.logger.info('Aggregating results', {\n pattern: input.pattern,\n resultCount: input.results.length,\n });\n\n const strategy = determineStrategy(input.pattern);\n const { output: aggregatedOutput, conflicts } = this.applyStrategy(strategy, input);\n const qualityScore = this.qualityScorer(input.results, aggregatedOutput);\n\n const qualityCheck = this.checkQuality(qualityScore);\n if (!qualityCheck.ok) return err(qualityCheck.error);\n\n const result = this.buildResult(\n input.results,\n aggregatedOutput,\n strategy,\n conflicts,\n qualityScore\n );\n\n this.logger.info('Aggregation complete', {\n strategy,\n qualityScore: result.qualityScore,\n conflictCount: conflicts.length,\n });\n\n return ok(result);\n }\n\n private applyStrategy(\n strategy: AggregationStrategy,\n input: AggregatorInput\n ): { output: unknown; conflicts: ResultConflict[] } {\n switch (strategy) {\n case 'merge':\n return this.mergeResults(input.results);\n case 'select_best':\n return { output: selectBest(input.results, input.reviews), conflicts: [] };\n case 'consensus':\n return { output: buildConsensus(input.results, input.votes), conflicts: [] };\n case 'sequential_chain':\n return { output: chainSequential(input.results), conflicts: [] };\n }\n }\n\n private checkQuality(qualityScore: number): Result<void, AgentError> {\n if (qualityScore < this.minQualityScore) {\n return err(\n new AgentError('Aggregated result quality below threshold', {\n context: { qualityScore, minQualityScore: this.minQualityScore },\n })\n );\n }\n return ok(undefined);\n }\n\n private buildResult(\n results: ExpertResult[],\n output: unknown,\n strategy: AggregationStrategy,\n conflicts: ResultConflict[],\n qualityScore: number\n ): AggregatedResult {\n const totalTokensUsed = results.reduce((s, r) => s + r.result.metadata.tokensUsed, 0);\n const avgConfidence = results.reduce((s, r) => s + (r.confidence ?? 0.5), 0) / results.length;\n\n return {\n output,\n strategy,\n qualityScore: Math.round(qualityScore * 100) / 100,\n conflicts,\n metadata: {\n resultCount: results.length,\n conflictCount: conflicts.length,\n averageConfidence: Math.round(avgConfidence * 100) / 100,\n totalTokensUsed,\n aggregatedAt: new Date().toISOString(),\n },\n };\n }\n\n /**\n * Merges multiple results into one.\n */\n private mergeResults(results: ExpertResult[]): { output: unknown; conflicts: ResultConflict[] } {\n if (results.length === 1) {\n return { output: results[0]?.result.output, conflicts: [] };\n }\n\n const conflicts: ResultConflict[] = [];\n const outputs = results.map((r) => r.result.output);\n\n if (areAllStrings(outputs)) {\n return { output: mergeStrings(outputs), conflicts };\n }\n\n if (areAllObjects(outputs)) {\n return mergeObjects(results, outputs, this.conflictResolver);\n }\n\n if (areAllArrays(outputs)) {\n return { output: mergeArrays(outputs), conflicts };\n }\n\n const merged = {\n sources: results.map((r) => ({\n expertId: r.expertId,\n output: r.result.output,\n })),\n };\n\n return { output: merged, conflicts };\n }\n}\n\n/**\n * Creates a result aggregator.\n */\nexport function createResultAggregator(options?: AggregatorOptions): ResultAggregator {\n return new ResultAggregator(options);\n}\n\n/**\n * Convenience function to aggregate results.\n */\nexport function aggregateResults(\n input: AggregatorInput,\n options?: AggregatorOptions\n): Result<AggregatedResult, AgentError> {\n const aggregator = createResultAggregator(options);\n return aggregator.aggregate(input);\n}\n","/**\n * @nexus-agents/workflows - Workflow Parser\n *\n * Parses and validates workflow definitions from YAML and JSON formats.\n * Uses Zod schemas for runtime validation at the parsing boundary.\n */\n\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport * as yaml from 'yaml';\nimport { type Result, ok, err, ParseError, SecurityError } from '../core/index.js';\nimport type { WorkflowDefinition, WorkflowStep, InputDefinition } from '../core/index.js';\nimport {\n WorkflowDefinitionSchema,\n formatZodErrors,\n type WorkflowDefinitionOutput,\n} from './workflow-types.js';\nimport { validateDependencyGraph } from './dependency-graph.js';\n\n/**\n * Maximum file size for workflow templates (1MB).\n */\nconst MAX_FILE_SIZE_BYTES = 1024 * 1024;\n\n/**\n * Supported workflow file extensions.\n */\nconst SUPPORTED_EXTENSIONS = ['.yaml', '.yml', '.json'] as const;\n\n/**\n * Validates that a file path is within the allowed root directory.\n * Prevents path traversal attacks (e.g., ../../../etc/passwd).\n * @param userPath - The user-provided file path\n * @param allowedRoot - The root directory that paths must be within\n * @returns Result with validated absolute path or SecurityError\n */\nfunction validatePath(userPath: string, allowedRoot: string): Result<string, SecurityError> {\n const resolvedRoot = path.resolve(allowedRoot);\n const resolved = path.resolve(allowedRoot, userPath);\n\n if (!resolved.startsWith(resolvedRoot + path.sep) && resolved !== resolvedRoot) {\n return err(\n new SecurityError('Path traversal detected: path escapes allowed root directory', {\n context: { userPath, allowedRoot: resolvedRoot },\n })\n );\n }\n return ok(resolved);\n}\n\n/**\n * Parses a YAML string into a WorkflowDefinition.\n * @param content - YAML string content\n * @returns Result with WorkflowDefinition or ParseError\n */\nexport function parseWorkflowYaml(content: string): Result<WorkflowDefinition, ParseError> {\n // Parse YAML to JavaScript object\n let parsed: unknown;\n try {\n parsed = yaml.parse(content, {\n strict: true,\n uniqueKeys: true,\n });\n } catch (e) {\n const yamlError = e as yaml.YAMLParseError;\n const linePos = yamlError.linePos?.[0];\n const errorOptions: { line?: number; column?: number } = {};\n if (linePos?.line !== undefined) {\n errorOptions.line = linePos.line;\n }\n if (linePos?.col !== undefined) {\n errorOptions.column = linePos.col;\n }\n return err(new ParseError(`YAML parse error: ${yamlError.message}`, errorOptions));\n }\n\n // Validate against schema\n return validateWorkflowObject(parsed);\n}\n\n/**\n * Parses a JSON string into a WorkflowDefinition.\n * @param content - JSON string content\n * @returns Result with WorkflowDefinition or ParseError\n */\nexport function parseWorkflowJson(content: string): Result<WorkflowDefinition, ParseError> {\n // Parse JSON to JavaScript object\n let parsed: unknown;\n try {\n parsed = JSON.parse(content) as unknown;\n } catch (e) {\n const jsonError = e as SyntaxError;\n // Extract line/column from JSON parse error message if possible\n const posMatch = jsonError.message.match(/position (\\d+)/);\n const matchGroup = posMatch?.[1];\n const position = matchGroup !== undefined ? parseInt(matchGroup, 10) : undefined;\n const lineInfo = position !== undefined ? findLineColumn(content, position) : undefined;\n\n const errorOptions: { line?: number; column?: number } = {};\n if (lineInfo?.line !== undefined) {\n errorOptions.line = lineInfo.line;\n }\n if (lineInfo?.column !== undefined) {\n errorOptions.column = lineInfo.column;\n }\n\n return err(new ParseError(`JSON parse error: ${jsonError.message}`, errorOptions));\n }\n\n // Validate against schema\n return validateWorkflowObject(parsed);\n}\n\n/**\n * Validates a parsed object against the WorkflowDefinition schema.\n * @param obj - Parsed object to validate\n * @returns Result with WorkflowDefinition or ParseError\n */\nfunction validateWorkflowObject(obj: unknown): Result<WorkflowDefinition, ParseError> {\n const result = WorkflowDefinitionSchema.safeParse(obj);\n\n if (!result.success) {\n const issues = formatZodErrors(result.error);\n const message = issues\n .map((issue) => {\n const pathStr = issue.path.length > 0 ? issue.path.join('.') : 'root';\n return `${pathStr}: ${issue.message}`;\n })\n .join('; ');\n\n return err(new ParseError(`Validation error: ${message}`));\n }\n\n // Convert Zod output to WorkflowDefinition interface\n const workflow = toWorkflowDefinition(result.data);\n\n // Validate dependency graph\n const graphResult = validateDependencyGraph(workflow);\n if (!graphResult.ok) {\n return graphResult;\n }\n\n return ok(workflow);\n}\n\n/**\n * Maps Zod input definition output to core InputDefinition.\n */\nfunction mapInputDefinition(input: WorkflowDefinitionOutput['inputs'][number]): InputDefinition {\n const inputDef: InputDefinition = {\n name: input.name,\n type: input.type,\n required: input.required,\n };\n if (input.description !== undefined) inputDef.description = input.description;\n if (input.default !== undefined) inputDef.default = input.default;\n return inputDef;\n}\n\n/**\n * Maps Zod step definition output to core WorkflowStep.\n */\nfunction mapWorkflowStep(step: WorkflowDefinitionOutput['steps'][number]): WorkflowStep {\n const stepDef: WorkflowStep = {\n id: step.id,\n agent: step.agent,\n action: step.action,\n inputs: step.inputs,\n };\n if (step.dependsOn !== undefined) stepDef.dependsOn = step.dependsOn;\n if (step.parallel !== undefined) stepDef.parallel = step.parallel;\n if (step.retries !== undefined) stepDef.retries = step.retries;\n if (step.timeout !== undefined) stepDef.timeout = step.timeout;\n if (step.condition !== undefined) stepDef.condition = step.condition;\n return stepDef;\n}\n\n/**\n * Converts Zod schema output to WorkflowDefinition interface.\n * This ensures compatibility with the core types and exactOptionalPropertyTypes.\n */\nfunction toWorkflowDefinition(data: WorkflowDefinitionOutput): WorkflowDefinition {\n const workflow: WorkflowDefinition = {\n name: data.name,\n version: data.version,\n inputs: data.inputs.map(mapInputDefinition),\n steps: data.steps.map(mapWorkflowStep),\n };\n if (data.description !== undefined) workflow.description = data.description;\n if (data.timeout !== undefined) workflow.timeout = data.timeout;\n return workflow;\n}\n\n/**\n * Loads and parses a workflow definition from a file.\n * @param filePath - Path to the workflow file\n * @param allowedRoot - Root directory for path validation (defaults to process.cwd())\n * @returns Result with WorkflowDefinition or ParseError/SecurityError\n */\nexport async function loadWorkflowFile(\n filePath: string,\n allowedRoot: string = process.cwd()\n): Promise<Result<WorkflowDefinition, ParseError | SecurityError>> {\n // Validate path to prevent path traversal attacks\n const pathValidation = validatePath(filePath, allowedRoot);\n if (!pathValidation.ok) {\n return pathValidation;\n }\n const validatedPath = pathValidation.value;\n\n // Validate file extension\n const ext = path.extname(validatedPath).toLowerCase();\n if (!SUPPORTED_EXTENSIONS.includes(ext as (typeof SUPPORTED_EXTENSIONS)[number])) {\n return err(\n new ParseError(\n `Unsupported file extension: ${ext}. Supported: ${SUPPORTED_EXTENSIONS.join(', ')}`\n )\n );\n }\n\n // Read file with size check\n let content: string;\n try {\n const stats = await fs.stat(validatedPath);\n if (stats.size > MAX_FILE_SIZE_BYTES) {\n return err(\n new ParseError(\n `File too large: ${String(stats.size)} bytes. Maximum: ${String(MAX_FILE_SIZE_BYTES)} bytes`\n )\n );\n }\n content = await fs.readFile(validatedPath, 'utf-8');\n } catch (e) {\n const fsError = e as NodeJS.ErrnoException;\n if (fsError.code === 'ENOENT') {\n return err(new ParseError(`File not found: ${validatedPath}`));\n }\n if (fsError.code === 'EACCES') {\n return err(new ParseError(`Permission denied: ${validatedPath}`));\n }\n return err(new ParseError(`Failed to read file: ${fsError.message}`));\n }\n\n // Parse based on extension\n if (ext === '.json') {\n return parseWorkflowJson(content);\n }\n return parseWorkflowYaml(content);\n}\n\n/**\n * Validates a WorkflowDefinition object.\n * Useful for validating programmatically created workflows.\n * @param workflow - WorkflowDefinition to validate\n * @returns Result with void or ParseError\n */\nexport function validateWorkflow(workflow: WorkflowDefinition): Result<void, ParseError> {\n // Re-validate through the schema\n const result = WorkflowDefinitionSchema.safeParse(workflow);\n\n if (!result.success) {\n const issues = formatZodErrors(result.error);\n const message = issues\n .map((issue) => {\n const pathStr = issue.path.length > 0 ? issue.path.join('.') : 'root';\n return `${pathStr}: ${issue.message}`;\n })\n .join('; ');\n\n return err(new ParseError(`Validation error: ${message}`));\n }\n\n // Validate dependency graph\n const graphResult = validateDependencyGraph(workflow);\n if (!graphResult.ok) {\n return err(graphResult.error);\n }\n\n return ok(undefined);\n}\n\n/**\n * Finds line and column number from a character position.\n * @param content - The full content string\n * @param position - Character position in the string\n * @returns Line and column numbers (1-indexed)\n */\nfunction findLineColumn(content: string, position: number): { line: number; column: number } {\n let line = 1;\n let column = 1;\n\n for (let i = 0; i < position && i < content.length; i++) {\n if (content[i] === '\\n') {\n line++;\n column = 1;\n } else {\n column++;\n }\n }\n\n return { line, column };\n}\n","/**\n * @nexus-agents/workflows - Workflow Types\n *\n * Zod schemas for runtime validation of workflow definitions.\n * These schemas validate YAML/JSON workflow templates at parse time.\n */\n\nimport { z } from 'zod';\n\n/**\n * Input types supported in workflow definitions.\n */\nexport const InputTypeSchema = z.enum(['string', 'number', 'boolean', 'object', 'array']);\n\nexport type InputType = z.infer<typeof InputTypeSchema>;\n\n/**\n * Schema for workflow input definitions.\n * Inputs are parameters that must be provided when executing a workflow.\n */\nexport const InputDefinitionSchema = z\n .object({\n /** Input parameter name */\n name: z\n .string()\n .min(1, 'Input name is required')\n .regex(\n /^[a-zA-Z_][a-zA-Z0-9_]*$/,\n 'Input name must be a valid identifier (letters, numbers, underscores, starting with letter or underscore)'\n ),\n /** Input data type */\n type: InputTypeSchema,\n /** Human-readable description */\n description: z.string().optional(),\n /** Whether this input is required */\n required: z.boolean().default(true),\n /** Default value if not provided */\n default: z.unknown().optional(),\n })\n .strict();\n\nexport type InputDefinitionInput = z.input<typeof InputDefinitionSchema>;\nexport type InputDefinitionOutput = z.output<typeof InputDefinitionSchema>;\n\n/**\n * Agent roles that can execute workflow steps.\n */\nexport const AgentRoleSchema = z.enum([\n 'tech_lead',\n 'code_expert',\n 'architecture_expert',\n 'security_expert',\n 'documentation_expert',\n 'testing_expert',\n 'custom',\n]);\n\nexport type AgentRoleType = z.infer<typeof AgentRoleSchema>;\n\n/**\n * Schema for a single workflow step.\n * Steps are the atomic units of work in a workflow.\n */\nexport const WorkflowStepSchema = z\n .object({\n /** Unique identifier for this step (must be unique within workflow) */\n id: z\n .string()\n .min(1, 'Step ID is required')\n .regex(\n /^[a-zA-Z_][a-zA-Z0-9_-]*$/,\n 'Step ID must be a valid identifier (letters, numbers, underscores, hyphens)'\n ),\n /** Agent role to execute this step */\n agent: AgentRoleSchema,\n /** Action/task to perform */\n action: z.string().min(1, 'Action is required'),\n /** Input parameters for this step */\n inputs: z.record(z.string(), z.unknown()).default({}),\n /** Step IDs that must complete before this step runs */\n dependsOn: z.array(z.string()).optional(),\n /** Whether this step can run in parallel with its dependencies */\n parallel: z.boolean().optional(),\n /** Number of retry attempts on failure */\n retries: z.number().int().min(0).max(10).optional(),\n /** Timeout in milliseconds */\n timeout: z.number().int().positive().optional(),\n /** Condition expression for conditional execution */\n condition: z.string().optional(),\n })\n .strict();\n\nexport type WorkflowStepInput = z.input<typeof WorkflowStepSchema>;\nexport type WorkflowStepOutput = z.output<typeof WorkflowStepSchema>;\n\n/**\n * Semantic version pattern for workflow versions.\n */\nconst VERSION_REGEX = /^\\d+\\.\\d+\\.\\d+(-[a-zA-Z0-9.-]+)?(\\+[a-zA-Z0-9.-]+)?$/;\n\n/**\n * Schema for a complete workflow definition.\n * This is the top-level structure of a workflow template file.\n */\nexport const WorkflowDefinitionSchema = z\n .object({\n /** Workflow name */\n name: z\n .string()\n .min(1, 'Workflow name is required')\n .max(100, 'Workflow name must be at most 100 characters'),\n /** Semantic version string */\n version: z\n .string()\n .regex(VERSION_REGEX, 'Version must be valid semver (e.g., 1.0.0, 1.0.0-beta.1)'),\n /** Human-readable description */\n description: z.string().max(1000).optional(),\n /** Input parameter definitions */\n inputs: z.array(InputDefinitionSchema).default([]),\n /** Workflow steps to execute */\n steps: z.array(WorkflowStepSchema).min(1, 'Workflow must have at least one step'),\n /** Global timeout in milliseconds */\n timeout: z.number().int().positive().optional(),\n })\n .strict();\n\nexport type WorkflowDefinitionInput = z.input<typeof WorkflowDefinitionSchema>;\nexport type WorkflowDefinitionOutput = z.output<typeof WorkflowDefinitionSchema>;\n\n/**\n * Validation result with detailed error information.\n */\nexport interface ValidationIssue {\n /** Path to the problematic field */\n path: (string | number)[];\n /** Error message */\n message: string;\n /** Error code from Zod */\n code: string;\n}\n\n/**\n * Formats Zod errors into ValidationIssue array.\n * @param error - Zod error object\n * @returns Array of validation issues\n */\nexport function formatZodErrors(error: z.ZodError): ValidationIssue[] {\n return error.issues.map((issue) => ({\n path: issue.path,\n message: issue.message,\n code: issue.code,\n }));\n}\n","/**\n * @nexus-agents/workflows - Dependency Graph\n *\n * Builds and validates step dependency graphs for workflow definitions.\n * Detects circular dependencies using Kahn's algorithm for topological sort.\n */\n\nimport { type Result, ok, err, ParseError } from '../core/index.js';\nimport type { WorkflowDefinition, WorkflowStep } from '../core/index.js';\n\n/**\n * Represents a node in the dependency graph.\n */\ninterface GraphNode {\n /** Step ID */\n id: string;\n /** IDs of steps this node depends on */\n dependencies: Set<string>;\n /** IDs of steps that depend on this node */\n dependents: Set<string>;\n}\n\n/**\n * Dependency graph for workflow steps.\n */\nexport class DependencyGraph {\n private readonly nodes: Map<string, GraphNode> = new Map();\n\n /**\n * Adds a step to the graph.\n * @param step - The workflow step to add\n */\n addStep(step: WorkflowStep): void {\n const node: GraphNode = {\n id: step.id,\n dependencies: new Set(step.dependsOn ?? []),\n dependents: new Set(),\n };\n this.nodes.set(step.id, node);\n }\n\n /**\n * Builds the reverse dependency links (dependents).\n */\n buildReverseLinks(): void {\n for (const node of this.nodes.values()) {\n for (const depId of node.dependencies) {\n const depNode = this.nodes.get(depId);\n if (depNode) {\n depNode.dependents.add(node.id);\n }\n }\n }\n }\n\n /**\n * Gets all step IDs in the graph.\n */\n getStepIds(): string[] {\n return Array.from(this.nodes.keys());\n }\n\n /**\n * Gets a node by step ID.\n */\n getNode(id: string): GraphNode | undefined {\n return this.nodes.get(id);\n }\n\n /**\n * Validates that all dependency references exist.\n * @returns Result with void or ParseError containing missing references\n */\n validateReferences(): Result<void, ParseError> {\n const missingRefs: Array<{ stepId: string; missingDep: string }> = [];\n\n for (const [stepId, node] of this.nodes) {\n for (const depId of node.dependencies) {\n if (!this.nodes.has(depId)) {\n missingRefs.push({ stepId, missingDep: depId });\n }\n }\n }\n\n if (missingRefs.length > 0) {\n const messages = missingRefs.map(\n (ref) => `Step '${ref.stepId}' depends on non-existent step '${ref.missingDep}'`\n );\n return err(new ParseError(`Missing step references: ${messages.join('; ')}`));\n }\n\n return ok(undefined);\n }\n\n /**\n * Validates that all step IDs are unique.\n * @param steps - Array of workflow steps\n * @returns Result with void or ParseError for duplicates\n */\n static validateUniqueIds(steps: WorkflowStep[]): Result<void, ParseError> {\n const seen = new Set<string>();\n const duplicates: string[] = [];\n\n for (const step of steps) {\n if (seen.has(step.id)) {\n duplicates.push(step.id);\n }\n seen.add(step.id);\n }\n\n if (duplicates.length > 0) {\n return err(new ParseError(`Duplicate step IDs: ${duplicates.join(', ')}`));\n }\n\n return ok(undefined);\n }\n\n /**\n * Initializes in-degree map for Kahn's algorithm.\n */\n private initializeInDegrees(): Map<string, number> {\n const inDegree = new Map<string, number>();\n for (const [id, node] of this.nodes) {\n inDegree.set(id, node.dependencies.size);\n }\n return inDegree;\n }\n\n /**\n * Gets initial queue of nodes with zero dependencies.\n */\n private getInitialQueue(inDegree: Map<string, number>): string[] {\n const queue: string[] = [];\n for (const [id, degree] of inDegree) {\n if (degree === 0) queue.push(id);\n }\n return queue;\n }\n\n /**\n * Processes a single node in Kahn's algorithm.\n */\n private processNode(current: string, inDegree: Map<string, number>, queue: string[]): void {\n const node = this.nodes.get(current);\n if (node === undefined) return;\n for (const dependentId of node.dependents) {\n const newDegree = (inDegree.get(dependentId) ?? 0) - 1;\n inDegree.set(dependentId, newDegree);\n if (newDegree === 0) queue.push(dependentId);\n }\n }\n\n /**\n * Detects circular dependencies using Kahn's algorithm.\n * @returns Result with topologically sorted step IDs or ParseError for cycles\n */\n detectCycles(): Result<string[], ParseError> {\n const inDegree = this.initializeInDegrees();\n const queue = this.getInitialQueue(inDegree);\n const sorted: string[] = [];\n\n while (queue.length > 0) {\n const current = queue.shift();\n if (current === undefined) break;\n sorted.push(current);\n this.processNode(current, inDegree, queue);\n }\n\n if (sorted.length !== this.nodes.size) {\n return this.createCycleError(sorted);\n }\n\n return ok(sorted);\n }\n\n /**\n * Creates error for detected cycle.\n */\n private createCycleError(sorted: string[]): Result<never, ParseError> {\n const cycleNodes = Array.from(this.nodes.keys()).filter((id) => !sorted.includes(id));\n const cyclePath = this.findCyclePath(cycleNodes);\n const firstNode = cyclePath[0] ?? 'unknown';\n return err(\n new ParseError(`Circular dependency detected: ${cyclePath.join(' -> ')} -> ${firstNode}`)\n );\n }\n\n /**\n * Finds a cycle path starting from one of the cycle nodes.\n * Uses DFS to trace back through dependencies.\n * @param cycleNodes - Nodes known to be in cycles\n * @returns Array of step IDs forming a cycle\n */\n private findCyclePath(cycleNodes: string[]): string[] {\n const firstNode = cycleNodes[0];\n if (firstNode === undefined) {\n return [];\n }\n\n const startNode: string = firstNode;\n const visited = new Set<string>();\n const path: string[] = [];\n\n const dfs = (nodeId: string): boolean => {\n if (path.includes(nodeId)) {\n // Found the cycle, trim to just the cycle\n const cycleStart = path.indexOf(nodeId);\n path.splice(0, cycleStart);\n return true;\n }\n\n if (visited.has(nodeId)) {\n return false;\n }\n\n visited.add(nodeId);\n path.push(nodeId);\n\n const node = this.nodes.get(nodeId);\n if (node) {\n for (const depId of node.dependencies) {\n if (cycleNodes.includes(depId)) {\n if (dfs(depId)) {\n return true;\n }\n }\n }\n }\n\n path.pop();\n return false;\n };\n\n dfs(startNode);\n return path.length > 0 ? path : cycleNodes.slice(0, 3);\n }\n\n /**\n * Gets the execution order (topologically sorted step IDs).\n * @returns Result with sorted step IDs or ParseError\n */\n getExecutionOrder(): Result<string[], ParseError> {\n return this.detectCycles();\n }\n}\n\n/**\n * Builds a dependency graph from a workflow definition.\n * @param workflow - The workflow definition\n * @returns The constructed dependency graph\n */\nexport function buildDependencyGraph(workflow: WorkflowDefinition): DependencyGraph {\n const graph = new DependencyGraph();\n\n for (const step of workflow.steps) {\n graph.addStep(step);\n }\n\n graph.buildReverseLinks();\n return graph;\n}\n\n/**\n * Validates the dependency graph of a workflow.\n * Checks for:\n * - Duplicate step IDs\n * - Missing step references\n * - Circular dependencies\n *\n * @param workflow - The workflow definition to validate\n * @returns Result with void or ParseError\n */\nexport function validateDependencyGraph(workflow: WorkflowDefinition): Result<void, ParseError> {\n // Check for duplicate step IDs\n const uniqueResult = DependencyGraph.validateUniqueIds(workflow.steps);\n if (!uniqueResult.ok) {\n return uniqueResult;\n }\n\n // Build the graph\n const graph = buildDependencyGraph(workflow);\n\n // Check for missing references\n const refResult = graph.validateReferences();\n if (!refResult.ok) {\n return refResult;\n }\n\n // Check for cycles\n const cycleResult = graph.detectCycles();\n if (!cycleResult.ok) {\n return err(cycleResult.error);\n }\n\n return ok(undefined);\n}\n\n/**\n * Gets the topologically sorted execution order for a workflow.\n * Used for parsing validation (returns ParseError).\n * For execution planning, use createExecutionPlan from execution-planner.\n *\n * @param workflow - The workflow definition\n * @returns Result with sorted step IDs or ParseError\n */\nexport function getTopologicalOrder(workflow: WorkflowDefinition): Result<string[], ParseError> {\n const graph = buildDependencyGraph(workflow);\n\n const refResult = graph.validateReferences();\n if (!refResult.ok) {\n return err(refResult.error);\n }\n\n return graph.getExecutionOrder();\n}\n","/**\n * @nexus-agents/workflows - Task Queue\n *\n * Simple task queue for limiting concurrent task execution.\n * Provides cancellation support via AbortController.\n */\n\n/**\n * Task function type.\n */\ntype Task<T> = (signal: AbortSignal) => Promise<T>;\n\n/**\n * Queued task with its resolve/reject handlers.\n */\ninterface QueuedTask<T> {\n task: Task<T>;\n resolve: (value: T) => void;\n reject: (error: Error) => void;\n}\n\n/**\n * A task queue that limits concurrent execution.\n *\n * @template T - The return type of tasks in this queue\n */\nexport class TaskQueue<T> {\n private readonly concurrency: number;\n private readonly queue: QueuedTask<T>[] = [];\n private running = 0;\n private readonly abortController: AbortController;\n private cancelled = false;\n\n /**\n * Creates a new TaskQueue.\n *\n * @param concurrency - Maximum number of concurrent tasks (default: 5)\n */\n constructor(concurrency = 5) {\n if (concurrency < 1) {\n throw new Error('Concurrency must be at least 1');\n }\n this.concurrency = concurrency;\n this.abortController = new AbortController();\n }\n\n /**\n * Adds a task to the queue for execution.\n *\n * @param task - The async task to execute\n * @returns Promise that resolves with the task result\n * @throws Error if the queue has been cancelled\n */\n add(task: Task<T>): Promise<T> {\n if (this.cancelled) {\n return Promise.reject(new Error('Queue has been cancelled'));\n }\n\n return new Promise<T>((resolve, reject) => {\n this.queue.push({ task, resolve, reject });\n this.processNext();\n });\n }\n\n /**\n * Cancels all pending and running tasks.\n * Running tasks receive an abort signal.\n */\n cancel(): void {\n this.cancelled = true;\n this.abortController.abort();\n\n // Reject all queued tasks\n const error = new Error('Queue cancelled');\n for (const item of this.queue) {\n item.reject(error);\n }\n this.queue.length = 0;\n }\n\n /**\n * Returns whether the queue has been cancelled.\n */\n isCancelled(): boolean {\n return this.cancelled;\n }\n\n /**\n * Returns the number of currently running tasks.\n */\n getRunningCount(): number {\n return this.running;\n }\n\n /**\n * Returns the number of tasks waiting in the queue.\n */\n getQueuedCount(): number {\n return this.queue.length;\n }\n\n /**\n * Returns the abort signal for external use.\n */\n getAbortSignal(): AbortSignal {\n return this.abortController.signal;\n }\n\n /**\n * Processes the next task in the queue if capacity allows.\n */\n private processNext(): void {\n if (this.cancelled || this.running >= this.concurrency || this.queue.length === 0) {\n return;\n }\n\n const item = this.queue.shift();\n if (!item) return;\n\n this.running++;\n\n item\n .task(this.abortController.signal)\n .then((result) => {\n item.resolve(result);\n })\n .catch((error: unknown) => {\n if (error instanceof Error) {\n item.reject(error);\n } else {\n item.reject(new Error(String(error)));\n }\n })\n .finally(() => {\n this.running--;\n this.processNext();\n });\n }\n}\n\n/**\n * Creates a task queue with the specified concurrency.\n *\n * @param concurrency - Maximum number of concurrent tasks\n * @returns A new TaskQueue instance\n */\nexport function createTaskQueue<T>(concurrency = 5): TaskQueue<T> {\n return new TaskQueue<T>(concurrency);\n}\n","/**\n * @nexus-agents/workflows - Execution Planner\n *\n * Creates execution plans with phases based on step dependencies.\n * Uses topological sort to group independent steps into concurrent phases.\n */\n\nimport type { Result } from '../core/index.js';\nimport { ok, err, WorkflowError } from '../core/index.js';\nimport type { WorkflowStep, WorkflowDefinition } from '../core/index.js';\n\n/**\n * A phase of steps that can be executed concurrently.\n */\nexport interface ExecutionPhase {\n /** Steps that can run in parallel within this phase */\n steps: WorkflowStep[];\n /** Phase index (0-based) */\n phaseIndex: number;\n}\n\n/**\n * Execution plan with ordered phases.\n */\nexport interface ExecutionPlan {\n /** Ordered phases of execution */\n phases: ExecutionPhase[];\n /** Total number of steps */\n totalSteps: number;\n /** Maximum parallelism (max steps in any phase) */\n maxParallelism: number;\n}\n\n/**\n * Graph node for topological sorting.\n */\ninterface DependencyNode {\n step: WorkflowStep;\n dependencies: Set<string>;\n dependents: Set<string>;\n inDegree: number;\n}\n\n/**\n * Builds a dependency graph from workflow steps.\n *\n * @param steps - Workflow steps to analyze\n * @returns Map of step ID to dependency node\n */\nfunction buildDependencyGraph(steps: WorkflowStep[]): Map<string, DependencyNode> {\n const graph = new Map<string, DependencyNode>();\n\n // Initialize nodes\n for (const step of steps) {\n graph.set(step.id, {\n step,\n dependencies: new Set(step.dependsOn ?? []),\n dependents: new Set(),\n inDegree: step.dependsOn?.length ?? 0,\n });\n }\n\n // Build reverse dependencies (dependents)\n for (const step of steps) {\n if (step.dependsOn) {\n for (const depId of step.dependsOn) {\n const depNode = graph.get(depId);\n if (depNode) {\n depNode.dependents.add(step.id);\n }\n }\n }\n }\n\n return graph;\n}\n\n/**\n * Validates the dependency graph for cycles and missing dependencies.\n *\n * @param graph - Dependency graph to validate\n * @param stepIds - Set of all step IDs\n * @returns Result with void or WorkflowError\n */\nfunction validateGraph(\n graph: Map<string, DependencyNode>,\n stepIds: Set<string>\n): Result<void, WorkflowError> {\n // Check for missing dependencies\n for (const [stepId, node] of graph) {\n for (const depId of node.dependencies) {\n if (!stepIds.has(depId)) {\n return err(\n new WorkflowError(`Step '${stepId}' depends on unknown step '${depId}'`, {\n context: { stepId, missingDependency: depId },\n })\n );\n }\n }\n }\n\n // Check for cycles using DFS\n const visited = new Set<string>();\n const recursionStack = new Set<string>();\n\n function hasCycle(nodeId: string): string[] | null {\n visited.add(nodeId);\n recursionStack.add(nodeId);\n\n const node = graph.get(nodeId);\n if (!node) return null;\n\n for (const depId of node.dependents) {\n if (!visited.has(depId)) {\n const cyclePath = hasCycle(depId);\n if (cyclePath) {\n return [nodeId, ...cyclePath];\n }\n } else if (recursionStack.has(depId)) {\n return [nodeId, depId];\n }\n }\n\n recursionStack.delete(nodeId);\n return null;\n }\n\n for (const nodeId of graph.keys()) {\n if (!visited.has(nodeId)) {\n const cyclePath = hasCycle(nodeId);\n if (cyclePath) {\n return err(\n new WorkflowError(`Circular dependency detected: ${cyclePath.join(' -> ')}`, {\n context: { cyclePath },\n })\n );\n }\n }\n }\n\n return ok(undefined);\n}\n\n/** Initializes in-degrees map from graph */\nfunction initializeInDegrees(graph: Map<string, DependencyNode>): Map<string, number> {\n const inDegrees = new Map<string, number>();\n for (const [stepId, node] of graph) {\n inDegrees.set(stepId, node.inDegree);\n }\n return inDegrees;\n}\n\n/** Finds all steps ready to execute (in-degree 0) */\nfunction findReadySteps(\n remaining: Set<string>,\n inDegrees: Map<string, number>,\n graph: Map<string, DependencyNode>\n): WorkflowStep[] {\n const readySteps: WorkflowStep[] = [];\n for (const stepId of remaining) {\n if ((inDegrees.get(stepId) ?? 0) === 0) {\n const node = graph.get(stepId);\n if (node !== undefined) {\n readySteps.push(node.step);\n }\n }\n }\n return readySteps;\n}\n\n/** Updates in-degrees after processing steps */\nfunction updateInDegrees(\n processedSteps: WorkflowStep[],\n remaining: Set<string>,\n inDegrees: Map<string, number>,\n graph: Map<string, DependencyNode>\n): void {\n for (const step of processedSteps) {\n remaining.delete(step.id);\n const node = graph.get(step.id);\n if (node !== undefined) {\n for (const dependentId of node.dependents) {\n const currentDegree = inDegrees.get(dependentId) ?? 0;\n inDegrees.set(dependentId, currentDegree - 1);\n }\n }\n }\n}\n\n/**\n * Performs Kahn's algorithm to create execution phases.\n * Steps with no dependencies form phase 0, their dependents form phase 1, etc.\n *\n * @param graph - Validated dependency graph\n * @returns Array of execution phases\n */\nfunction topologicalSort(graph: Map<string, DependencyNode>): ExecutionPhase[] {\n const phases: ExecutionPhase[] = [];\n const inDegrees = initializeInDegrees(graph);\n const remaining = new Set<string>(graph.keys());\n let phaseIndex = 0;\n\n while (remaining.size > 0) {\n const readySteps = findReadySteps(remaining, inDegrees, graph);\n\n if (readySteps.length === 0) {\n break; // Should not happen if validation passed\n }\n\n phases.push({ steps: readySteps, phaseIndex });\n updateInDegrees(readySteps, remaining, inDegrees, graph);\n phaseIndex++;\n }\n\n return phases;\n}\n\n/**\n * Creates an execution plan from a workflow definition.\n * Groups steps into phases based on dependencies for parallel execution.\n *\n * @param workflow - Workflow definition to analyze\n * @returns Result with ExecutionPlan or WorkflowError\n */\nexport function createExecutionPlan(\n workflow: WorkflowDefinition\n): Result<ExecutionPlan, WorkflowError> {\n const { steps } = workflow;\n\n // Handle empty workflow\n if (steps.length === 0) {\n return ok({\n phases: [],\n totalSteps: 0,\n maxParallelism: 0,\n });\n }\n\n // Check for duplicate step IDs\n const stepIds = new Set<string>();\n for (const step of steps) {\n if (stepIds.has(step.id)) {\n return err(\n new WorkflowError(`Duplicate step ID: '${step.id}'`, {\n context: { duplicateId: step.id },\n })\n );\n }\n stepIds.add(step.id);\n }\n\n // Build and validate dependency graph\n const graph = buildDependencyGraph(steps);\n const validationResult = validateGraph(graph, stepIds);\n\n if (!validationResult.ok) {\n return err(validationResult.error);\n }\n\n // Create phases via topological sort\n const phases = topologicalSort(graph);\n\n // Calculate max parallelism\n const maxParallelism = Math.max(...phases.map((p) => p.steps.length), 0);\n\n return ok({\n phases,\n totalSteps: steps.length,\n maxParallelism,\n });\n}\n\n/**\n * Validates a workflow definition without creating a full plan.\n *\n * @param workflow - Workflow definition to validate\n * @returns Result with void or WorkflowError\n */\nexport function validateWorkflowDependencies(\n workflow: WorkflowDefinition\n): Result<void, WorkflowError> {\n const planResult = createExecutionPlan(workflow);\n if (!planResult.ok) {\n return err(planResult.error);\n }\n return ok(undefined);\n}\n\n/**\n * Gets the execution order of steps as a flat array.\n * Steps in the same phase are grouped together.\n *\n * @param plan - Execution plan\n * @returns Ordered array of step IDs\n */\nexport function getExecutionOrder(plan: ExecutionPlan): string[] {\n const order: string[] = [];\n for (const phase of plan.phases) {\n for (const step of phase.steps) {\n order.push(step.id);\n }\n }\n return order;\n}\n","/**\n * @nexus-agents/workflows - Parallel Executor\n *\n * Executes workflow steps in parallel with concurrency limiting,\n * fail-fast behavior, and cancellation support.\n */\n\nimport type { Result } from '../core/index.js';\nimport { ok, err, WorkflowError } from '../core/index.js';\nimport type { WorkflowStep, StepResult } from '../core/index.js';\nimport { TaskQueue } from './task-queue.js';\n\n/**\n * Options for parallel execution.\n */\nexport interface ParallelOptions {\n /** Maximum concurrent steps (default: 5) */\n maxConcurrency?: number;\n /** Stop on first error (default: true) */\n failFast?: boolean;\n /** Overall timeout in milliseconds */\n timeoutMs?: number;\n}\n\n/**\n * Context passed to step executor.\n */\nexport interface ExecutionContext {\n /** Workflow execution ID */\n executionId: string;\n /** Results from previous steps */\n stepResults: Map<string, StepResult>;\n /** Workflow inputs */\n inputs: Record<string, unknown>;\n /** Abort signal for cancellation */\n signal?: AbortSignal;\n}\n\n/**\n * Function signature for step execution.\n */\nexport type StepExecutor = (step: WorkflowStep, context: ExecutionContext) => Promise<StepResult>;\n\n/**\n * Default parallel execution options.\n */\nconst DEFAULT_OPTIONS: Required<ParallelOptions> = {\n maxConcurrency: 5,\n failFast: true,\n timeoutMs: 0, // 0 means no timeout\n};\n\n/**\n * Creates a cancelled step result.\n */\nfunction createCancelledResult(stepId: string): StepResult {\n return { stepId, output: null, durationMs: 0, status: 'skipped', error: 'Execution cancelled' };\n}\n\n/**\n * Creates a timeout step result.\n */\nfunction createTimeoutResult(stepId: string, durationMs: number, timeoutMs: number): StepResult {\n return {\n stepId,\n output: null,\n durationMs,\n status: 'failed',\n error: `Step timed out after ${String(timeoutMs)}ms`,\n };\n}\n\n/**\n * Creates a failed step result from an error.\n */\nfunction createErrorResult(stepId: string, durationMs: number, error: unknown): StepResult {\n return {\n stepId,\n output: null,\n durationMs,\n status: 'failed',\n error: error instanceof Error ? error.message : String(error),\n };\n}\n\n/**\n * Executes a single step with timeout and abort support.\n */\nasync function executeStepWithTimeout(\n step: WorkflowStep,\n context: ExecutionContext,\n stepExecutor: StepExecutor,\n signal: AbortSignal\n): Promise<StepResult> {\n if (signal.aborted) {\n return createCancelledResult(step.id);\n }\n\n const stepTimeout = step.timeout ?? 0;\n const startTime = Date.now();\n const stepContext: ExecutionContext = { ...context, signal };\n\n if (stepTimeout === 0) {\n return stepExecutor(step, stepContext);\n }\n\n return executeWithTimeout(step, stepContext, stepExecutor, stepTimeout, startTime);\n}\n\n/**\n * Executes step with a timeout wrapper.\n */\nfunction executeWithTimeout(\n step: WorkflowStep,\n context: ExecutionContext,\n executor: StepExecutor,\n timeout: number,\n startTime: number\n): Promise<StepResult> {\n return new Promise<StepResult>((resolve) => {\n const timeoutId = setTimeout(() => {\n resolve(createTimeoutResult(step.id, Date.now() - startTime, timeout));\n }, timeout);\n\n executor(step, context)\n .then((result) => {\n clearTimeout(timeoutId);\n resolve(result);\n })\n .catch((error: unknown) => {\n clearTimeout(timeoutId);\n resolve(createErrorResult(step.id, Date.now() - startTime, error));\n });\n });\n}\n\n/** Internal state for parallel execution */\ninterface ParallelState {\n results: StepResult[];\n firstError: WorkflowError | null;\n completed: boolean;\n timeoutId: ReturnType<typeof setTimeout> | undefined;\n queue: TaskQueue<StepResult>;\n abortController: AbortController;\n}\n\n/** Creates WorkflowError for step failure */\nfunction createStepError(stepId: string, errorMsg: string | undefined): WorkflowError {\n const message = errorMsg ?? 'Unknown error';\n return new WorkflowError(`Step '${stepId}' failed: ${message}`, {\n context: { stepId, error: message },\n });\n}\n\n/** Creates WorkflowError for timeout */\nfunction createTimeoutError(timeoutMs: number): WorkflowError {\n return new WorkflowError(`Parallel execution timed out after ${String(timeoutMs)}ms`, {\n context: { timeoutMs, isTimeout: true },\n });\n}\n\n/** Sets up overall timeout for execution */\nfunction setupOverallTimeout(state: ParallelState, opts: Required<ParallelOptions>): void {\n if (opts.timeoutMs <= 0) return;\n\n state.timeoutId = setTimeout(() => {\n if (!state.completed) {\n state.firstError = createTimeoutError(opts.timeoutMs);\n state.abortController.abort();\n state.queue.cancel();\n }\n }, opts.timeoutMs);\n}\n\n/** Cleans up execution state */\nfunction cleanupExecution(state: ParallelState): void {\n if (state.timeoutId !== undefined) {\n clearTimeout(state.timeoutId);\n }\n state.queue.cancel();\n}\n\n/** Sorts results by original step order */\nfunction sortResultsByStepOrder(results: StepResult[], steps: WorkflowStep[]): void {\n const stepOrder = new Map(steps.map((s, i) => [s.id, i]));\n results.sort((a, b) => (stepOrder.get(a.stepId) ?? 0) - (stepOrder.get(b.stepId) ?? 0));\n}\n\n/**\n * Executes steps in parallel with concurrency limiting.\n */\nexport async function executeParallel(\n steps: WorkflowStep[],\n context: ExecutionContext,\n stepExecutor: StepExecutor,\n options?: ParallelOptions\n): Promise<Result<StepResult[], WorkflowError>> {\n if (steps.length === 0) {\n return ok([]);\n }\n\n const opts = { ...DEFAULT_OPTIONS, ...options };\n const state: ParallelState = {\n results: [],\n firstError: null,\n completed: false,\n timeoutId: undefined,\n queue: new TaskQueue<StepResult>(opts.maxConcurrency),\n abortController: new AbortController(),\n };\n\n if (context.signal !== undefined) {\n context.signal.addEventListener('abort', () => {\n state.abortController.abort();\n });\n }\n\n try {\n setupOverallTimeout(state, opts);\n await runAllSteps(steps, context, stepExecutor, opts, state);\n state.completed = true;\n cleanupExecution(state);\n\n if (state.firstError !== null) {\n return err(state.firstError);\n }\n\n sortResultsByStepOrder(state.results, steps);\n return ok(state.results);\n } catch (error) {\n cleanupExecution(state);\n return err(\n new WorkflowError('Parallel execution failed unexpectedly', {\n cause: error instanceof Error ? error : new Error(String(error)),\n })\n );\n }\n}\n\n/** Runs all steps through the queue */\nasync function runAllSteps(\n steps: WorkflowStep[],\n context: ExecutionContext,\n stepExecutor: StepExecutor,\n opts: Required<ParallelOptions>,\n state: ParallelState\n): Promise<void> {\n const promises = steps.map((step) =>\n executeStepInQueue(step, context, stepExecutor, opts, state)\n );\n await Promise.allSettled(promises);\n}\n\n/** Executes a single step in the queue */\nasync function executeStepInQueue(\n step: WorkflowStep,\n context: ExecutionContext,\n stepExecutor: StepExecutor,\n opts: Required<ParallelOptions>,\n state: ParallelState\n): Promise<StepResult> {\n try {\n const result = await state.queue.add((signal) => {\n const combined = new AbortController();\n signal.addEventListener('abort', () => {\n combined.abort();\n });\n state.abortController.signal.addEventListener('abort', () => {\n combined.abort();\n });\n return executeStepWithTimeout(step, context, stepExecutor, combined.signal);\n });\n\n state.results.push(result);\n if (opts.failFast && result.status === 'failed' && state.firstError === null) {\n state.firstError = createStepError(result.stepId, result.error);\n state.abortController.abort();\n state.queue.cancel();\n }\n return result;\n } catch (error: unknown) {\n const stepResult = createErrorResult(step.id, 0, error);\n state.results.push(stepResult);\n if (opts.failFast && state.firstError === null) {\n state.firstError = createStepError(step.id, stepResult.error);\n state.abortController.abort();\n state.queue.cancel();\n }\n return stepResult;\n }\n}\n\n/**\n * Creates a step executor that wraps a base executor with retry logic.\n *\n * @param baseExecutor - Base step executor\n * @param defaultRetries - Default retry count for steps without explicit retries\n * @returns Step executor with retry support\n */\nexport function withRetries(baseExecutor: StepExecutor, defaultRetries = 0): StepExecutor {\n return async (step, context): Promise<StepResult> => {\n const maxRetries = step.retries ?? defaultRetries;\n let lastResult: StepResult | null = null;\n let attempt = 0;\n\n while (attempt <= maxRetries) {\n // Check for cancellation - use explicit boolean check\n const isAborted = context.signal?.aborted === true;\n if (isAborted) {\n return createCancelledResult(step.id);\n }\n\n lastResult = await baseExecutor(step, context);\n\n if (lastResult.status === 'success') {\n return lastResult;\n }\n\n attempt++;\n\n if (attempt <= maxRetries) {\n // Exponential backoff: 100ms, 200ms, 400ms, etc.\n const delay = Math.min(100 * Math.pow(2, attempt - 1), 5000);\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n }\n\n if (lastResult !== null) {\n return lastResult;\n }\n\n return {\n stepId: step.id,\n output: null,\n durationMs: 0,\n status: 'failed',\n error: 'Max retries exceeded',\n };\n };\n}\n\n/**\n * Checks if all step results are successful.\n *\n * @param results - Array of step results\n * @returns True if all steps succeeded\n */\nexport function allSucceeded(results: StepResult[]): boolean {\n return results.every((r) => r.status === 'success');\n}\n\n/**\n * Gets failed step results.\n *\n * @param results - Array of step results\n * @returns Array of failed step results\n */\nexport function getFailedSteps(results: StepResult[]): StepResult[] {\n return results.filter((r) => r.status === 'failed');\n}\n","/**\n * @nexus-agents/workflows - Template Types\n *\n * Type definitions and Zod schemas for workflow templates.\n */\n\nimport { z } from 'zod';\nimport type { WorkflowDefinition, WorkflowTemplate } from '../core/index.js';\n\n/**\n * Template category for organization.\n */\nexport type TemplateCategory = 'development' | 'review' | 'documentation' | 'testing' | 'custom';\n\n/**\n * Extended template metadata for registry.\n */\nexport interface TemplateMetadata extends WorkflowTemplate {\n /** Template category */\n category: TemplateCategory;\n /** Keywords for search */\n keywords: string[];\n /** Whether this is a built-in template */\n builtIn: boolean;\n /** Template author */\n author?: string;\n /** Last updated timestamp */\n updatedAt?: string;\n}\n\n/**\n * Template registry interface.\n */\nexport interface ITemplateRegistry {\n /**\n * Get all built-in templates.\n * @returns Array of built-in template metadata\n */\n getBuiltIn(): TemplateMetadata[];\n\n /**\n * Get all registered templates (built-in + custom).\n * @returns Array of all template metadata\n */\n getAll(): TemplateMetadata[];\n\n /**\n * Get a workflow definition by template ID.\n * @param id - Template name/ID\n * @returns WorkflowDefinition or undefined if not found\n */\n getById(id: string): WorkflowDefinition | undefined;\n\n /**\n * Register a custom workflow template.\n * @param workflow - Workflow definition to register\n * @param metadata - Optional additional metadata\n */\n register(workflow: WorkflowDefinition, metadata?: Partial<TemplateMetadata>): void;\n\n /**\n * Unregister a custom template by ID.\n * @param id - Template ID to unregister\n * @returns True if template was removed\n */\n unregister(id: string): boolean;\n\n /**\n * Load templates from a directory.\n * @param directoryPath - Path to directory containing YAML templates\n * @returns Number of templates loaded\n */\n loadFromDirectory(directoryPath: string): Promise<number>;\n\n /**\n * Search templates by keyword.\n * @param query - Search query\n * @returns Matching template metadata\n */\n search(query: string): TemplateMetadata[];\n\n /**\n * Get templates by category.\n * @param category - Category to filter by\n * @returns Templates in the category\n */\n getByCategory(category: TemplateCategory): TemplateMetadata[];\n}\n\n// ============================================================================\n// Zod Schemas for YAML Template Validation\n// ============================================================================\n\n/**\n * Input definition schema.\n */\nexport const InputDefinitionSchema = z.object({\n name: z.string().min(1, 'Input name is required'),\n type: z.enum(['string', 'number', 'boolean', 'object', 'array']),\n description: z.string().optional(),\n required: z.boolean().optional().default(false),\n default: z.unknown().optional(),\n});\n\n/**\n * Agent role schema.\n */\nexport const AgentRoleSchema = z.enum([\n 'tech_lead',\n 'code_expert',\n 'architecture_expert',\n 'security_expert',\n 'documentation_expert',\n 'testing_expert',\n 'custom',\n]);\n\n/**\n * Workflow step schema.\n */\nexport const WorkflowStepSchema = z.object({\n id: z.string().min(1, 'Step ID is required'),\n agent: AgentRoleSchema,\n action: z.string().min(1, 'Action is required'),\n description: z.string().optional(),\n inputs: z.record(z.unknown()).default({}),\n dependsOn: z.array(z.string()).optional(),\n parallel: z.boolean().optional().default(false),\n retries: z.number().int().min(0).max(5).optional(),\n timeout: z.number().positive().optional(),\n condition: z.string().optional(),\n});\n\n/**\n * Workflow definition schema for YAML parsing.\n * Validates and transforms YAML content into WorkflowDefinition.\n */\nexport const WorkflowDefinitionSchema = z\n .object({\n name: z.string().min(1, 'Workflow name is required'),\n version: z.string().regex(/^\\d+\\.\\d+\\.\\d+$/, 'Version must be semver format'),\n description: z.string().optional(),\n inputs: z.array(InputDefinitionSchema).default([]),\n steps: z.array(WorkflowStepSchema).min(1, 'At least one step is required'),\n timeout: z.number().positive().optional(),\n })\n .transform((data) => ({\n name: data.name,\n version: data.version,\n description: data.description,\n inputs: data.inputs.map((input) => ({\n name: input.name,\n type: input.type,\n description: input.description,\n required: input.required,\n default: input.default,\n })),\n steps: data.steps.map((step) => ({\n id: step.id,\n agent: step.agent,\n action: step.action,\n inputs: step.inputs,\n dependsOn: step.dependsOn,\n parallel: step.parallel,\n retries: step.retries,\n timeout: step.timeout,\n condition: step.condition,\n })),\n timeout: data.timeout,\n }));\n\n/**\n * Template category schema.\n */\nexport const TemplateCategorySchema = z.enum([\n 'development',\n 'review',\n 'documentation',\n 'testing',\n 'custom',\n]);\n\n/**\n * Template metadata schema.\n */\nexport const TemplateMetadataSchema = z.object({\n name: z.string().min(1),\n version: z.string(),\n description: z.string().optional(),\n path: z.string(),\n category: TemplateCategorySchema,\n keywords: z.array(z.string()).default([]),\n builtIn: z.boolean().default(false),\n author: z.string().optional(),\n updatedAt: z.string().optional(),\n});\n\n/**\n * Built-in template names.\n */\nexport const BUILT_IN_TEMPLATES = [\n 'code-review',\n 'feature-implementation',\n 'bug-fix',\n 'documentation-update',\n] as const;\n\nexport type BuiltInTemplateName = (typeof BUILT_IN_TEMPLATES)[number];\n\n/**\n * Category mapping for built-in templates.\n */\nexport const TEMPLATE_CATEGORIES: Record<BuiltInTemplateName, TemplateCategory> = {\n 'code-review': 'review',\n 'feature-implementation': 'development',\n 'bug-fix': 'development',\n 'documentation-update': 'documentation',\n};\n\n/**\n * Keywords for built-in templates.\n */\nexport const TEMPLATE_KEYWORDS: Record<BuiltInTemplateName, string[]> = {\n 'code-review': ['review', 'quality', 'security', 'analysis', 'code'],\n 'feature-implementation': ['feature', 'implement', 'develop', 'create', 'build'],\n 'bug-fix': ['bug', 'fix', 'debug', 'error', 'issue', 'patch'],\n 'documentation-update': ['docs', 'documentation', 'readme', 'api', 'update'],\n};\n","/**\n * @nexus-agents/workflows - Template Loader\n *\n * Utilities for loading and parsing YAML workflow templates.\n */\n\nimport { readFile, readdir, stat } from 'node:fs/promises';\nimport { join, basename, extname, resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { dirname } from 'node:path';\nimport { parse as parseYaml } from 'yaml';\nimport type { Result } from '../core/index.js';\nimport { ParseError, SecurityError } from '../core/index.js';\nimport type { WorkflowDefinition } from '../core/index.js';\nimport {\n WorkflowDefinitionSchema,\n BUILT_IN_TEMPLATES,\n TEMPLATE_CATEGORIES,\n TEMPLATE_KEYWORDS,\n type BuiltInTemplateName,\n type TemplateMetadata,\n} from './template-types.js';\n\n/**\n * Result of parsing a template file.\n */\nexport interface ParsedTemplate {\n definition: WorkflowDefinition;\n metadata: TemplateMetadata;\n}\n\n/**\n * Validates that a file path is within the allowed root directory.\n * Prevents path traversal attacks (e.g., ../../../etc/passwd).\n * @param userPath - The user-provided file path\n * @param allowedRoot - The root directory that paths must be within\n * @returns Result with validated absolute path or SecurityError\n */\nfunction validatePath(userPath: string, allowedRoot: string): Result<string, SecurityError> {\n const resolvedRoot = resolve(allowedRoot);\n const resolved = resolve(allowedRoot, userPath);\n\n if (!resolved.startsWith(resolvedRoot + sep) && resolved !== resolvedRoot) {\n return {\n ok: false,\n error: new SecurityError('Path traversal detected: path escapes allowed root directory', {\n context: { userPath, allowedRoot: resolvedRoot },\n }),\n };\n }\n return { ok: true, value: resolved };\n}\n\n/**\n * Get the directory containing built-in templates.\n * @returns Path to templates directory\n */\nexport function getBuiltInTemplatesPath(): string {\n const currentFile = fileURLToPath(import.meta.url);\n const currentDir = dirname(currentFile);\n return join(currentDir, 'templates');\n}\n\n/**\n * Create a validation error result.\n */\nfunction createValidationError(\n errors: Array<{ path: (string | number)[]; message: string }>\n): Result<WorkflowDefinition, ParseError> {\n const firstError = errors[0];\n const errorPath = firstError?.path.join('.') ?? 'unknown';\n const message = `Validation error at '${errorPath}': ${firstError?.message ?? 'Unknown error'}`;\n return { ok: false, error: new ParseError(message) };\n}\n\n/**\n * Create a parse error result from an exception.\n */\nfunction createParseErrorFromException(\n error: unknown,\n filePath: string\n): Result<WorkflowDefinition, ParseError> {\n if (error instanceof Error) {\n const lineMatch = error.message.match(/at line (\\d+)/);\n const lineNumber = lineMatch?.[1] !== undefined ? parseInt(lineMatch[1], 10) : undefined;\n const parseError = new ParseError(\n `Failed to parse ${filePath}: ${error.message}`,\n lineNumber !== undefined ? { line: lineNumber } : undefined\n );\n return { ok: false, error: parseError };\n }\n return { ok: false, error: new ParseError(`Unknown error parsing ${filePath}`) };\n}\n\n/**\n * Parse a YAML template string into a WorkflowDefinition.\n * @param content - YAML content to parse\n * @param filePath - Path to the file (for error messages)\n * @returns Result with WorkflowDefinition or ParseError\n */\nexport function parseTemplateContent(\n content: string,\n filePath: string\n): Result<WorkflowDefinition, ParseError> {\n try {\n const parsed: unknown = parseYaml(content);\n const validated = WorkflowDefinitionSchema.safeParse(parsed);\n\n if (!validated.success) {\n return createValidationError(validated.error.errors);\n }\n\n const definition = validated.data as WorkflowDefinition;\n return { ok: true, value: definition };\n } catch (error) {\n return createParseErrorFromException(error, filePath);\n }\n}\n\n/**\n * Load a template from a file path.\n * @param filePath - Path to the YAML template file\n * @param allowedRoot - Optional root directory for path validation (skipped if undefined)\n * @returns Result with ParsedTemplate or ParseError/SecurityError\n */\nexport async function loadTemplateFile(\n filePath: string,\n allowedRoot?: string\n): Promise<Result<ParsedTemplate, ParseError | SecurityError>> {\n // If allowedRoot is provided, validate the path\n let validatedPath = filePath;\n if (allowedRoot !== undefined) {\n const pathValidation = validatePath(filePath, allowedRoot);\n if (!pathValidation.ok) {\n return pathValidation;\n }\n validatedPath = pathValidation.value;\n }\n\n try {\n const content = await readFile(validatedPath, 'utf-8');\n const parseResult = parseTemplateContent(content, validatedPath);\n\n if (!parseResult.ok) {\n return parseResult;\n }\n\n const definition = parseResult.value;\n const templateName = basename(validatedPath, extname(validatedPath));\n const isBuiltIn = BUILT_IN_TEMPLATES.includes(templateName as BuiltInTemplateName);\n\n const metadata: TemplateMetadata = {\n name: definition.name,\n version: definition.version,\n path: validatedPath,\n category: isBuiltIn ? TEMPLATE_CATEGORIES[templateName as BuiltInTemplateName] : 'custom',\n keywords: isBuiltIn\n ? TEMPLATE_KEYWORDS[templateName as BuiltInTemplateName]\n : extractKeywords(definition),\n builtIn: isBuiltIn,\n };\n if (definition.description !== undefined) {\n metadata.description = definition.description;\n }\n\n return { ok: true, value: { definition, metadata } };\n } catch (error) {\n if (error instanceof Error) {\n return {\n ok: false,\n error: new ParseError(`Failed to read ${validatedPath}: ${error.message}`),\n };\n }\n return {\n ok: false,\n error: new ParseError(`Unknown error reading ${validatedPath}`),\n };\n }\n}\n\n/**\n * Load all templates from a directory.\n * Validates each file path to prevent path traversal attacks.\n * @param directoryPath - Path to directory containing YAML templates\n * @returns Array of successfully loaded templates and any errors\n */\nexport async function loadTemplatesFromDirectory(\n directoryPath: string\n): Promise<{ templates: ParsedTemplate[]; errors: Array<ParseError | SecurityError> }> {\n const templates: ParsedTemplate[] = [];\n const errors: Array<ParseError | SecurityError> = [];\n\n try {\n // Resolve the directory path to an absolute path\n const resolvedDirectory = resolve(directoryPath);\n\n const stats = await stat(resolvedDirectory);\n if (!stats.isDirectory()) {\n errors.push(new ParseError(`${resolvedDirectory} is not a directory`));\n return { templates, errors };\n }\n\n const entries = await readdir(resolvedDirectory);\n\n for (const entry of entries) {\n if (!isYamlFile(entry)) {\n continue;\n }\n\n // Validate the entry path to prevent path traversal\n // (e.g., if readdir somehow returned \"../malicious.yaml\")\n const pathValidation = validatePath(entry, resolvedDirectory);\n if (!pathValidation.ok) {\n errors.push(pathValidation.error);\n continue;\n }\n\n const filePath = pathValidation.value;\n // Pass the resolved directory as allowedRoot to ensure consistent validation\n const result = await loadTemplateFile(filePath, resolvedDirectory);\n\n if (result.ok) {\n templates.push(result.value);\n } else {\n errors.push(result.error);\n }\n }\n } catch (error) {\n if (error instanceof Error) {\n errors.push(new ParseError(`Failed to read directory ${directoryPath}: ${error.message}`));\n }\n }\n\n return { templates, errors };\n}\n\n/**\n * Load all built-in templates.\n * @returns Map of template name to WorkflowDefinition\n */\nexport async function getBuiltInTemplates(): Promise<Map<string, WorkflowDefinition>> {\n const templatesPath = getBuiltInTemplatesPath();\n const result = await loadTemplatesFromDirectory(templatesPath);\n\n const templateMap = new Map<string, WorkflowDefinition>();\n\n for (const { definition } of result.templates) {\n templateMap.set(definition.name, definition);\n }\n\n return templateMap;\n}\n\n/**\n * Load built-in templates with full metadata.\n * @returns Array of parsed templates with metadata\n */\nexport async function getBuiltInTemplatesWithMetadata(): Promise<ParsedTemplate[]> {\n const templatesPath = getBuiltInTemplatesPath();\n const result = await loadTemplatesFromDirectory(templatesPath);\n return result.templates;\n}\n\n/**\n * Check if a file is a YAML file.\n * @param filename - Filename to check\n * @returns True if file has YAML extension\n */\nfunction isYamlFile(filename: string): boolean {\n const ext = extname(filename).toLowerCase();\n return ext === '.yaml' || ext === '.yml';\n}\n\n/**\n * Extract keywords from a workflow definition.\n * @param definition - Workflow definition\n * @returns Array of keywords\n */\nfunction extractKeywords(definition: WorkflowDefinition): string[] {\n const keywords = new Set<string>();\n\n // Add name words\n for (const word of definition.name.split(/[-_\\s]+/)) {\n if (word.length > 2) {\n keywords.add(word.toLowerCase());\n }\n }\n\n // Add step action words\n for (const step of definition.steps) {\n for (const word of step.action.split(/[-_\\s]+/)) {\n if (word.length > 2) {\n keywords.add(word.toLowerCase());\n }\n }\n }\n\n // Add agent roles\n for (const step of definition.steps) {\n keywords.add(step.agent.replace(/_/g, ' '));\n }\n\n return Array.from(keywords);\n}\n","/**\n * @nexus-agents/workflows - Template Registry\n *\n * Registry for managing workflow templates (built-in and custom).\n */\n\nimport type { WorkflowDefinition } from '../core/index.js';\nimport type { ITemplateRegistry, TemplateMetadata, TemplateCategory } from './template-types.js';\nimport { loadTemplatesFromDirectory, getBuiltInTemplatesWithMetadata } from './template-loader.js';\n\n/**\n * Maximum number of templates allowed in registry.\n * Prevents memory issues from unbounded growth.\n */\nconst MAX_TEMPLATES = 100;\n\n/**\n * Template registry implementation.\n * Manages both built-in and custom workflow templates.\n */\nclass TemplateRegistry implements ITemplateRegistry {\n private readonly definitions = new Map<string, WorkflowDefinition>();\n private readonly metadata = new Map<string, TemplateMetadata>();\n private initialized = false;\n\n /**\n * Initialize the registry with built-in templates.\n * Called automatically on first access if not already initialized.\n */\n async initialize(): Promise<void> {\n if (this.initialized) {\n return;\n }\n\n const builtInTemplates = await getBuiltInTemplatesWithMetadata();\n\n for (const { definition, metadata } of builtInTemplates) {\n this.definitions.set(definition.name, definition);\n this.metadata.set(definition.name, metadata);\n }\n\n this.initialized = true;\n }\n\n /**\n * Ensure registry is initialized.\n */\n private async ensureInitialized(): Promise<void> {\n if (!this.initialized) {\n await this.initialize();\n }\n }\n\n /**\n * Get all built-in templates.\n */\n getBuiltIn(): TemplateMetadata[] {\n return Array.from(this.metadata.values()).filter((m) => m.builtIn);\n }\n\n /**\n * Get all registered templates.\n */\n getAll(): TemplateMetadata[] {\n return Array.from(this.metadata.values());\n }\n\n /**\n * Get a workflow definition by ID.\n */\n getById(id: string): WorkflowDefinition | undefined {\n return this.definitions.get(id);\n }\n\n /**\n * Register a custom workflow template.\n */\n register(workflow: WorkflowDefinition, partialMetadata?: Partial<TemplateMetadata>): void {\n this.validateCanRegister(workflow.name);\n const metadata = this.buildMetadata(workflow, partialMetadata);\n this.definitions.set(workflow.name, workflow);\n this.metadata.set(workflow.name, metadata);\n }\n\n /**\n * Validate that a template can be registered.\n */\n private validateCanRegister(name: string): void {\n if (this.definitions.size >= MAX_TEMPLATES) {\n throw new Error(`Maximum template limit (${String(MAX_TEMPLATES)}) reached`);\n }\n const existingMeta = this.metadata.get(name);\n if (existingMeta?.builtIn === true) {\n throw new Error(`Cannot overwrite built-in template: ${name}`);\n }\n }\n\n /**\n * Build metadata for a workflow.\n */\n private buildMetadata(\n workflow: WorkflowDefinition,\n partialMetadata?: Partial<TemplateMetadata>\n ): TemplateMetadata {\n const metadata: TemplateMetadata = {\n name: workflow.name,\n version: workflow.version,\n path: partialMetadata?.path ?? '',\n category: partialMetadata?.category ?? 'custom',\n keywords: partialMetadata?.keywords ?? extractKeywordsFromWorkflow(workflow),\n builtIn: false,\n updatedAt: new Date().toISOString(),\n };\n if (workflow.description !== undefined) {\n metadata.description = workflow.description;\n }\n if (partialMetadata?.author !== undefined) {\n metadata.author = partialMetadata.author;\n }\n return metadata;\n }\n\n /**\n * Unregister a custom template.\n */\n unregister(id: string): boolean {\n const meta = this.metadata.get(id);\n\n if (meta === undefined) {\n return false;\n }\n\n if (meta.builtIn) {\n throw new Error(`Cannot unregister built-in template: ${id}`);\n }\n\n this.definitions.delete(id);\n this.metadata.delete(id);\n return true;\n }\n\n /**\n * Load templates from a directory.\n */\n async loadFromDirectory(directoryPath: string): Promise<number> {\n await this.ensureInitialized();\n\n const { templates, errors } = await loadTemplatesFromDirectory(directoryPath);\n\n if (errors.length > 0) {\n // Log errors but continue with successfully loaded templates\n for (const error of errors) {\n console.warn(`Template loading warning: ${error.message}`);\n }\n }\n\n let loadedCount = 0;\n\n for (const { definition, metadata } of templates) {\n try {\n // Skip if it would overwrite a built-in\n const existingMeta = this.metadata.get(definition.name);\n if (existingMeta?.builtIn !== true) {\n this.register(definition, metadata);\n loadedCount++;\n }\n } catch {\n // Skip templates that fail to register\n }\n }\n\n return loadedCount;\n }\n\n /**\n * Search templates by keyword.\n */\n search(query: string): TemplateMetadata[] {\n const lowerQuery = query.toLowerCase();\n return Array.from(this.metadata.values()).filter((meta) => this.matchesQuery(meta, lowerQuery));\n }\n\n /**\n * Check if metadata matches a search query.\n */\n private matchesQuery(meta: TemplateMetadata, lowerQuery: string): boolean {\n const nameMatches = meta.name.toLowerCase().includes(lowerQuery);\n const descMatches = meta.description?.toLowerCase().includes(lowerQuery) ?? false;\n const keywordMatches = meta.keywords.some((k) => k.includes(lowerQuery));\n return nameMatches || descMatches || keywordMatches;\n }\n\n /**\n * Get templates by category.\n */\n getByCategory(category: TemplateCategory): TemplateMetadata[] {\n return Array.from(this.metadata.values()).filter((m) => m.category === category);\n }\n\n /**\n * Clear all custom templates (keeps built-in).\n */\n clearCustom(): void {\n const customIds: string[] = [];\n\n for (const [id, meta] of this.metadata) {\n if (!meta.builtIn) {\n customIds.push(id);\n }\n }\n\n for (const id of customIds) {\n this.definitions.delete(id);\n this.metadata.delete(id);\n }\n }\n\n /**\n * Get registry statistics.\n */\n getStats(): { total: number; builtIn: number; custom: number } {\n const builtIn = this.getBuiltIn().length;\n const total = this.metadata.size;\n return { total, builtIn, custom: total - builtIn };\n }\n}\n\n/**\n * Extract keywords from a workflow definition.\n */\nfunction extractKeywordsFromWorkflow(definition: WorkflowDefinition): string[] {\n const keywords = new Set<string>();\n\n // Add name words\n for (const word of definition.name.split(/[-_\\s]+/)) {\n if (word.length > 2) {\n keywords.add(word.toLowerCase());\n }\n }\n\n // Add step action words\n for (const step of definition.steps) {\n for (const word of step.action.split(/[-_\\s]+/)) {\n if (word.length > 2) {\n keywords.add(word.toLowerCase());\n }\n }\n }\n\n return Array.from(keywords);\n}\n\n// Singleton instance\nlet registryInstance: TemplateRegistry | null = null;\n\n/**\n * Create or get the template registry instance.\n * @returns Template registry instance\n */\nexport function createTemplateRegistry(): ITemplateRegistry {\n registryInstance ??= new TemplateRegistry();\n return registryInstance;\n}\n\n/**\n * Create a new isolated template registry instance.\n * Useful for testing or isolated contexts.\n * @returns New template registry instance\n */\nexport function createIsolatedRegistry(): TemplateRegistry {\n return new TemplateRegistry();\n}\n\n/**\n * Reset the global registry instance.\n * Primarily for testing purposes.\n */\nexport function resetRegistry(): void {\n registryInstance = null;\n}\n\nexport { TemplateRegistry };\n","/**\n * @nexus-agents/workflows - Execution Context\n *\n * Manages execution state and variable resolution for workflow steps.\n * Provides context isolation and result tracking during workflow execution.\n */\n\nimport { z } from 'zod';\nimport type { StepResult } from '../core/index.js';\nimport { ValidationError } from '../core/index.js';\n\n/**\n * Full execution context for a running workflow.\n * Tracks step results, variables, and provides input resolution.\n * This is the comprehensive context used by the step executor.\n */\nexport interface WorkflowExecutionContext {\n /** Workflow definition ID */\n readonly workflowId: string;\n /** Unique execution instance ID */\n readonly executionId: string;\n /** Initial workflow inputs */\n readonly inputs: Record<string, unknown>;\n /** Results from completed steps (stepId -> result) */\n readonly stepResults: Map<string, StepResult>;\n /** Runtime variables set during execution */\n readonly variables: Map<string, unknown>;\n /** Execution start time */\n readonly startedAt: Date;\n /** Whether execution has been cancelled */\n cancelled: boolean;\n}\n\n/**\n * Schema for validating workflow inputs.\n */\nexport const WorkflowInputsSchema = z.record(z.unknown());\n\n/**\n * Options for creating an execution context.\n */\nexport interface CreateExecutionContextOptions {\n /** Workflow definition ID */\n workflowId: string;\n /** Workflow inputs */\n inputs: Record<string, unknown>;\n /** Optional custom execution ID (auto-generated if not provided) */\n executionId?: string;\n}\n\n/**\n * Generate a unique execution ID.\n */\nfunction generateExecutionId(): string {\n const timestamp = Date.now().toString(36);\n const random = Math.random().toString(36).substring(2, 10);\n return `exec_${timestamp}_${random}`;\n}\n\n/**\n * Creates a new execution context for a workflow run.\n *\n * @param options - Context creation options\n * @returns A new WorkflowExecutionContext instance\n */\nexport function createExecutionContext(\n options: CreateExecutionContextOptions\n): WorkflowExecutionContext {\n const { workflowId, inputs, executionId } = options;\n\n return {\n workflowId,\n executionId: executionId ?? generateExecutionId(),\n inputs: { ...inputs },\n stepResults: new Map<string, StepResult>(),\n variables: new Map<string, unknown>(),\n startedAt: new Date(),\n cancelled: false,\n };\n}\n\n/**\n * Stores a step result in the execution context.\n *\n * @param context - The execution context\n * @param stepId - The step identifier\n * @param result - The step result to store\n */\nexport function storeStepResult(\n context: WorkflowExecutionContext,\n stepId: string,\n result: StepResult\n): void {\n context.stepResults.set(stepId, result);\n}\n\n/**\n * Retrieves a step result from the execution context.\n *\n * @param context - The execution context\n * @param stepId - The step identifier\n * @returns The step result or undefined if not found\n */\nexport function getStepResult(\n context: WorkflowExecutionContext,\n stepId: string\n): StepResult | undefined {\n return context.stepResults.get(stepId);\n}\n\n/**\n * Sets a variable in the execution context.\n *\n * @param context - The execution context\n * @param name - Variable name\n * @param value - Variable value\n */\nexport function setVariable(context: WorkflowExecutionContext, name: string, value: unknown): void {\n context.variables.set(name, value);\n}\n\n/**\n * Gets a variable from the execution context.\n *\n * @param context - The execution context\n * @param name - Variable name\n * @returns The variable value or undefined\n */\nexport function getVariable(context: WorkflowExecutionContext, name: string): unknown {\n return context.variables.get(name);\n}\n\n/**\n * Gets all completed step IDs.\n *\n * @param context - The execution context\n * @returns Array of completed step IDs\n */\nexport function getCompletedSteps(context: WorkflowExecutionContext): string[] {\n return Array.from(context.stepResults.keys());\n}\n\n/**\n * Checks if a step has been completed.\n *\n * @param context - The execution context\n * @param stepId - The step identifier\n * @returns True if step is completed\n */\nexport function isStepCompleted(context: WorkflowExecutionContext, stepId: string): boolean {\n return context.stepResults.has(stepId);\n}\n\n/**\n * Checks if all specified steps are completed.\n *\n * @param context - The execution context\n * @param stepIds - Array of step identifiers to check\n * @returns True if all specified steps are completed\n */\nexport function areStepsCompleted(context: WorkflowExecutionContext, stepIds: string[]): boolean {\n return stepIds.every((stepId) => isStepCompleted(context, stepId));\n}\n\n/**\n * Gets the execution duration in milliseconds.\n *\n * @param context - The execution context\n * @returns Duration in milliseconds\n */\nexport function getExecutionDuration(context: WorkflowExecutionContext): number {\n return Date.now() - context.startedAt.getTime();\n}\n\n/**\n * Marks the execution as cancelled.\n *\n * @param context - The execution context\n */\nexport function cancelExecution(context: WorkflowExecutionContext): void {\n context.cancelled = true;\n}\n\n/**\n * Checks if the execution has been cancelled.\n *\n * @param context - The execution context\n * @returns True if cancelled\n */\nexport function isCancelled(context: WorkflowExecutionContext): boolean {\n return context.cancelled;\n}\n\n/**\n * Creates a snapshot of the current context state.\n * Useful for debugging and logging.\n *\n * @param context - The execution context\n * @returns A plain object snapshot\n */\nexport function snapshotContext(context: WorkflowExecutionContext): Record<string, unknown> {\n const stepResults: Record<string, StepResult> = {};\n for (const [key, value] of context.stepResults) {\n stepResults[key] = value;\n }\n\n const variables: Record<string, unknown> = {};\n for (const [key, value] of context.variables) {\n variables[key] = value;\n }\n\n return {\n workflowId: context.workflowId,\n executionId: context.executionId,\n inputs: context.inputs,\n stepResults,\n variables,\n startedAt: context.startedAt.toISOString(),\n durationMs: getExecutionDuration(context),\n cancelled: context.cancelled,\n };\n}\n\n/**\n * Validates that required inputs are present.\n *\n * @param inputs - The inputs to validate\n * @param required - Array of required input names\n * @returns Validation error or null if valid\n */\nexport function validateRequiredInputs(\n inputs: Record<string, unknown>,\n required: string[]\n): ValidationError | null {\n const missing: string[] = [];\n\n for (const name of required) {\n if (!(name in inputs) || inputs[name] === undefined) {\n missing.push(name);\n }\n }\n\n if (missing.length > 0) {\n return new ValidationError(`Missing required inputs: ${missing.join(', ')}`, {\n context: { missingInputs: missing },\n });\n }\n\n return null;\n}\n","/**\n * @nexus-agents/workflows - Expression Resolver\n *\n * Parses and resolves ${{ }} template expressions in workflow step inputs.\n * Supports accessing workflow inputs, step outputs, and variables.\n *\n * Expression syntax:\n * - ${{ inputs.name }} - Access workflow input\n * - ${{ steps.stepId.output }} - Access step output\n * - ${{ steps.stepId.output.field }} - Access nested field in step output\n * - ${{ variables.name }} - Access runtime variable\n */\n\nimport type { WorkflowExecutionContext } from './execution-context.js';\nimport type { StepResult } from '../core/index.js';\nimport { ValidationError } from '../core/index.js';\n\n/**\n * Regular expression to match ${{ expression }} patterns.\n * Captures the expression content between ${{ and }}.\n */\nconst EXPRESSION_PATTERN = /\\$\\{\\{\\s*([^}]+)\\s*\\}\\}/g;\n\n/**\n * Types of expression references.\n */\nexport type ExpressionType = 'inputs' | 'steps' | 'variables';\n\n/**\n * Parsed expression structure.\n */\nexport interface ParsedExpression {\n /** Original expression string */\n original: string;\n /** Expression type (inputs, steps, variables) */\n type: ExpressionType;\n /** Path segments after the type */\n path: string[];\n}\n\n/**\n * Result of expression resolution.\n */\nexport interface ResolveResult {\n /** Whether resolution succeeded */\n success: boolean;\n /** Resolved value if successful */\n value?: unknown;\n /** Error message if failed */\n error?: string;\n}\n\n/**\n * Parses an expression string into its components.\n *\n * @param expression - The expression content (without ${{ }})\n * @returns Parsed expression or null if invalid\n */\nexport function parseExpression(expression: string): ParsedExpression | null {\n const trimmed = expression.trim();\n const parts = trimmed.split('.');\n\n if (parts.length < 2) {\n return null;\n }\n\n const type = parts[0];\n if (type !== 'inputs' && type !== 'steps' && type !== 'variables') {\n return null;\n }\n\n return {\n original: expression,\n type: type as ExpressionType,\n path: parts.slice(1),\n };\n}\n\n/**\n * Safely accesses a nested property in an object.\n *\n * @param obj - The object to access\n * @param path - Array of property names\n * @returns The value at the path or undefined\n */\nfunction getNestedValue(obj: unknown, path: string[]): unknown {\n let current: unknown = obj;\n\n for (const key of path) {\n if (current === null || current === undefined) {\n return undefined;\n }\n if (typeof current !== 'object') {\n return undefined;\n }\n current = (current as Record<string, unknown>)[key];\n }\n\n return current;\n}\n\n/**\n * Resolves an inputs expression.\n *\n * @param path - Property path within inputs\n * @param context - Execution context\n * @returns Resolve result\n */\nfunction resolveInputs(path: string[], context: WorkflowExecutionContext): ResolveResult {\n const value = getNestedValue(context.inputs, path);\n if (value === undefined) {\n return {\n success: false,\n error: `Input '${path.join('.')}' not found`,\n };\n }\n return { success: true, value };\n}\n\n/**\n * Resolves a steps expression.\n *\n * @param path - Property path (stepId.output[.field...])\n * @param context - Execution context\n * @returns Resolve result\n */\nfunction resolveSteps(path: string[], context: WorkflowExecutionContext): ResolveResult {\n if (path.length < 2) {\n return {\n success: false,\n error: 'Steps expression requires at least stepId and output',\n };\n }\n\n const stepId = path[0];\n const outputKey = path[1];\n const rest = path.slice(2);\n\n if (stepId === undefined || outputKey === undefined) {\n return {\n success: false,\n error: 'Steps expression requires stepId and output',\n };\n }\n\n const stepResult: StepResult | undefined = context.stepResults.get(stepId);\n\n if (stepResult === undefined) {\n return {\n success: false,\n error: `Step '${stepId}' has not completed`,\n };\n }\n\n if (stepResult.status !== 'success') {\n return {\n success: false,\n error: `Step '${stepId}' did not complete successfully`,\n };\n }\n\n if (outputKey !== 'output') {\n return {\n success: false,\n error: `Invalid step property '${outputKey}', only 'output' is supported`,\n };\n }\n\n if (rest.length === 0) {\n return { success: true, value: stepResult.output };\n }\n\n const value = getNestedValue(stepResult.output, rest);\n if (value === undefined) {\n return {\n success: false,\n error: `Output field '${rest.join('.')}' not found in step '${stepId}'`,\n };\n }\n\n return { success: true, value };\n}\n\n/**\n * Resolves a variables expression.\n *\n * @param path - Property path within variables\n * @param context - Execution context\n * @returns Resolve result\n */\nfunction resolveVariables(path: string[], context: WorkflowExecutionContext): ResolveResult {\n if (path.length === 0) {\n return {\n success: false,\n error: 'Variables expression requires a variable name',\n };\n }\n\n const varName = path[0];\n const rest = path.slice(1);\n\n if (varName === undefined) {\n return {\n success: false,\n error: 'Variables expression requires a variable name',\n };\n }\n\n const varValue = context.variables.get(varName);\n\n if (varValue === undefined) {\n return {\n success: false,\n error: `Variable '${varName}' not found`,\n };\n }\n\n if (rest.length === 0) {\n return { success: true, value: varValue };\n }\n\n const value = getNestedValue(varValue, rest);\n if (value === undefined) {\n return {\n success: false,\n error: `Variable field '${rest.join('.')}' not found`,\n };\n }\n\n return { success: true, value };\n}\n\n/**\n * Resolves a single parsed expression against the context.\n *\n * @param parsed - Parsed expression\n * @param context - Execution context\n * @returns Resolve result\n */\nexport function resolveExpression(\n parsed: ParsedExpression,\n context: WorkflowExecutionContext\n): ResolveResult {\n switch (parsed.type) {\n case 'inputs':\n return resolveInputs(parsed.path, context);\n case 'steps':\n return resolveSteps(parsed.path, context);\n case 'variables':\n return resolveVariables(parsed.path, context);\n }\n}\n\n/**\n * Checks if a value contains expression patterns.\n *\n * @param value - Value to check\n * @returns True if value contains expressions\n */\nexport function containsExpressions(value: unknown): boolean {\n if (typeof value !== 'string') {\n return false;\n }\n // Reset regex state before testing (global flag causes lastIndex to persist)\n EXPRESSION_PATTERN.lastIndex = 0;\n return EXPRESSION_PATTERN.test(value);\n}\n\n/**\n * Resolves a single expression and returns the value.\n */\nfunction resolveSingleExpression(expression: string, context: WorkflowExecutionContext): unknown {\n const parsed = parseExpression(expression);\n if (parsed === null) {\n throw new ValidationError(`Invalid expression syntax: ${expression}`);\n }\n const result = resolveExpression(parsed, context);\n if (!result.success) {\n throw new ValidationError(result.error ?? `Failed to resolve: ${expression}`);\n }\n return result.value;\n}\n\n/**\n * Converts a resolved value to a string for interpolation.\n */\nfunction valueToString(value: unknown): string {\n if (value === undefined || value === null) return '';\n if (typeof value === 'string') return value;\n if (typeof value === 'number' || typeof value === 'boolean') return String(value);\n return JSON.stringify(value);\n}\n\n/**\n * Resolves all expressions in a string value.\n *\n * If the entire string is a single expression, returns the resolved value.\n * If the string contains multiple expressions or mixed content, returns a string\n * with all expressions replaced by their resolved values.\n */\nexport function resolveStringExpressions(\n value: string,\n context: WorkflowExecutionContext\n): unknown {\n EXPRESSION_PATTERN.lastIndex = 0;\n\n // Check if the entire value is a single expression\n const fullMatch = value.match(/^\\$\\{\\{\\s*([^}]+)\\s*\\}\\}$/);\n if (fullMatch?.[1] !== undefined) {\n return resolveSingleExpression(fullMatch[1], context);\n }\n\n // Handle multiple expressions or mixed content\n let resolvedString = value;\n EXPRESSION_PATTERN.lastIndex = 0;\n\n let match: RegExpExecArray | null;\n while ((match = EXPRESSION_PATTERN.exec(value)) !== null) {\n const expression = match[1];\n if (expression === undefined) continue;\n\n const resolved = resolveSingleExpression(expression, context);\n resolvedString = resolvedString.replace(match[0], valueToString(resolved));\n }\n\n return resolvedString;\n}\n\n/**\n * Recursively resolves expressions in a value.\n *\n * Handles strings, arrays, and objects. Primitives other than strings\n * are returned unchanged.\n *\n * @param input - Value containing potential expressions\n * @param context - Execution context\n * @returns Resolved value\n * @throws ValidationError if resolution fails\n */\nexport function resolveInput(input: unknown, context: WorkflowExecutionContext): unknown {\n // Handle strings with expressions\n if (typeof input === 'string') {\n if (containsExpressions(input)) {\n return resolveStringExpressions(input, context);\n }\n return input;\n }\n\n // Handle arrays\n if (Array.isArray(input)) {\n return input.map((item) => resolveInput(item, context));\n }\n\n // Handle objects\n if (input !== null && typeof input === 'object') {\n const resolved: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(input)) {\n resolved[key] = resolveInput(value, context);\n }\n return resolved;\n }\n\n // Return primitives unchanged\n return input;\n}\n\n/**\n * Validates that all expressions in a value can be resolved.\n * Does not actually resolve them, just checks validity.\n *\n * @param input - Value containing potential expressions\n * @param context - Execution context\n * @returns Array of validation errors (empty if all valid)\n */\nexport function validateExpressions(input: unknown, context: WorkflowExecutionContext): string[] {\n const errors: string[] = [];\n\n function validate(value: unknown): void {\n if (typeof value === 'string' && containsExpressions(value)) {\n try {\n resolveStringExpressions(value, context);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n errors.push(message);\n }\n } else if (Array.isArray(value)) {\n for (const item of value) {\n validate(item);\n }\n } else if (value !== null && typeof value === 'object') {\n for (const v of Object.values(value)) {\n validate(v);\n }\n }\n }\n\n validate(input);\n return errors;\n}\n\n/**\n * Extracts all expression references from a value.\n * Useful for determining step dependencies.\n *\n * @param input - Value containing potential expressions\n * @returns Array of parsed expressions\n */\nexport function extractExpressions(input: unknown): ParsedExpression[] {\n const expressions: ParsedExpression[] = [];\n\n function extract(value: unknown): void {\n if (typeof value === 'string') {\n // Reset regex state\n EXPRESSION_PATTERN.lastIndex = 0;\n let match: RegExpExecArray | null;\n while ((match = EXPRESSION_PATTERN.exec(value)) !== null) {\n const exprContent = match[1];\n if (exprContent !== undefined) {\n const parsed = parseExpression(exprContent);\n if (parsed !== null) {\n expressions.push(parsed);\n }\n }\n }\n } else if (Array.isArray(value)) {\n for (const item of value) {\n extract(item);\n }\n } else if (value !== null && typeof value === 'object') {\n for (const v of Object.values(value)) {\n extract(v);\n }\n }\n }\n\n extract(input);\n return expressions;\n}\n\n/**\n * Gets all step IDs referenced in expressions within a value.\n *\n * @param input - Value containing potential expressions\n * @returns Array of referenced step IDs\n */\nexport function getReferencedSteps(input: unknown): string[] {\n const stepIds = new Set<string>();\n const expressions = extractExpressions(input);\n\n for (const expr of expressions) {\n const firstPath = expr.path[0];\n if (expr.type === 'steps' && firstPath !== undefined) {\n stepIds.add(firstPath);\n }\n }\n\n return Array.from(stepIds);\n}\n","/**\n * @nexus-agents/workflows - Step Executor\n *\n * Executes individual workflow steps using agent experts.\n * Handles input resolution, error handling, retries, timeouts, and conditions.\n */\n\nimport type { Result, WorkflowStep, StepResult, AgentRole, Task } from '../core/index.js';\nimport { ok, err, WorkflowError, TimeoutError, ErrorCode } from '../core/index.js';\nimport type { Expert, ExpertFactory as ExpertFactoryType } from '../agents/index.js';\nimport type { WorkflowExecutionContext } from './execution-context.js';\nimport { resolveInput, getReferencedSteps } from './expression-resolver.js';\n\n/** Default timeout for step execution (5 minutes). */\nconst DEFAULT_TIMEOUT_MS = 300_000;\n\n/** Default number of retries. */\nconst DEFAULT_RETRIES = 0;\n\n/** Delay between retries in milliseconds. */\nconst DEFAULT_RETRY_DELAY_MS = 1000;\n\n/** Maximum retry delay (capped with exponential backoff). */\nconst MAX_RETRY_DELAY_MS = 30_000;\n\n/**\n * Interface for expert factory dependency.\n */\nexport interface IExpertFactory {\n createForRole(role: AgentRole): Result<Expert, Error>;\n}\n\n/**\n * Wrapper to adapt ExpertFactory to IExpertFactory interface.\n */\nexport class ExpertFactoryAdapter implements IExpertFactory {\n private readonly factory: typeof ExpertFactoryType;\n\n constructor(factory: typeof ExpertFactoryType) {\n this.factory = factory;\n }\n\n createForRole(role: AgentRole): Result<Expert, Error> {\n const roleToType: Record<string, string> = {\n code_expert: 'code',\n architecture_expert: 'architecture',\n security_expert: 'security',\n documentation_expert: 'documentation',\n testing_expert: 'testing',\n };\n\n const expertType = roleToType[role];\n if (expertType === undefined) {\n return err(new Error(`Unsupported agent role: ${role}`));\n }\n\n type BuiltInType = 'code' | 'architecture' | 'security' | 'documentation' | 'testing';\n return this.factory.createBuiltIn(expertType as BuiltInType);\n }\n}\n\n/** Dependencies for the step executor. */\nexport interface StepExecutorDeps {\n expertFactory: IExpertFactory;\n logger?: {\n debug: (message: string, data?: Record<string, unknown>) => void;\n info: (message: string, data?: Record<string, unknown>) => void;\n warn: (message: string, data?: Record<string, unknown>) => void;\n error: (message: string, data?: Record<string, unknown>) => void;\n };\n}\n\n/** Options for step execution. */\nexport interface StepExecutionOptions {\n timeoutMs?: number;\n retries?: number;\n retryDelayMs?: number;\n}\n\n// ============================================================================\n// Condition Evaluation Helpers\n// ============================================================================\n\nfunction checkSimpleCondition(condition: string): boolean | null {\n if (condition === 'always' || condition === 'true') return true;\n if (condition === 'never' || condition === 'false') return false;\n return null;\n}\n\nfunction checkStepStatusCondition(\n condition: string,\n context: WorkflowExecutionContext\n): boolean | null {\n const match = condition.match(/^steps\\.(\\w+)\\.status\\s*==\\s*['\"](\\w+)['\"]$/i);\n if (match === null) return null;\n\n const stepId = match[1];\n const expectedStatus = match[2]?.toLowerCase();\n if (stepId === undefined || expectedStatus === undefined) return false;\n\n const stepResult = context.stepResults.get(stepId);\n return stepResult?.status === expectedStatus;\n}\n\nfunction checkStepOutputCondition(\n condition: string,\n context: WorkflowExecutionContext\n): boolean | null {\n const match = condition.match(/^steps\\.(\\w+)\\.output$/i);\n if (match === null) return null;\n\n const stepId = match[1];\n if (stepId === undefined) return false;\n\n const stepResult = context.stepResults.get(stepId);\n return stepResult?.output !== undefined;\n}\n\nfunction evaluateCondition(condition: string, context: WorkflowExecutionContext): boolean {\n const trimmed = condition.trim();\n const lower = trimmed.toLowerCase();\n\n const simple = checkSimpleCondition(lower);\n if (simple !== null) return simple;\n\n const status = checkStepStatusCondition(trimmed, context);\n if (status !== null) return status;\n\n const output = checkStepOutputCondition(trimmed, context);\n if (output !== null) return output;\n\n return true; // Default: treat unrecognized as truthy\n}\n\n// ============================================================================\n// Utility Functions\n// ============================================================================\n\nfunction createTimeout(ms: number, stepId: string): Promise<never> {\n return new Promise((_, reject) => {\n setTimeout(() => {\n reject(new TimeoutError(`Step '${stepId}' timed out after ${String(ms)}ms`));\n }, ms);\n });\n}\n\nfunction calculateRetryDelay(attempt: number, baseDelayMs: number): number {\n const delay = baseDelayMs * Math.pow(2, attempt);\n return Math.min(delay, MAX_RETRY_DELAY_MS);\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction formatValue(value: unknown): string {\n if (value === null || value === undefined) return 'null';\n if (typeof value === 'string') {\n return value.length > 100 ? `${value.substring(0, 100)}...` : value;\n }\n if (typeof value === 'object') {\n const json = JSON.stringify(value);\n return json.length > 100 ? `${json.substring(0, 100)}...` : json;\n }\n return typeof value === 'number' || typeof value === 'boolean' ? String(value) : '[complex]';\n}\n\nfunction buildTaskDescription(step: WorkflowStep, inputs: Record<string, unknown>): string {\n const inputSummary = Object.entries(inputs)\n .map(([key, value]) => `- ${key}: ${formatValue(value)}`)\n .join('\\n');\n\n return `Execute action: ${step.action}\\n\\nInputs:\\n${inputSummary}`;\n}\n\nfunction extractErrorMessage(error: Error | undefined): string {\n if (error === undefined) return 'Unknown error';\n if (error instanceof WorkflowError && error.cause instanceof Error) {\n return extractErrorMessage(error.cause);\n }\n return error.message;\n}\n\nfunction isNonRetryableError(error: Error): boolean {\n if (error.name === 'ValidationError') return true;\n if (error instanceof WorkflowError) {\n const code = error.code;\n return (\n code === ErrorCode.VALIDATION_ERROR ||\n code === ErrorCode.WORKFLOW_PARSE_ERROR ||\n code === ErrorCode.INVALID_INPUT\n );\n }\n return false;\n}\n\n// ============================================================================\n// Step Executor Class\n// ============================================================================\n\n/**\n * Executor for individual workflow steps.\n */\nexport class StepExecutor {\n private readonly deps: StepExecutorDeps;\n\n constructor(deps: StepExecutorDeps) {\n this.deps = deps;\n }\n\n async execute(\n step: WorkflowStep,\n context: WorkflowExecutionContext,\n options?: StepExecutionOptions\n ): Promise<Result<StepResult, WorkflowError>> {\n const startTime = Date.now();\n\n // Pre-execution checks\n const preCheck = this.preExecutionChecks(step, context, startTime);\n if (preCheck !== null) return preCheck;\n\n // Resolve inputs\n const inputsResult = this.resolveStepInputs(step, context);\n if (!inputsResult.ok) return inputsResult;\n\n // Execute with retries\n return this.executeWithRetries(step, inputsResult.value, context, startTime, options);\n }\n\n private preExecutionChecks(\n step: WorkflowStep,\n context: WorkflowExecutionContext,\n startTime: number\n ): Result<StepResult, WorkflowError> | null {\n if (context.cancelled) {\n return err(\n new WorkflowError(`Execution cancelled before step '${step.id}'`, {\n context: { stepId: step.id },\n })\n );\n }\n\n const depCheck = this.checkDependencies(step, context);\n if (!depCheck.ok) return depCheck;\n\n if (step.condition !== undefined && !evaluateCondition(step.condition, context)) {\n return ok({\n stepId: step.id,\n output: null,\n durationMs: Date.now() - startTime,\n status: 'skipped',\n });\n }\n\n return null;\n }\n\n private resolveStepInputs(\n step: WorkflowStep,\n context: WorkflowExecutionContext\n ): Result<Record<string, unknown>, WorkflowError> {\n try {\n const resolved = resolveInput(step.inputs, context) as Record<string, unknown>;\n return ok(resolved);\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error';\n const errorOptions: { context: Record<string, unknown>; cause?: Error } = {\n context: { stepId: step.id },\n };\n if (error instanceof Error) errorOptions.cause = error;\n return err(\n new WorkflowError(\n `Failed to resolve inputs for step '${step.id}': ${message}`,\n errorOptions\n )\n );\n }\n }\n\n private getRetryParams(\n step: WorkflowStep,\n options?: StepExecutionOptions\n ): {\n timeoutMs: number;\n retries: number;\n retryDelayMs: number;\n } {\n return {\n timeoutMs: options?.timeoutMs ?? step.timeout ?? DEFAULT_TIMEOUT_MS,\n retries: options?.retries ?? step.retries ?? DEFAULT_RETRIES,\n retryDelayMs: options?.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS,\n };\n }\n\n private createCancelledError(\n step: WorkflowStep,\n attempt: number\n ): Result<StepResult, WorkflowError> {\n return err(\n new WorkflowError(`Execution cancelled during step '${step.id}'`, {\n context: { stepId: step.id, attempt },\n })\n );\n }\n\n private async executeWithRetries(\n step: WorkflowStep,\n resolvedInputs: Record<string, unknown>,\n context: WorkflowExecutionContext,\n startTime: number,\n options?: StepExecutionOptions\n ): Promise<Result<StepResult, WorkflowError>> {\n const { timeoutMs, retries, retryDelayMs } = this.getRetryParams(step, options);\n let lastError: Error | undefined;\n\n for (let attempt = 0; attempt <= retries; attempt++) {\n if (attempt > 0) await sleep(calculateRetryDelay(attempt - 1, retryDelayMs));\n if (context.cancelled) return this.createCancelledError(step, attempt);\n\n const result = await this.executeAttempt(step, resolvedInputs, timeoutMs, startTime);\n if (result.ok) return result;\n\n lastError = result.error;\n if (isNonRetryableError(lastError)) return result;\n }\n\n return ok({\n stepId: step.id,\n output: null,\n durationMs: Date.now() - startTime,\n status: 'failed',\n error: extractErrorMessage(lastError),\n });\n }\n\n private checkDependencies(\n step: WorkflowStep,\n context: WorkflowExecutionContext\n ): Result<void, WorkflowError> {\n const dependencies = step.dependsOn ?? [];\n const referencedSteps = getReferencedSteps(step.inputs);\n const allDeps = new Set([...dependencies, ...referencedSteps]);\n\n for (const depId of allDeps) {\n if (context.stepResults.get(depId) === undefined) {\n return err(\n new WorkflowError(`Dependency '${depId}' not completed for step '${step.id}'`, {\n context: { stepId: step.id, missingDependency: depId },\n })\n );\n }\n }\n\n return ok(undefined);\n }\n\n private async executeAttempt(\n step: WorkflowStep,\n resolvedInputs: Record<string, unknown>,\n timeoutMs: number,\n startTime: number\n ): Promise<Result<StepResult, WorkflowError>> {\n const expertResult = this.deps.expertFactory.createForRole(step.agent);\n if (!expertResult.ok) {\n return err(\n new WorkflowError(`Failed to create expert for role '${step.agent}'`, {\n context: { stepId: step.id, role: step.agent },\n cause: expertResult.error,\n })\n );\n }\n\n const expert = expertResult.value;\n const task: Task = {\n id: `${step.id}-${String(Date.now())}`,\n description: buildTaskDescription(step, resolvedInputs),\n context: { metadata: { stepId: step.id, action: step.action, inputs: resolvedInputs } },\n };\n\n try {\n return await this.runExpertWithTimeout(expert, task, step, timeoutMs, startTime);\n } finally {\n await this.cleanupExpert(expert);\n }\n }\n\n private async runExpertWithTimeout(\n expert: Expert,\n task: Task,\n step: WorkflowStep,\n timeoutMs: number,\n startTime: number\n ): Promise<Result<StepResult, WorkflowError>> {\n try {\n const taskResult = await Promise.race([\n expert.execute(task),\n createTimeout(timeoutMs, step.id),\n ]);\n\n if (!taskResult.ok) {\n return err(\n new WorkflowError(`Expert execution failed for step '${step.id}'`, {\n context: { stepId: step.id },\n cause: taskResult.error,\n })\n );\n }\n\n return ok({\n stepId: step.id,\n output: taskResult.value.output,\n durationMs: Date.now() - startTime,\n status: 'success',\n });\n } catch (error) {\n return this.handleExecutionError(error, step, timeoutMs);\n }\n }\n\n private handleExecutionError(\n error: unknown,\n step: WorkflowStep,\n timeoutMs: number\n ): Result<StepResult, WorkflowError> {\n if (error instanceof TimeoutError) {\n return err(\n new WorkflowError(error.message, {\n context: { stepId: step.id, timeout: timeoutMs },\n })\n );\n }\n\n const message = error instanceof Error ? error.message : 'Unknown error';\n const errorOptions: { context: Record<string, unknown>; cause?: Error } = {\n context: { stepId: step.id },\n };\n if (error instanceof Error) errorOptions.cause = error;\n\n return err(\n new WorkflowError(`Unexpected error in step '${step.id}': ${message}`, errorOptions)\n );\n }\n\n private async cleanupExpert(expert: Expert): Promise<void> {\n if (typeof expert.cleanup === 'function') {\n try {\n await expert.cleanup();\n } catch {\n // Ignore cleanup errors\n }\n }\n }\n}\n\n/**\n * Creates a new StepExecutor instance.\n */\nexport function createStepExecutor(deps: StepExecutorDeps): StepExecutor {\n return new StepExecutor(deps);\n}\n","/**\n * @nexus-agents/mcp - MCP Server\n *\n * Main MCP server implementation for Nexus Agents orchestration.\n * Provides factory functions to create and start the server with\n * stdio or custom transports.\n *\n * (Source: MCP Protocol 2025-11-25)\n */\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';\n\nimport { createLogger, type Result, ok, err, type ILogger } from '../core/index.js';\n\nimport { VERSION } from './index.js';\n\n/**\n * Server configuration options.\n */\nexport interface ServerConfig {\n /** Server name (default: \"nexus-agents\") */\n readonly name?: string;\n /** Server version (default: package version) */\n readonly version?: string;\n /** Logger instance */\n readonly logger?: ILogger;\n}\n\n/**\n * Server creation result containing the server and logger.\n */\nexport interface ServerInstance {\n /** The MCP server instance */\n readonly server: McpServer;\n /** The logger instance for this server */\n readonly logger: ILogger;\n}\n\n/**\n * Error type for server operations.\n */\nexport interface ServerError {\n code: 'SERVER_CREATION_FAILED' | 'SERVER_START_FAILED' | 'SERVER_STOP_FAILED';\n message: string;\n cause?: Error;\n}\n\nconst DEFAULT_SERVER_NAME = 'nexus-agents';\n\n/**\n * Creates a ServerError with the given code, message, and optional cause.\n */\nfunction createServerError(\n code: ServerError['code'],\n message: string,\n error: unknown\n): ServerError {\n const serverError: ServerError = { code, message };\n if (error instanceof Error) {\n serverError.cause = error;\n }\n return serverError;\n}\n\n/**\n * Creates a new MCP server instance.\n *\n * @param config - Optional server configuration\n * @returns Result containing the server instance or an error\n *\n * @example\n * ```typescript\n * const result = createServer({ name: 'my-server' });\n * if (result.ok) {\n * const { server, logger } = result.value;\n * // Register tools on server\n * }\n * ```\n */\nexport function createServer(config?: ServerConfig): Result<ServerInstance, ServerError> {\n const serverName = config?.name ?? DEFAULT_SERVER_NAME;\n const serverVersion = config?.version ?? VERSION;\n const logger = config?.logger ?? createLogger({ component: 'mcp-server' });\n\n try {\n logger.info('Creating MCP server', {\n name: serverName,\n version: serverVersion,\n });\n\n const server = new McpServer({\n name: serverName,\n version: serverVersion,\n });\n\n logger.debug('MCP server created successfully');\n\n return ok({ server, logger });\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n logger.error('Failed to create MCP server', error instanceof Error ? error : undefined);\n return err(\n createServerError(\n 'SERVER_CREATION_FAILED',\n `Failed to create MCP server: ${errorMessage}`,\n error\n )\n );\n }\n}\n\n/**\n * Connects the server to a transport.\n *\n * @param server - The MCP server instance\n * @param transport - The transport to connect to\n * @param logger - Logger for the operation\n * @returns Result indicating success or failure\n */\nexport async function connectTransport(\n server: McpServer,\n transport: Transport,\n logger?: ILogger\n): Promise<Result<void, ServerError>> {\n const log = logger ?? createLogger({ component: 'mcp-server' });\n\n try {\n log.info('Connecting server to transport');\n await server.connect(transport);\n log.debug('Server connected to transport successfully');\n return ok(undefined);\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n log.error('Failed to connect to transport', error instanceof Error ? error : undefined);\n return err(\n createServerError(\n 'SERVER_START_FAILED',\n `Failed to connect to transport: ${errorMessage}`,\n error\n )\n );\n }\n}\n\n/**\n * Starts the MCP server with stdio transport.\n *\n * This is the main entry point for running the server as a standalone process.\n * The server will communicate over stdin/stdout using the MCP protocol.\n *\n * @param config - Optional server configuration\n * @returns Result indicating success or failure\n *\n * @example\n * ```typescript\n * const result = await startStdioServer();\n * if (!result.ok) {\n * console.error('Failed to start server:', result.error.message);\n * process.exit(1);\n * }\n * ```\n */\nexport async function startStdioServer(\n config?: ServerConfig\n): Promise<Result<ServerInstance, ServerError>> {\n const serverResult = createServer(config);\n if (!serverResult.ok) {\n return serverResult;\n }\n\n const { server, logger } = serverResult.value;\n\n try {\n logger.info('Starting stdio transport');\n const transport = new StdioServerTransport();\n\n const connectResult = await connectTransport(server, transport, logger);\n if (!connectResult.ok) {\n return connectResult;\n }\n\n logger.info('MCP server running with stdio transport');\n return ok({ server, logger });\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n logger.error('Failed to start stdio server', error instanceof Error ? error : undefined);\n return err(\n createServerError(\n 'SERVER_START_FAILED',\n `Failed to start stdio server: ${errorMessage}`,\n error\n )\n );\n }\n}\n\n/**\n * Gracefully closes the server connection.\n *\n * @param server - The MCP server to close\n * @param logger - Optional logger\n * @returns Result indicating success or failure\n */\nexport async function closeServer(\n server: McpServer,\n logger?: ILogger\n): Promise<Result<void, ServerError>> {\n const log = logger ?? createLogger({ component: 'mcp-server' });\n\n try {\n log.info('Closing MCP server');\n await server.close();\n log.info('MCP server closed successfully');\n return ok(undefined);\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n log.error('Failed to close server', error instanceof Error ? error : undefined);\n return err(\n createServerError('SERVER_STOP_FAILED', `Failed to close server: ${errorMessage}`, error)\n );\n }\n}\n","/**\n * @nexus-agents/mcp - Validation Middleware\n *\n * Input validation helper using Zod schemas.\n * All tool inputs must be validated at the boundary.\n *\n * (Source: MCP Protocol 2025-11-25, Zod Documentation)\n */\n\nimport type { ZodSchema, ZodError, ZodIssue } from 'zod';\n\nimport { type Result, ok, err, ValidationError } from '../../core/index.js';\n\n/**\n * Formats a Zod validation error into a human-readable message.\n *\n * @param error - The Zod error to format\n * @returns A formatted error message\n */\nfunction formatZodError(error: ZodError): string {\n const issues = error.issues.map(formatZodIssue);\n return issues.join('; ');\n}\n\n/**\n * Formats a single Zod issue into a readable string.\n *\n * @param issue - The Zod issue to format\n * @returns A formatted issue message\n */\nfunction formatZodIssue(issue: ZodIssue): string {\n const path = issue.path.length > 0 ? `${issue.path.join('.')}: ` : '';\n return `${path}${issue.message}`;\n}\n\n/**\n * Validates tool input against a Zod schema.\n *\n * This function should be called at the start of every tool handler\n * to validate incoming arguments before processing.\n *\n * @template T - The expected type after validation\n * @param schema - The Zod schema to validate against\n * @param args - The unknown input to validate\n * @returns Result containing validated data or a ValidationError\n *\n * @example\n * ```typescript\n * const InputSchema = z.object({\n * task: z.string().min(1),\n * context: z.record(z.unknown()).optional(),\n * });\n *\n * server.tool('my_tool', InputSchema.shape, async (args) => {\n * const result = validateToolInput(InputSchema, args);\n * if (!result.ok) {\n * return { isError: true, content: [{ type: 'text', text: result.error.message }] };\n * }\n * const { task, context } = result.value;\n * // Process validated input...\n * });\n * ```\n */\nexport function validateToolInput<T>(\n schema: ZodSchema<T>,\n args: unknown\n): Result<T, ValidationError> {\n const parsed = schema.safeParse(args);\n\n if (parsed.success) {\n return ok(parsed.data);\n }\n\n const message = formatZodError(parsed.error);\n const validationError = new ValidationError(`Invalid tool input: ${message}`, {\n context: {\n issues: parsed.error.issues,\n receivedType: typeof args,\n },\n });\n\n return err(validationError);\n}\n\n/**\n * Creates a validation function bound to a specific schema.\n *\n * Useful for reusing the same schema across multiple tools.\n *\n * @template T - The expected type after validation\n * @param schema - The Zod schema to bind\n * @returns A validation function for the schema\n *\n * @example\n * ```typescript\n * const validateTask = createValidator(TaskSchema);\n *\n * // Later in tool handlers:\n * const result = validateTask(args);\n * ```\n */\nexport function createValidator<T>(\n schema: ZodSchema<T>\n): (args: unknown) => Result<T, ValidationError> {\n return (args: unknown) => validateToolInput(schema, args);\n}\n\n/**\n * Type guard to check if a value is a Zod error.\n *\n * @param error - The value to check\n * @returns True if the value is a ZodError\n */\nexport function isZodError(error: unknown): error is ZodError {\n return (\n error !== null &&\n typeof error === 'object' &&\n 'issues' in error &&\n Array.isArray((error as ZodError).issues)\n );\n}\n","/**\n * @nexus-agents/mcp - Rate Limiter Middleware\n *\n * Token bucket implementation for rate limiting MCP tool calls.\n * Prevents abuse and ensures fair resource usage.\n *\n * (Source: Token Bucket Algorithm, RFC 6585)\n */\n\nimport { createLogger, type ILogger } from '../../core/index.js';\n\n/**\n * Configuration for the token bucket rate limiter.\n */\nexport interface RateLimiterConfig {\n /** Maximum number of tokens in the bucket */\n readonly capacity: number;\n /** Number of tokens added per interval */\n readonly refillRate: number;\n /** Interval in milliseconds between token refills (default: 1000ms) */\n readonly refillIntervalMs?: number;\n /** Optional logger instance */\n readonly logger?: ILogger;\n /** Optional identifier for logging */\n readonly name?: string;\n}\n\n/**\n * Current state of the rate limiter.\n */\nexport interface RateLimiterState {\n /** Current number of available tokens */\n readonly tokens: number;\n /** Capacity of the bucket */\n readonly capacity: number;\n /** Time until next token is available (0 if tokens available) */\n readonly nextTokenMs: number;\n}\n\nconst DEFAULT_REFILL_INTERVAL_MS = 1000;\n\n/**\n * Token bucket rate limiter implementation.\n *\n * The token bucket algorithm allows for bursting up to the capacity,\n * while maintaining a steady-state rate equal to the refill rate.\n *\n * @example\n * ```typescript\n * const limiter = new RateLimiter({\n * capacity: 100,\n * refillRate: 10,\n * refillIntervalMs: 1000,\n * });\n *\n * if (limiter.tryAcquire()) {\n * // Proceed with operation\n * } else {\n * // Rate limited, reject or queue\n * }\n * ```\n */\nexport class RateLimiter {\n private tokens: number;\n private readonly capacity: number;\n private readonly refillRate: number;\n private readonly refillIntervalMs: number;\n private lastRefillTime: number;\n private readonly logger: ILogger;\n private readonly name: string;\n\n constructor(config: RateLimiterConfig) {\n this.capacity = config.capacity;\n this.refillRate = config.refillRate;\n this.refillIntervalMs = config.refillIntervalMs ?? DEFAULT_REFILL_INTERVAL_MS;\n this.tokens = this.capacity;\n this.lastRefillTime = Date.now();\n this.name = config.name ?? 'rate-limiter';\n this.logger = config.logger ?? createLogger({ component: this.name });\n\n this.logger.debug('Rate limiter initialized', {\n capacity: this.capacity,\n refillRate: this.refillRate,\n refillIntervalMs: this.refillIntervalMs,\n });\n }\n\n /**\n * Refills tokens based on elapsed time.\n * Called automatically before each acquire attempt.\n */\n private refill(): void {\n const now = Date.now();\n const elapsed = now - this.lastRefillTime;\n const intervals = Math.floor(elapsed / this.refillIntervalMs);\n\n if (intervals > 0) {\n const tokensToAdd = intervals * this.refillRate;\n this.tokens = Math.min(this.capacity, this.tokens + tokensToAdd);\n this.lastRefillTime = now - (elapsed % this.refillIntervalMs);\n\n if (tokensToAdd > 0) {\n this.logger.debug('Tokens refilled', {\n added: tokensToAdd,\n current: this.tokens,\n });\n }\n }\n }\n\n /**\n * Attempts to acquire a token.\n *\n * @param count - Number of tokens to acquire (default: 1)\n * @returns True if tokens were acquired, false if rate limited\n */\n tryAcquire(count = 1): boolean {\n this.refill();\n\n if (this.tokens >= count) {\n this.tokens -= count;\n this.logger.debug('Token acquired', {\n requested: count,\n remaining: this.tokens,\n });\n return true;\n }\n\n this.logger.warn('Rate limit exceeded', {\n requested: count,\n available: this.tokens,\n });\n return false;\n }\n\n /**\n * Gets the current state of the rate limiter.\n *\n * @returns The current rate limiter state\n */\n getState(): RateLimiterState {\n this.refill();\n\n const nextTokenMs =\n this.tokens > 0 ? 0 : this.refillIntervalMs - (Date.now() - this.lastRefillTime);\n\n return {\n tokens: this.tokens,\n capacity: this.capacity,\n nextTokenMs: Math.max(0, nextTokenMs),\n };\n }\n\n /**\n * Resets the rate limiter to full capacity.\n * Useful for testing or after configuration changes.\n */\n reset(): void {\n this.tokens = this.capacity;\n this.lastRefillTime = Date.now();\n this.logger.debug('Rate limiter reset', { tokens: this.tokens });\n }\n}\n\n/**\n * Creates a rate limiter with default settings suitable for MCP tools.\n *\n * Default configuration:\n * - Capacity: 100 tokens\n * - Refill rate: 10 tokens per second\n *\n * @param name - Optional name for the rate limiter\n * @param logger - Optional logger instance\n * @returns A configured RateLimiter instance\n */\nexport function createDefaultRateLimiter(name?: string, logger?: ILogger): RateLimiter {\n const config: RateLimiterConfig = {\n capacity: 100,\n refillRate: 10,\n refillIntervalMs: 1000,\n };\n if (name !== undefined) {\n (config as { name?: string }).name = name;\n }\n if (logger !== undefined) {\n (config as { logger?: ILogger }).logger = logger;\n }\n return new RateLimiter(config);\n}\n","/**\n * @nexus-agents/mcp - Logging Middleware\n *\n * Structured logger context for MCP operations.\n * Provides consistent logging across all MCP tools and handlers.\n */\n\nimport { createLogger, type ILogger, type LogContext } from '../../core/index.js';\n\n/**\n * MCP-specific log context fields.\n */\nexport interface McpLogContext extends LogContext {\n /** The tool being executed */\n tool?: string;\n /** Request ID for tracing */\n requestId?: string;\n /** Duration of the operation in milliseconds */\n durationMs?: number;\n /** Whether the operation succeeded */\n success?: boolean;\n /** Error code if operation failed */\n errorCode?: string;\n}\n\n/**\n * Creates a logger with MCP-specific context.\n *\n * @param baseContext - Base context to include in all log entries\n * @returns An ILogger instance with MCP context\n *\n * @example\n * ```typescript\n * const logger = createMcpLogger({ requestId: 'req-123' });\n * logger.info('Processing request', { tool: 'orchestrate' });\n * ```\n */\nexport function createMcpLogger(baseContext?: McpLogContext): ILogger {\n return createLogger({\n component: 'mcp',\n ...baseContext,\n });\n}\n\n/**\n * Creates a child logger for a specific tool execution.\n *\n * @param parentLogger - The parent logger instance\n * @param toolName - Name of the tool being executed\n * @param requestId - Optional request ID for tracing\n * @returns A child logger with tool context\n */\nexport function createToolLogger(\n parentLogger: ILogger,\n toolName: string,\n requestId?: string\n): ILogger {\n const context: McpLogContext = {\n tool: toolName,\n };\n\n if (requestId !== undefined) {\n context.requestId = requestId;\n }\n\n return parentLogger.child(context);\n}\n\n/**\n * Logs the start of a tool execution.\n *\n * @param logger - The logger to use\n * @param toolName - Name of the tool\n * @param args - Tool arguments (sanitized for logging)\n */\nexport function logToolStart(\n logger: ILogger,\n toolName: string,\n args?: Record<string, unknown>\n): void {\n logger.info('Tool execution started', {\n tool: toolName,\n hasArgs: args !== undefined,\n argKeys: args !== undefined ? Object.keys(args) : [],\n });\n}\n\n/**\n * Logs the successful completion of a tool execution.\n *\n * @param logger - The logger to use\n * @param toolName - Name of the tool\n * @param durationMs - Duration of the execution in milliseconds\n * @param resultInfo - Optional information about the result\n */\nexport function logToolSuccess(\n logger: ILogger,\n toolName: string,\n durationMs: number,\n resultInfo?: Record<string, unknown>\n): void {\n logger.info('Tool execution completed', {\n tool: toolName,\n durationMs,\n success: true,\n ...resultInfo,\n });\n}\n\n/**\n * Logs a failed tool execution.\n *\n * @param logger - The logger to use\n * @param toolName - Name of the tool\n * @param error - The error that occurred\n * @param durationMs - Duration of the execution in milliseconds\n */\nexport function logToolError(\n logger: ILogger,\n toolName: string,\n error: Error,\n durationMs: number\n): void {\n logger.error('Tool execution failed', error, {\n tool: toolName,\n durationMs,\n success: false,\n errorCode: 'code' in error ? (error as { code: string }).code : undefined,\n });\n}\n\n/**\n * Creates a timing utility for measuring operation duration.\n *\n * @returns An object with start time and elapsed() method\n *\n * @example\n * ```typescript\n * const timer = createTimer();\n * // ... perform operation\n * const durationMs = timer.elapsed();\n * ```\n */\nexport function createTimer(): { elapsed: () => number } {\n const startTime = Date.now();\n return {\n elapsed: () => Date.now() - startTime,\n };\n}\n\n/**\n * Higher-order function that wraps a tool handler with logging.\n *\n * @template TArgs - Tool argument type\n * @template TResult - Tool result type\n * @param toolName - Name of the tool\n * @param handler - The tool handler function\n * @param logger - The logger to use\n * @returns A wrapped handler with automatic logging\n *\n * @example\n * ```typescript\n * const wrappedHandler = withLogging(\n * 'my_tool',\n * async (args) => { ... },\n * logger\n * );\n * ```\n */\nexport function withLogging<TArgs, TResult>(\n toolName: string,\n handler: (args: TArgs) => Promise<TResult>,\n logger: ILogger\n): (args: TArgs) => Promise<TResult> {\n const toolLogger = createToolLogger(logger, toolName);\n\n return async (args: TArgs): Promise<TResult> => {\n const timer = createTimer();\n logToolStart(toolLogger, toolName, args as Record<string, unknown>);\n\n try {\n const result = await handler(args);\n logToolSuccess(toolLogger, toolName, timer.elapsed());\n return result;\n } catch (error) {\n logToolError(\n toolLogger,\n toolName,\n error instanceof Error ? error : new Error(String(error)),\n timer.elapsed()\n );\n throw error;\n }\n };\n}\n","/**\n * @nexus-agents/mcp - Create Expert Tool\n *\n * MCP tool for creating expert agents dynamically.\n * Supports built-in expert types: code, architecture, security, documentation, testing.\n */\n\nimport { z } from 'zod';\nimport type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport type { ILogger, AgentCapability } from '../../core/index.js';\nimport type { RateLimiter } from '../middleware/rate-limiter.js';\nimport {\n ExpertFactory,\n Expert,\n type BuiltInExpertType,\n BUILT_IN_EXPERTS,\n} from '../../agents/index.js';\n\n/**\n * Input schema for create_expert tool.\n */\nexport const CreateExpertInputSchema = z.object({\n role: z\n .enum([\n 'code_expert',\n 'architecture_expert',\n 'security_expert',\n 'documentation_expert',\n 'testing_expert',\n ])\n .describe('Expert role to create'),\n modelPreference: z.string().optional().describe('Preferred model (e.g., claude-sonnet-4)'),\n});\n\n/**\n * Type for validated create expert input.\n */\nexport type CreateExpertInput = z.infer<typeof CreateExpertInputSchema>;\n\n/**\n * Expert factory interface for dependency injection.\n */\nexport interface IExpertFactory {\n createBuiltIn(\n type: BuiltInExpertType,\n options?: { modelOverrides?: { modelId?: string } }\n ): { ok: true; value: Expert } | { ok: false; error: Error };\n}\n\n/**\n * Dependencies for create_expert tool.\n */\nexport interface CreateExpertDeps {\n /** Expert factory for creating experts */\n expertFactory: IExpertFactory;\n /** Registry to track created experts */\n expertRegistry: Map<string, Expert>;\n /** Optional logger */\n logger?: ILogger;\n /** Optional rate limiter for throttling tool calls */\n rateLimiter?: RateLimiter;\n}\n\n/**\n * Response from create_expert tool.\n */\nexport interface CreateExpertResponse {\n /** Unique expert ID */\n expertId: string;\n /** Expert role */\n role: string;\n /** List of capabilities */\n capabilities: readonly AgentCapability[];\n /** Expert status */\n status: 'ready';\n}\n\n/**\n * Maximum number of experts allowed in the registry.\n * Prevents unbounded memory growth from expert creation.\n */\nconst MAX_EXPERTS = 100;\n\n/**\n * Maps role to built-in expert type.\n */\nconst ROLE_TO_EXPERT_TYPE: Record<string, BuiltInExpertType> = {\n code_expert: 'code',\n architecture_expert: 'architecture',\n security_expert: 'security',\n documentation_expert: 'documentation',\n testing_expert: 'testing',\n};\n\n/**\n * Validates the role and returns the corresponding expert type.\n */\nfunction getExpertType(role: string): BuiltInExpertType | undefined {\n return ROLE_TO_EXPERT_TYPE[role];\n}\n\n/**\n * Builds the create expert response.\n */\nfunction buildResponse(expert: Expert): CreateExpertResponse {\n return {\n expertId: expert.id,\n role: expert.role,\n capabilities: expert.capabilities,\n status: 'ready',\n };\n}\n\n/**\n * Creates an expert using the factory.\n */\nfunction createExpertFromFactory(\n deps: CreateExpertDeps,\n expertType: BuiltInExpertType,\n modelPreference?: string\n): { ok: true; value: Expert } | { ok: false; error: string } {\n const options =\n modelPreference !== undefined ? { modelOverrides: { modelId: modelPreference } } : undefined;\n\n const result = deps.expertFactory.createBuiltIn(expertType, options);\n\n if (!result.ok) {\n return { ok: false, error: result.error.message };\n }\n\n return { ok: true, value: result.value };\n}\n\n/**\n * Handles the create_expert tool execution.\n */\nfunction handleCreateExpert(\n deps: CreateExpertDeps,\n args: CreateExpertInput\n): { ok: true; value: CreateExpertResponse } | { ok: false; error: string } {\n const { role, modelPreference } = args;\n\n // Map role to expert type\n const expertType = getExpertType(role);\n if (expertType === undefined) {\n return { ok: false, error: `Invalid role: ${role}` };\n }\n\n // Create expert\n const createResult = createExpertFromFactory(deps, expertType, modelPreference);\n if (!createResult.ok) {\n return { ok: false, error: createResult.error };\n }\n\n const expert = createResult.value;\n\n // Check registry bounds to prevent unbounded memory growth\n if (deps.expertRegistry.size >= MAX_EXPERTS) {\n return {\n ok: false,\n error: `Maximum number of experts (${String(MAX_EXPERTS)}) reached. Remove unused experts first.`,\n };\n }\n\n // Track in registry\n deps.expertRegistry.set(expert.id, expert);\n\n // Log creation\n deps.logger?.info('Expert created', {\n expertId: expert.id,\n role: expert.role,\n capabilities: expert.capabilities,\n });\n\n return { ok: true, value: buildResponse(expert) };\n}\n\n/** MCP tool response type for create_expert */\ntype CreateExpertToolResponse = {\n content: Array<{ type: 'text'; text: string }>;\n isError?: boolean;\n};\n\n/**\n * Creates a handler function for the create_expert tool.\n * @param deps - Tool dependencies\n * @returns Handler function for the tool\n */\nfunction createToolHandler(deps: CreateExpertDeps) {\n return (args: unknown): CreateExpertToolResponse => {\n // Rate limiting check\n if (deps.rateLimiter !== undefined) {\n const acquired = deps.rateLimiter.tryAcquire();\n if (!acquired) {\n const state = deps.rateLimiter.getState();\n return {\n isError: true,\n content: [\n {\n type: 'text',\n text: `Rate limit exceeded. Try again in ${String(state.nextTokenMs)}ms.`,\n },\n ],\n };\n }\n }\n\n // Validate input\n const validationResult = CreateExpertInputSchema.safeParse(args);\n if (!validationResult.success) {\n const errorMessage = validationResult.error.issues\n .map((issue) => `${issue.path.join('.')}: ${issue.message}`)\n .join('; ');\n return {\n isError: true,\n content: [{ type: 'text', text: `Validation error: ${errorMessage}` }],\n };\n }\n\n // Execute tool logic\n const result = handleCreateExpert(deps, validationResult.data);\n\n if (!result.ok) {\n return {\n isError: true,\n content: [{ type: 'text', text: `Failed to create expert: ${result.error}` }],\n };\n }\n\n return {\n content: [{ type: 'text', text: JSON.stringify(result.value, null, 2) }],\n };\n };\n}\n\n/**\n * Registers the create_expert tool with the MCP server.\n *\n * @param server - MCP server instance\n * @param deps - Tool dependencies\n */\nexport function registerCreateExpertTool(server: McpServer, deps: CreateExpertDeps): void {\n const toolSchema = {\n role: z\n .enum([\n 'code_expert',\n 'architecture_expert',\n 'security_expert',\n 'documentation_expert',\n 'testing_expert',\n ])\n .describe('Expert role to create'),\n modelPreference: z.string().optional().describe('Preferred model (e.g., claude-sonnet-4)'),\n };\n\n const description =\n 'Create a specialized expert agent for code, architecture, security, documentation, or testing tasks';\n\n // eslint-disable-next-line @typescript-eslint/no-deprecated -- Consistent with other tools in codebase\n server.tool('create_expert', description, toolSchema, createToolHandler(deps));\n}\n\n/**\n * Creates default dependencies for the create_expert tool.\n *\n * @param logger - Optional logger instance\n * @returns CreateExpertDeps with default factory and empty registry\n */\nexport function createDefaultDeps(logger?: ILogger): CreateExpertDeps {\n const deps: CreateExpertDeps = {\n expertFactory: ExpertFactory,\n expertRegistry: new Map<string, Expert>(),\n };\n if (logger !== undefined) {\n deps.logger = logger;\n }\n return deps;\n}\n\n/**\n * Gets the list of available expert roles.\n */\nexport function getAvailableRoles(): string[] {\n return Object.keys(ROLE_TO_EXPERT_TYPE);\n}\n\n/**\n * Gets capabilities for a given expert role.\n */\nexport function getCapabilitiesForRole(role: string): readonly AgentCapability[] | undefined {\n const expertType = getExpertType(role);\n if (expertType === undefined) {\n return undefined;\n }\n return BUILT_IN_EXPERTS[expertType].capabilities;\n}\n","/**\n * @nexus-agents/mcp - Run Workflow Tool\n *\n * MCP tool for executing workflow templates with the workflow engine.\n * Supports both built-in templates and custom template paths.\n */\n\nimport { z } from 'zod';\nimport type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport type { Result } from '../../core/index.js';\nimport type { IWorkflowEngine, WorkflowDefinition, StepResult, ILogger } from '../../core/index.js';\nimport type { RateLimiter } from '../middleware/rate-limiter.js';\nimport { WorkflowError, ParseError } from '../../core/index.js';\n\n/**\n * Input schema for the run_workflow tool.\n */\nexport const RunWorkflowInputSchema = z.object({\n template: z.string().min(1).describe('Workflow template name (e.g., code-review) or file path'),\n inputs: z.record(z.unknown()).describe('Workflow inputs as key-value pairs'),\n dryRun: z.boolean().optional().default(false).describe('Validate workflow without executing'),\n});\n\nexport type RunWorkflowInput = z.infer<typeof RunWorkflowInputSchema>;\n\n/**\n * Workflow execution result returned by the tool.\n */\nexport interface WorkflowToolResult {\n executionId: string;\n workflowName: string;\n status: 'completed' | 'failed';\n stepResults: StepResultSummary[];\n output: unknown;\n durationMs: number;\n}\n\n/**\n * Simplified step result for tool output.\n */\nexport interface StepResultSummary {\n stepId: string;\n status: 'success' | 'failed' | 'skipped';\n durationMs: number;\n error?: string;\n}\n\n/**\n * Dry run validation result.\n */\nexport interface DryRunResult {\n valid: boolean;\n workflowName: string;\n stepCount: number;\n inputsProvided: string[];\n inputsRequired: string[];\n inputsMissing: string[];\n validationErrors: string[];\n}\n\n/**\n * Dependencies required by the run_workflow tool.\n */\nexport interface RunWorkflowDeps {\n workflowEngine: IWorkflowEngine;\n logger?: ILogger;\n /** Optional rate limiter for throttling tool calls */\n rateLimiter?: RateLimiter;\n}\n\n/**\n * Check if a template identifier is a file path.\n * @param template - Template identifier\n * @returns True if it's a file path\n */\nfunction isFilePath(template: string): boolean {\n return (\n template.includes('/') ||\n template.includes('\\\\') ||\n template.endsWith('.yaml') ||\n template.endsWith('.yml')\n );\n}\n\n/**\n * Convert StepResult to StepResultSummary for tool output.\n * @param result - Full step result\n * @returns Simplified summary\n */\nfunction toStepResultSummary(result: StepResult): StepResultSummary {\n const summary: StepResultSummary = {\n stepId: result.stepId,\n status: result.status,\n durationMs: result.durationMs,\n };\n if (result.error !== undefined) {\n summary.error = result.error;\n }\n return summary;\n}\n\n/**\n * Validate workflow inputs against definitions.\n * @param workflow - Workflow definition\n * @param inputs - Provided inputs\n * @returns Validation result\n */\nfunction validateWorkflowInputs(\n workflow: WorkflowDefinition,\n inputs: Record<string, unknown>\n): { valid: boolean; missing: string[]; errors: string[] } {\n const missing: string[] = [];\n const errors: string[] = [];\n const providedKeys = new Set(Object.keys(inputs));\n\n for (const inputDef of workflow.inputs) {\n const isRequired = inputDef.required === true;\n const hasValue = providedKeys.has(inputDef.name);\n const hasDefault = inputDef.default !== undefined;\n\n if (isRequired && !hasValue && !hasDefault) {\n missing.push(inputDef.name);\n }\n\n // Type validation for provided values\n if (hasValue) {\n const value = inputs[inputDef.name];\n const typeError = validateInputType(inputDef.name, value, inputDef.type);\n if (typeError !== null) {\n errors.push(typeError);\n }\n }\n }\n\n return {\n valid: missing.length === 0 && errors.length === 0,\n missing,\n errors,\n };\n}\n\n/**\n * Type validator functions for each expected type.\n */\nconst TYPE_VALIDATORS: Record<string, (value: unknown) => boolean> = {\n string: (v): boolean => typeof v === 'string',\n number: (v): boolean => typeof v === 'number',\n boolean: (v): boolean => typeof v === 'boolean',\n object: (v): boolean => v !== null && typeof v === 'object' && !Array.isArray(v),\n array: (v): boolean => Array.isArray(v),\n};\n\n/**\n * Get the actual type description for error messages.\n */\nfunction getActualTypeDescription(value: unknown): string {\n if (Array.isArray(value)) return 'array';\n if (value === null) return 'null';\n return typeof value;\n}\n\n/**\n * Validate that an input value matches its expected type.\n * @param name - Input name\n * @param value - Input value\n * @param expectedType - Expected type\n * @returns Error message or null if valid\n */\nfunction validateInputType(name: string, value: unknown, expectedType: string): string | null {\n const validator = TYPE_VALIDATORS[expectedType];\n if (validator === undefined || validator(value)) {\n return null;\n }\n return `Input '${name}' expected ${expectedType}, got ${getActualTypeDescription(value)}`;\n}\n\n/**\n * Load workflow definition from template name or path.\n * @param deps - Tool dependencies\n * @param template - Template name or path\n * @returns Result with workflow definition\n */\nasync function loadWorkflow(\n deps: RunWorkflowDeps,\n template: string\n): Promise<Result<WorkflowDefinition, WorkflowError | ParseError>> {\n const { workflowEngine, logger } = deps;\n\n if (isFilePath(template)) {\n logger?.debug('Loading workflow from file', { path: template });\n const result = await workflowEngine.loadTemplate(template);\n if (!result.ok) {\n return {\n ok: false,\n error: new WorkflowError(`Failed to load template from path: ${result.error.message}`, {\n context: { path: template },\n }),\n };\n }\n return result;\n }\n\n // Load from built-in templates\n logger?.debug('Looking up built-in template', { name: template });\n const templates = await workflowEngine.listTemplates();\n const found = templates.find((t) => t.name === template);\n\n if (found === undefined) {\n const availableNames = templates.map((t) => t.name).join(', ');\n return {\n ok: false,\n error: new WorkflowError(`Template not found: ${template}`, {\n context: {\n template,\n availableTemplates: availableNames,\n },\n }),\n };\n }\n\n // Load the template by path\n const result = await workflowEngine.loadTemplate(found.path);\n if (!result.ok) {\n return {\n ok: false,\n error: new WorkflowError(`Failed to load template: ${result.error.message}`, {\n context: { template, path: found.path },\n }),\n };\n }\n\n return result;\n}\n\n/**\n * Execute dry run validation.\n * @param workflow - Workflow definition\n * @param inputs - Provided inputs\n * @returns Dry run result\n */\nfunction executeDryRun(\n workflow: WorkflowDefinition,\n inputs: Record<string, unknown>\n): DryRunResult {\n const validation = validateWorkflowInputs(workflow, inputs);\n const requiredInputs = workflow.inputs.filter((i) => i.required === true).map((i) => i.name);\n const providedInputs = Object.keys(inputs);\n\n return {\n valid: validation.valid,\n workflowName: workflow.name,\n stepCount: workflow.steps.length,\n inputsProvided: providedInputs,\n inputsRequired: requiredInputs,\n inputsMissing: validation.missing,\n validationErrors: validation.errors,\n };\n}\n\n/**\n * Execute workflow and convert result.\n * @param deps - Tool dependencies\n * @param workflow - Workflow definition\n * @param inputs - Workflow inputs\n * @returns Tool result\n */\nasync function executeWorkflow(\n deps: RunWorkflowDeps,\n workflow: WorkflowDefinition,\n inputs: Record<string, unknown>\n): Promise<Result<WorkflowToolResult, WorkflowError>> {\n const { workflowEngine, logger } = deps;\n\n logger?.info('Executing workflow', {\n workflowName: workflow.name,\n inputCount: Object.keys(inputs).length,\n });\n\n const startTime = Date.now();\n const result = await workflowEngine.execute(workflow, inputs);\n\n if (!result.ok) {\n logger?.error('Workflow execution failed', result.error, {\n workflowName: workflow.name,\n });\n\n return {\n ok: false,\n error: result.error,\n };\n }\n\n const workflowResult = result.value;\n\n logger?.info('Workflow completed', {\n workflowName: workflow.name,\n durationMs: Date.now() - startTime,\n stepCount: workflowResult.stepResults.length,\n });\n\n return {\n ok: true,\n value: {\n executionId: workflowResult.executionId,\n workflowName: workflowResult.workflowName,\n status: 'completed',\n stepResults: workflowResult.stepResults.map(toStepResultSummary),\n output: workflowResult.output,\n durationMs: workflowResult.totalDurationMs,\n },\n };\n}\n\n/** MCP tool response type */\ntype ToolResponse = { content: Array<{ type: 'text'; text: string }>; isError?: boolean };\n\n/** Create a successful JSON response */\nfunction successResponse(data: unknown): ToolResponse {\n return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }] };\n}\n\n/** Create an error response */\nfunction errorResponse(message: string): ToolResponse {\n return { isError: true, content: [{ type: 'text', text: message }] };\n}\n\n/** Create a failed workflow result */\nfunction createFailedResult(workflowName: string, errorMessage: string): ToolResponse {\n const result = {\n executionId: 'unknown',\n workflowName,\n status: 'failed',\n stepResults: [],\n output: null,\n durationMs: 0,\n error: errorMessage,\n };\n return { isError: true, content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };\n}\n\n/** Format validation errors into a message */\nfunction formatValidationErrors(validation: { missing: string[]; errors: string[] }): string {\n const messages = [\n ...validation.missing.map((m) => `Missing required input: ${m}`),\n ...validation.errors,\n ];\n return messages.join('\\n');\n}\n\n/**\n * Handle tool execution and format response.\n * @param deps - Tool dependencies\n * @param args - Validated tool arguments\n * @returns MCP tool response\n */\nasync function handleRunWorkflow(\n deps: RunWorkflowDeps,\n args: RunWorkflowInput\n): Promise<ToolResponse> {\n const { template, inputs, dryRun } = args;\n deps.logger?.debug('run_workflow called', { template, dryRun, inputKeys: Object.keys(inputs) });\n\n const loadResult = await loadWorkflow(deps, template);\n if (!loadResult.ok) {\n return errorResponse(loadResult.error.message);\n }\n\n const workflow = loadResult.value;\n\n if (dryRun) {\n return successResponse(executeDryRun(workflow, inputs));\n }\n\n const validation = validateWorkflowInputs(workflow, inputs);\n if (!validation.valid) {\n return errorResponse(formatValidationErrors(validation));\n }\n\n const executeResult = await executeWorkflow(deps, workflow, inputs);\n if (!executeResult.ok) {\n return createFailedResult(workflow.name, executeResult.error.message);\n }\n\n return successResponse(executeResult.value);\n}\n\n/** Input schema for registerTool */\nconst toolInputSchema = {\n template: z.string().min(1).describe('Workflow template name (e.g., code-review) or file path'),\n inputs: z.record(z.unknown()).describe('Workflow inputs as key-value pairs'),\n dryRun: z.boolean().optional().default(false).describe('Validate workflow without executing'),\n};\n\n/**\n * Register the run_workflow tool with an MCP server.\n * @param server - MCP server instance\n * @param deps - Tool dependencies\n */\nexport function registerRunWorkflowTool(server: McpServer, deps: RunWorkflowDeps): void {\n server.registerTool(\n 'run_workflow',\n {\n description:\n 'Execute a workflow template with provided inputs, supporting built-in templates and custom paths',\n inputSchema: toolInputSchema,\n },\n async (args) => {\n // Rate limiting check\n if (deps.rateLimiter !== undefined) {\n const acquired = deps.rateLimiter.tryAcquire();\n if (!acquired) {\n const state = deps.rateLimiter.getState();\n return {\n isError: true,\n content: [\n {\n type: 'text' as const,\n text: `Rate limit exceeded. Try again in ${String(state.nextTokenMs)}ms.`,\n },\n ],\n };\n }\n }\n\n const validated = RunWorkflowInputSchema.safeParse(args);\n if (!validated.success) {\n const errorMessage = validated.error.errors\n .map((e) => `${e.path.join('.')}: ${e.message}`)\n .join(', ');\n return {\n isError: true,\n content: [{ type: 'text' as const, text: `Validation error: ${errorMessage}` }],\n };\n }\n return handleRunWorkflow(deps, validated.data);\n }\n );\n}\n","/**\n * @nexus-agents/mcp - Orchestrate Tool\n *\n * MCP tool for task orchestration using TechLead agent.\n * Analyzes tasks, coordinates with experts, and returns structured results.\n *\n * (Source: MCP Protocol 2025-11-25)\n */\n\nimport { z } from 'zod';\nimport type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport type { Result, ILogger, Task, TaskContext } from '../../core/index.js';\nimport { ok, err, AgentError, createLogger } from '../../core/index.js';\nimport type { RateLimiter } from '../middleware/rate-limiter.js';\nimport type { ExecutionPlan, Expert } from '../../agents/index.js';\nimport { TechLead } from '../../agents/index.js';\n\n/**\n * Input schema for the orchestrate tool.\n * Validated using Zod at the tool boundary.\n */\nexport const OrchestrateInputSchema = z.object({\n task: z.string().min(1).describe('Task description to orchestrate'),\n context: z.record(z.unknown()).optional().describe('Additional context for the task'),\n maxIterations: z\n .number()\n .min(1)\n .max(50)\n .optional()\n .default(10)\n .describe('Maximum iterations for orchestration'),\n});\n\nexport type OrchestrateInput = z.infer<typeof OrchestrateInputSchema>;\n\n/**\n * Output schema for the orchestrate tool response.\n */\nexport const OrchestrateOutputSchema = z.object({\n taskId: z.string().describe('Unique execution ID'),\n analysis: z.object({\n taskId: z.string(),\n complexity: z.number().min(1).max(10),\n taskType: z.string(),\n requirements: z.array(z.string()),\n risks: z.array(z.string()),\n needsDecomposition: z.boolean(),\n approach: z.string(),\n estimatedEffort: z.number(),\n }),\n result: z.unknown().describe('Final execution result'),\n stepsCompleted: z.number().describe('Number of steps completed'),\n metadata: z.object({\n durationMs: z.number(),\n tokensUsed: z.number(),\n expertsUsed: z.array(z.string()),\n }),\n});\n\nexport type OrchestrateOutput = z.infer<typeof OrchestrateOutputSchema>;\n\n/**\n * Interface for TechLead operations.\n * Allows for dependency injection and mocking.\n */\nexport interface ITechLead {\n execute(\n task: Task\n ): Promise<Result<{ taskId: string; output: unknown; metadata: unknown }, AgentError>>;\n}\n\n/**\n * Interface for expert factory operations.\n */\nexport interface IExpertFactory {\n createBuiltIn(type: string): Result<Expert, AgentError>;\n}\n\n/**\n * Dependencies for the orchestrate tool.\n */\nexport interface OrchestrateDeps {\n techLead?: ITechLead;\n expertFactory?: IExpertFactory;\n logger?: ILogger;\n /** Optional rate limiter for throttling tool calls */\n rateLimiter?: RateLimiter;\n}\n\n/**\n * Error class for orchestration-specific errors.\n */\nexport class OrchestrationError extends AgentError {\n constructor(message: string, options?: { cause?: Error; context?: Record<string, unknown> }) {\n super(message, options);\n this.name = 'OrchestrationError';\n }\n}\n\n/**\n * Generates a unique task ID for tracking execution.\n */\nfunction generateTaskId(): string {\n const timestamp = Date.now().toString(36);\n const random = Math.random().toString(36).substring(2, 8);\n return `orch-${timestamp}-${random}`;\n}\n\n/**\n * Creates a Task object from orchestrate input.\n */\nfunction createTaskFromInput(input: OrchestrateInput, taskId: string): Task {\n const context: TaskContext = {};\n\n // Only set metadata if context is defined\n if (input.context !== undefined) {\n context.metadata = input.context;\n }\n\n return {\n id: taskId,\n description: input.task,\n context,\n constraints: {\n maxTokens: input.maxIterations * 1000,\n },\n };\n}\n\n/**\n * Extracts expert names from execution plan assignments.\n */\nfunction extractExpertsUsed(output: unknown): string[] {\n if (typeof output !== 'object' || output === null) {\n return [];\n }\n\n const plan = output as Partial<ExecutionPlan>;\n if (!Array.isArray(plan.assignments)) {\n return [];\n }\n\n return plan.assignments.map((a) => a.expertRole);\n}\n\n/**\n * Builds the orchestration output from execution result.\n */\nfunction buildOutput(\n taskId: string,\n result: { output: unknown; metadata: unknown },\n durationMs: number\n): OrchestrateOutput {\n const output = result.output as Partial<ExecutionPlan>;\n const metadata = result.metadata as { tokensUsed?: number } | undefined;\n\n const analysis = output.analysis ?? {\n taskId,\n complexity: 5,\n taskType: 'general',\n requirements: [],\n risks: [],\n needsDecomposition: false,\n approach: 'Direct execution',\n estimatedEffort: 1,\n };\n\n const stepsCompleted = Array.isArray(output.subtasks) ? output.subtasks.length : 0;\n const expertsUsed = extractExpertsUsed(result.output);\n\n return {\n taskId,\n analysis: {\n taskId: analysis.taskId,\n complexity: analysis.complexity,\n taskType: analysis.taskType,\n requirements: analysis.requirements,\n risks: analysis.risks,\n needsDecomposition: analysis.needsDecomposition,\n approach: analysis.approach,\n estimatedEffort: analysis.estimatedEffort,\n },\n result: result.output,\n stepsCompleted,\n metadata: {\n durationMs,\n tokensUsed: metadata?.tokensUsed ?? 0,\n expertsUsed,\n },\n };\n}\n\n/**\n * Executes the orchestration logic.\n */\nasync function executeOrchestration(\n input: OrchestrateInput,\n deps: OrchestrateDeps\n): Promise<Result<OrchestrateOutput, OrchestrationError>> {\n const logger = deps.logger ?? createLogger({ tool: 'orchestrate' });\n const techLead = deps.techLead ?? new TechLead({ logger });\n const taskId = generateTaskId();\n const startTime = Date.now();\n\n logger.info('Starting orchestration', { taskId, taskLength: input.task.length });\n\n const task = createTaskFromInput(input, taskId);\n\n try {\n const result = await techLead.execute(task);\n\n if (!result.ok) {\n logger.error('Orchestration failed', result.error, { taskId });\n return err(\n new OrchestrationError(`Task execution failed: ${result.error.message}`, {\n cause: result.error,\n context: { taskId },\n })\n );\n }\n\n const durationMs = Date.now() - startTime;\n const output = buildOutput(taskId, result.value, durationMs);\n\n logger.info('Orchestration completed', {\n taskId,\n durationMs,\n stepsCompleted: output.stepsCompleted,\n });\n\n return ok(output);\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error';\n const cause = error instanceof Error ? error : undefined;\n logger.error('Orchestration exception', cause, { taskId });\n\n const errorOptions: { cause?: Error; context: Record<string, unknown> } = {\n context: { taskId },\n };\n if (cause !== undefined) {\n errorOptions.cause = cause;\n }\n\n return err(\n new OrchestrationError(`Orchestration failed unexpectedly: ${message}`, errorOptions)\n );\n }\n}\n\n/**\n * Tool input schema definition.\n */\nconst TOOL_SCHEMA = {\n task: z.string().min(1).describe('Task description to orchestrate'),\n context: z.record(z.unknown()).optional().describe('Additional context for the task'),\n maxIterations: z\n .number()\n .min(1)\n .max(50)\n .optional()\n .describe('Maximum iterations for orchestration (default: 10)'),\n};\n\n/**\n * Creates a tool handler for the orchestrate tool.\n */\nfunction createOrchestrateHandler(deps: OrchestrateDeps, logger: ILogger) {\n return async (args: unknown) => {\n // Rate limiting check\n if (deps.rateLimiter !== undefined) {\n const acquired = deps.rateLimiter.tryAcquire();\n if (!acquired) {\n const state = deps.rateLimiter.getState();\n return {\n isError: true,\n content: [\n {\n type: 'text' as const,\n text: `Rate limit exceeded. Try again in ${String(state.nextTokenMs)}ms.`,\n },\n ],\n };\n }\n }\n\n const validated = OrchestrateInputSchema.safeParse(args);\n if (!validated.success) {\n const errorMessage = validated.error.issues\n .map((issue) => `${issue.path.join('.')}: ${issue.message}`)\n .join('; ');\n logger.warn('Invalid orchestrate input', { errors: validated.error.issues });\n return {\n isError: true,\n content: [{ type: 'text' as const, text: `Validation error: ${errorMessage}` }],\n };\n }\n\n const result = await executeOrchestration(validated.data, deps);\n if (!result.ok) {\n return {\n isError: true,\n content: [{ type: 'text' as const, text: `Orchestration error: ${result.error.message}` }],\n };\n }\n\n return { content: [{ type: 'text' as const, text: JSON.stringify(result.value, null, 2) }] };\n };\n}\n\n/**\n * Registers the orchestrate tool with the MCP server.\n *\n * @param server - MCP server instance\n * @param deps - Dependencies including TechLead and optional expert factory\n */\nexport function registerOrchestrateTool(server: McpServer, deps: OrchestrateDeps): void {\n const logger = deps.logger ?? createLogger({ tool: 'orchestrate' });\n const description =\n 'Orchestrate a task by analyzing it, breaking it into subtasks if needed, and coordinating expert agents';\n\n // eslint-disable-next-line @typescript-eslint/no-deprecated -- Consistent with other tools in codebase\n server.tool('orchestrate', description, TOOL_SCHEMA, createOrchestrateHandler(deps, logger));\n logger.info('Registered orchestrate tool');\n}\n\n/**\n * Creates a mock TechLead for testing purposes.\n * Uses heuristic analysis without model adapter.\n */\nexport function createMockTechLead(): ITechLead {\n return {\n execute(task: Task) {\n // Simulate basic analysis without model\n const complexity = Math.min(10, Math.max(1, Math.floor(task.description.length / 50)));\n const needsDecomposition = complexity > 5;\n\n const analysis = {\n taskId: task.id,\n complexity,\n taskType: 'implementation',\n requirements: ['Basic implementation required'],\n risks: [],\n needsDecomposition,\n approach: 'Standard execution',\n estimatedEffort: complexity,\n };\n\n const output: Partial<ExecutionPlan> = {\n taskId: task.id,\n analysis,\n subtasks: [],\n assignments: [],\n parallelGroups: [],\n estimatedDuration: complexity * 10,\n };\n\n return Promise.resolve(\n ok({\n taskId: task.id,\n output,\n metadata: {\n durationMs: 100,\n tokensUsed: 0,\n toolsUsed: [],\n model: 'mock-tech-lead',\n },\n })\n );\n },\n };\n}\n","/**\n * @nexus-agents/mcp - Tools\n *\n * MCP tool implementations for the Nexus Agents server.\n *\n * (Source: MCP Protocol 2025-11-25)\n */\n\nimport type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\n\nimport type { ILogger } from '../../core/index.js';\n\nimport { createMcpLogger } from '../middleware/logging.js';\nimport { RateLimiter, createDefaultRateLimiter } from '../middleware/rate-limiter.js';\n\n// Tool implementations\nexport {\n registerCreateExpertTool,\n createDefaultDeps,\n getAvailableRoles,\n getCapabilitiesForRole,\n CreateExpertInputSchema,\n type CreateExpertInput,\n type CreateExpertDeps,\n type CreateExpertResponse,\n type IExpertFactory,\n} from './create-expert.js';\n\nexport {\n registerRunWorkflowTool,\n RunWorkflowInputSchema,\n type RunWorkflowDeps,\n type RunWorkflowInput,\n type WorkflowToolResult,\n type StepResultSummary,\n type DryRunResult,\n} from './run-workflow.js';\n\nexport {\n registerOrchestrateTool,\n createMockTechLead,\n OrchestrateInputSchema,\n OrchestrateOutputSchema,\n OrchestrationError,\n type OrchestrateInput,\n type OrchestrateOutput,\n type OrchestrateDeps,\n type ITechLead,\n type IExpertFactory as IOrchestrateExpertFactory,\n} from './orchestrate.js';\n\n/**\n * Options for tool registration.\n */\nexport interface ToolRegistrationOptions {\n /** Logger instance for tool operations */\n readonly logger?: ILogger;\n /** Rate limiter for tool calls */\n readonly rateLimiter?: RateLimiter;\n}\n\n/**\n * Result of tool registration.\n */\nexport interface ToolRegistrationResult {\n /** Names of registered tools */\n readonly tools: readonly string[];\n /** Logger used for tool operations */\n readonly logger: ILogger;\n /** Rate limiter used for tool calls */\n readonly rateLimiter: RateLimiter;\n}\n\n/**\n * Registers all Nexus Agents tools on the MCP server.\n *\n * This function provides infrastructure and logging for tool registration.\n * Individual tools require their specific dependencies and should be\n * registered using their respective register functions:\n *\n * - `registerOrchestrateTool(server, { techLead, logger, rateLimiter })`\n * - `registerCreateExpertTool(server, { expertFactory, expertRegistry, logger, rateLimiter })`\n * - `registerRunWorkflowTool(server, { workflowEngine, logger, rateLimiter })`\n *\n * **Important:** Pass the `rateLimiter` from the result to each tool's register\n * function to enable rate limiting. Without it, tools will not be rate limited.\n *\n * @param server - The MCP server to register tools on\n * @param options - Optional configuration for tool registration\n * @returns Registration result with shared resources (logger, rate limiter)\n *\n * @example\n * ```typescript\n * const serverResult = createServer();\n * if (serverResult.ok) {\n * const { server, logger } = serverResult.value;\n * const { rateLimiter } = registerTools(server, { logger });\n *\n * // Register individual tools with their dependencies and rate limiter\n * registerOrchestrateTool(server, { techLead, logger, rateLimiter });\n * registerCreateExpertTool(server, { expertFactory, expertRegistry, logger, rateLimiter });\n * registerRunWorkflowTool(server, { workflowEngine, logger, rateLimiter });\n * }\n * ```\n */\nexport function registerTools(\n server: McpServer,\n options?: ToolRegistrationOptions\n): ToolRegistrationResult {\n const logger = options?.logger ?? createMcpLogger({ component: 'tools' });\n const rateLimiter = options?.rateLimiter ?? createDefaultRateLimiter('mcp-tools', logger);\n\n logger.info('Tool registration infrastructure initialized');\n\n // Note: Individual tools are registered separately with their specific dependencies.\n // The available tools are:\n // - orchestrate: Task orchestration with TechLead agent\n // - create_expert: Dynamic expert agent creation\n // - run_workflow: Workflow template execution\n //\n // Use the exported register functions with appropriate dependencies.\n\n // Reference server to avoid unused parameter warning\n void server;\n\n return {\n tools: ['orchestrate', 'create_expert', 'run_workflow'],\n logger,\n rateLimiter,\n };\n}\n\n/**\n * MCP tool content types.\n */\nexport interface TextContent {\n readonly type: 'text';\n readonly text: string;\n}\n\n/**\n * MCP tool result.\n */\nexport interface ToolResult {\n readonly content: readonly TextContent[];\n readonly isError?: boolean;\n}\n\n/**\n * Creates a successful tool result.\n *\n * @param text - The result text\n * @returns A ToolResult with the text content\n */\nexport function toolSuccess(text: string): ToolResult {\n return {\n content: [{ type: 'text', text }],\n };\n}\n\n/**\n * Creates an error tool result.\n *\n * @param message - The error message\n * @returns A ToolResult with isError set to true\n */\nexport function toolError(message: string): ToolResult {\n return {\n isError: true,\n content: [{ type: 'text', text: message }],\n };\n}\n","/**\n * @nexus-agents/mcp\n *\n * MCP server implementation for Nexus Agents.\n * Provides tools for orchestrating multi-agent workflows.\n *\n * (Source: MCP Protocol 2025-11-25)\n */\n\nexport const VERSION = '0.0.1';\n\n// Server\nexport {\n createServer,\n startStdioServer,\n connectTransport,\n closeServer,\n type ServerConfig,\n type ServerInstance,\n type ServerError,\n} from './server.js';\n\n// Middleware\nexport {\n // Validation\n validateToolInput,\n createValidator,\n isZodError,\n // Rate limiting\n RateLimiter,\n createDefaultRateLimiter,\n type RateLimiterConfig,\n type RateLimiterState,\n // Logging\n createMcpLogger,\n createToolLogger,\n logToolStart,\n logToolSuccess,\n logToolError,\n createTimer,\n withLogging,\n type McpLogContext,\n} from './middleware/index.js';\n\n// Tools\nexport {\n // Tool registration\n registerTools,\n toolSuccess,\n toolError,\n type ToolRegistrationOptions,\n type ToolRegistrationResult,\n type TextContent,\n type ToolResult,\n // create_expert tool\n registerCreateExpertTool,\n createDefaultDeps,\n getAvailableRoles,\n getCapabilitiesForRole,\n CreateExpertInputSchema,\n type CreateExpertInput,\n type CreateExpertDeps,\n type CreateExpertResponse,\n type IExpertFactory,\n // run_workflow tool\n registerRunWorkflowTool,\n RunWorkflowInputSchema,\n type RunWorkflowDeps,\n type RunWorkflowInput,\n type WorkflowToolResult,\n type StepResultSummary,\n type DryRunResult,\n // orchestrate tool\n registerOrchestrateTool,\n createMockTechLead,\n OrchestrateInputSchema,\n OrchestrateOutputSchema,\n OrchestrationError,\n type OrchestrateInput,\n type OrchestrateOutput,\n type OrchestrateDeps,\n type ITechLead,\n type IOrchestrateExpertFactory,\n} from './tools/index.js';\n","/* eslint-disable max-lines */\n/**\n * nexus-agents\n *\n * Multi-agent orchestration framework with MCP server.\n * Provides tools for orchestrating AI agents for complex software tasks.\n *\n * @example\n * ```typescript\n * import { createServer, startStdioServer, TechLead, createClaudeAdapter } from 'nexus-agents';\n *\n * // Start MCP server\n * const result = await startStdioServer({ name: 'my-server', version: '1.0.0' });\n *\n * // Or use programmatically\n * const adapter = createClaudeAdapter({ model: 'claude-sonnet-4-20250514' });\n * const techLead = new TechLead({ adapter });\n * ```\n */\n\nexport const VERSION = '1.0.0';\n\n// ============================================================================\n// Core - Types, Result<T,E>, errors, and logger\n// ============================================================================\nexport {\n // Result pattern\n type Result,\n ok,\n err,\n isOk,\n isErr,\n map,\n mapErr,\n unwrap,\n unwrapOr,\n // Error hierarchy\n ErrorCode,\n NexusError,\n ValidationError,\n ConfigError,\n ModelError,\n AgentError,\n WorkflowError,\n SecurityError,\n TimeoutError,\n RateLimitError,\n type SerializedError,\n type NexusErrorOptions,\n // Logger\n createLogger,\n logger,\n sanitize,\n type LogLevel,\n type LogContext,\n type LogEntry,\n type ILogger,\n} from './core/index.js';\n\n// Re-export all types from core\nexport type {\n // Agent types\n IAgent,\n AgentState,\n AgentRole,\n AgentMessage,\n AgentMessageType,\n AgentResponse,\n // Task types\n Task,\n TaskContext,\n TaskResult,\n // Model types\n IModelAdapter,\n Message,\n ContentBlock,\n MessageRole,\n CompletionRequest,\n CompletionResponse,\n TokenUsage,\n StopReason,\n StreamChunk,\n ToolDefinition,\n // Workflow types\n IWorkflowEngine,\n WorkflowDefinition,\n WorkflowStep,\n WorkflowTemplate,\n InputDefinition,\n StepResult,\n} from './core/index.js';\n\n// Re-export enums/constants from core\nexport { ModelCapability, AgentCapability, ParseError } from './core/index.js';\n\n// ============================================================================\n// Config - Configuration schemas\n// ============================================================================\nexport {\n AppConfigSchema,\n ModelConfigSchema,\n ModelTiersSchema,\n ProviderConfigSchema,\n ExpertConfigSchema as ConfigExpertConfigSchema,\n ExpertDefinitionSchema as ConfigExpertDefinitionSchema,\n WorkflowConfigSchema,\n SecurityConfigSchema,\n LoggingConfigSchema,\n defaultConfig,\n type AppConfig,\n type ModelConfig,\n type ModelTiers,\n type ProviderConfig,\n type ExpertConfig as ConfigExpertConfig,\n type ExpertDefinition as ConfigExpertDefinition,\n type WorkflowConfig,\n type SecurityConfig,\n type LoggingConfig,\n} from './config/index.js';\n\n// ============================================================================\n// Adapters - Model adapters (Claude, OpenAI, Gemini, Ollama)\n// ============================================================================\nexport {\n // Adapter factory\n AdapterFactory,\n AdapterConfigSchema,\n defaultFactory,\n type AdapterConfig,\n type AdapterCreator,\n type RegisterOptions as AdapterRegisterOptions,\n // Rate limiting\n RateLimiter as AdapterRateLimiter,\n createRateLimiter,\n type RateLimiterConfig as AdapterRateLimiterConfig,\n type RateLimitExceeded,\n // Retry logic\n withRetry,\n withRetryWrapper,\n isRetryableError,\n calculateDelay,\n sleep,\n RetryExhaustedError,\n DEFAULT_RETRY_CONFIG,\n type RetryConfig,\n type RetryAttemptInfo,\n type WithRetryOptions,\n // Base adapter\n BaseAdapter,\n AdapterModelError,\n type BaseAdapterConfig,\n // Streaming utilities\n StreamController,\n StreamError,\n StreamCancelledError,\n createStream,\n collectStream,\n transformStream,\n mergeStreams,\n takeUntil,\n take,\n skip,\n filterStream,\n withTimeout,\n bufferStream,\n concatStreams,\n fromArray,\n tapStream,\n reduceStream,\n type StreamState,\n type CreateStreamOptions,\n // Claude adapter\n ClaudeAdapter,\n createClaudeAdapter,\n CLAUDE_MODELS,\n CLAUDE_MODEL_ALIASES,\n type ClaudeAdapterConfig,\n // OpenAI adapter\n OpenAIAdapter,\n createOpenAIAdapter,\n OPENAI_MODELS,\n OPENAI_MODEL_ALIASES,\n type OpenAIAdapterConfig,\n // Ollama adapter\n OllamaAdapter,\n createOllamaAdapter,\n OLLAMA_MODELS,\n type OllamaAdapterConfig,\n // Gemini adapter\n GeminiAdapter,\n createGeminiAdapter,\n GEMINI_MODELS,\n GEMINI_MODEL_ALIASES,\n type GeminiAdapterConfig,\n} from './adapters/index.js';\n\n// ============================================================================\n// Agents - Agent framework, TechLead, Experts\n// ============================================================================\nexport {\n // Base agent\n BaseAgent,\n TaskSchema,\n AgentMessageSchema,\n BaseAgentOptionsSchema,\n type BaseAgentOptions,\n // Simple agent\n SimpleAgent,\n // TechLead\n TechLead,\n createTechLead,\n type ExecutionPlan,\n // TechLead types\n type SubTask,\n type TaskAnalysis,\n type ExpertAssignment,\n type SynthesizedResult,\n type ResultSummary,\n type Conflict,\n type TechLeadOptions,\n type SubtaskPriority,\n type SubtaskStatus,\n SubTaskSchema,\n TaskAnalysisSchema,\n ExpertAssignmentSchema,\n SynthesizedResultSchema,\n TechLeadOptionsSchema,\n SubtaskPrioritySchema,\n SubtaskStatusSchema,\n EXPERT_CAPABILITIES,\n TASK_TYPE_EXPERTS,\n // State machine\n AgentStateMachine,\n createStateMachine,\n type StateTransitionEvent,\n type StateTransition,\n type StateChangeCallback,\n type TransitionErrorCallback,\n type StateMachineOptions,\n // Context management\n ContextManager,\n ContentPriority,\n DEFAULT_BUDGET,\n ContextBudgetSchema,\n ContextManagerConfigSchema,\n type ContextBudget,\n type ContextItem,\n type ContextManagerConfig,\n type ContextStats,\n // Context pruning\n ContextPruner,\n PruningStrategy,\n ContextPrunerConfigSchema,\n type ContextPrunerConfig,\n type PruneOptions,\n type PruneResult,\n // Expert system\n type ExpertConfig,\n type ModelPreference,\n type BuiltInExpertType,\n ExpertConfigSchema,\n ModelPreferenceSchema,\n BuiltInExpertTypeSchema,\n BUILT_IN_EXPERTS,\n EXPERT_TYPE_TO_ROLE,\n validateExpertConfig,\n safeValidateExpertConfig,\n ExpertFactory,\n Expert,\n FactoryError,\n type CreateExpertOptions,\n ExpertRegistry,\n RegistryError,\n getExpertRegistry,\n type RegisterOptions as ExpertRegisterOptions,\n type QueryOptions,\n type RegistryStats,\n // Task analysis\n analyzeTask,\n TaskDomain,\n TaskComplexity,\n AnalysisError,\n TaskAnalysisResultSchema,\n type TaskAnalysisResult,\n // Expert selection\n selectExperts,\n quickSelect,\n createDefaultRegistry,\n SelectionError,\n ExpertCollaborationPattern,\n type ExpertCollaborationPatternType,\n ScoreBreakdownSchema,\n ExpertMatchSchema,\n SelectionResultSchema,\n SelectionOptionsSchema,\n type ExpertDefinition,\n type ExpertMatch,\n type ScoreBreakdown,\n type SelectionResult,\n type SelectionOptions,\n type SelectionExpertRegistry,\n // Expert types\n type ExpertDomain,\n type ExpertOptions,\n type ExpertOutput,\n type CodeAnalysisResult,\n type CodeChange,\n type SecurityAnalysisResult,\n type Vulnerability,\n type ComplianceStatus,\n type ArchitectureAnalysisResult,\n type ArchitecturePattern,\n type ArchitectureDecision,\n type SystemComponent,\n type TestingAnalysisResult,\n type GeneratedTest,\n type CoverageMetrics,\n type TestQuality,\n type DocumentationResult,\n type DocumentationSection,\n type ApiDocumentation,\n type ApiEndpoint,\n type ApiType,\n ExpertDomainSchema,\n ExpertOptionsSchema,\n ExpertOutputSchema,\n VulnerabilitySeveritySchema,\n VulnerabilitySchema,\n CodeChangeSchema,\n GeneratedTestSchema,\n CoverageMetricsSchema,\n EXPERT_DEFAULT_TEMPERATURES,\n EXPERT_DEFAULT_CAPABILITIES,\n // Specialized experts\n CodeExpert,\n createCodeExpert,\n type CodeExpertOptions,\n SecurityExpert,\n createSecurityExpert,\n type SecurityExpertOptions,\n type SecurityFocusArea,\n ArchitectureExpert,\n createArchitectureExpert,\n type ArchitectureExpertOptions,\n type ArchitectureStyle,\n type QualityAttribute,\n TestingExpert,\n createTestingExpert,\n type TestingExpertOptions,\n DocumentationExpert,\n createDocumentationExpert,\n type DocumentationExpertOptions,\n // Collaboration\n type CollaborationPattern,\n type SessionStatus,\n type VoteDecision,\n type CollaborationConfig,\n type ExpertParticipation,\n type CollaborationMessage,\n type TaskAssignmentMessage,\n type ResultSubmissionMessage,\n type ReviewRequestMessage,\n type ReviewResponseMessage,\n type FeedbackMessage,\n type VoteMessage,\n type StatusUpdateMessage,\n type SessionState,\n type CollaborationResult,\n type ExpertResultSummary,\n type AggregatedResult,\n type ResultConflict,\n type AggregationMetadata,\n CollaborationPatternSchema,\n SessionStatusSchema,\n VoteDecisionSchema,\n CollaborationConfigSchema,\n ExpertParticipationSchema,\n VoteMessageSchema,\n ReviewResponseMessageSchema,\n DEFAULT_TIMEOUTS,\n DEFAULT_MAX_RETRIES,\n MIN_EXPERTS_FOR_PATTERN,\n CollaborationSession,\n createCollaborationSession,\n type CollaborationSessionOptions,\n type SessionEvent,\n SequentialProtocol,\n ParallelProtocol,\n ReviewProtocol,\n ConsensusProtocol,\n ProtocolFactory,\n createProtocolFactory,\n type ICollaborationProtocol,\n type ProtocolOptions,\n ResultAggregator,\n createResultAggregator,\n aggregateResults,\n type AggregationStrategy,\n type AggregatorOptions,\n type AggregatorInput,\n type ExpertResult,\n type ConflictResolver,\n type QualityScorer,\n} from './agents/index.js';\n\n// ============================================================================\n// Workflows - Workflow engine with parallel execution\n// ============================================================================\nexport {\n // Workflow parser\n parseWorkflowYaml,\n parseWorkflowJson,\n loadWorkflowFile,\n validateWorkflow,\n // Workflow types\n InputTypeSchema,\n formatZodErrors,\n type InputType,\n type InputDefinitionInput,\n type InputDefinitionOutput,\n type AgentRoleType,\n type WorkflowStepInput,\n type WorkflowStepOutput,\n type WorkflowDefinitionInput,\n type WorkflowDefinitionOutput,\n type ValidationIssue,\n // Strict schemas\n StrictInputDefinitionSchema,\n StrictAgentRoleSchema,\n StrictWorkflowStepSchema,\n StrictWorkflowDefinitionSchema,\n // Dependency graph\n DependencyGraph,\n buildDependencyGraph,\n validateDependencyGraph,\n getTopologicalOrder,\n // Task queue\n TaskQueue,\n createTaskQueue,\n // Execution planner\n createExecutionPlan,\n validateWorkflowDependencies,\n getExecutionOrder,\n type ExecutionPhase,\n type ExecutionPlan as WorkflowExecutionPlan,\n // Parallel executor\n executeParallel,\n withRetries,\n allSucceeded,\n getFailedSteps,\n type ParallelOptions,\n type ExecutionContext,\n type StepExecutor,\n // Template types\n type TemplateCategory,\n type TemplateMetadata,\n type ITemplateRegistry,\n InputDefinitionSchema,\n AgentRoleSchema,\n WorkflowStepSchema,\n WorkflowDefinitionSchema,\n TemplateCategorySchema,\n TemplateMetadataSchema,\n BUILT_IN_TEMPLATES,\n TEMPLATE_CATEGORIES,\n TEMPLATE_KEYWORDS,\n // Template loader\n getBuiltInTemplatesPath,\n parseTemplateContent,\n loadTemplateFile,\n loadTemplatesFromDirectory,\n getBuiltInTemplates,\n getBuiltInTemplatesWithMetadata,\n type ParsedTemplate,\n // Template registry\n createTemplateRegistry,\n createIsolatedRegistry,\n resetRegistry,\n TemplateRegistry,\n // Execution context\n createExecutionContext,\n storeStepResult,\n getStepResult,\n setVariable,\n getVariable,\n getCompletedSteps,\n isStepCompleted,\n areStepsCompleted,\n getExecutionDuration,\n cancelExecution,\n isCancelled,\n snapshotContext,\n validateRequiredInputs,\n WorkflowInputsSchema,\n type WorkflowExecutionContext,\n type CreateExecutionContextOptions,\n // Expression resolver\n parseExpression,\n resolveExpression,\n resolveInput,\n resolveStringExpressions,\n containsExpressions,\n validateExpressions,\n extractExpressions,\n getReferencedSteps,\n type ExpressionType,\n type ParsedExpression,\n type ResolveResult,\n // Step executor\n AgentStepExecutor,\n createAgentStepExecutor,\n ExpertFactoryAdapter,\n type IExpertFactory as WorkflowExpertFactory,\n type StepExecutorDeps,\n type StepExecutionOptions,\n} from './workflows/index.js';\n\n// ============================================================================\n// MCP - MCP server implementation\n// ============================================================================\nexport {\n // Server\n createServer,\n startStdioServer,\n connectTransport,\n closeServer,\n type ServerConfig,\n type ServerInstance,\n type ServerError,\n // Middleware\n validateToolInput,\n createValidator,\n isZodError,\n RateLimiter as McpRateLimiter,\n createDefaultRateLimiter,\n type RateLimiterConfig as McpRateLimiterConfig,\n type RateLimiterState,\n createMcpLogger,\n createToolLogger,\n logToolStart,\n logToolSuccess,\n logToolError,\n createTimer,\n withLogging,\n type McpLogContext,\n // Tools\n registerTools,\n toolSuccess,\n toolError,\n type ToolRegistrationOptions,\n type ToolRegistrationResult,\n type TextContent,\n type ToolResult,\n // create_expert tool\n registerCreateExpertTool,\n createDefaultDeps,\n getAvailableRoles,\n getCapabilitiesForRole,\n CreateExpertInputSchema,\n type CreateExpertInput,\n type CreateExpertDeps,\n type CreateExpertResponse,\n type IExpertFactory as McpExpertFactory,\n // run_workflow tool\n registerRunWorkflowTool,\n RunWorkflowInputSchema,\n type RunWorkflowDeps,\n type RunWorkflowInput,\n type WorkflowToolResult,\n type StepResultSummary,\n type DryRunResult,\n // orchestrate tool\n registerOrchestrateTool,\n createMockTechLead,\n OrchestrateInputSchema,\n OrchestrateOutputSchema,\n OrchestrationError,\n type OrchestrateInput,\n type OrchestrateOutput,\n type OrchestrateDeps,\n type ITechLead,\n type IOrchestrateExpertFactory,\n} from './mcp/index.js';\n"],"mappings":";AAsBO,SAAS,GAAM,OAA4B;AAChD,SAAO,EAAE,IAAI,MAAM,MAAM;AAC3B;AAQO,SAAS,IAAO,OAA4B;AACjD,SAAO,EAAE,IAAI,OAAO,MAAM;AAC5B;AASO,SAAS,KACd,QACoD;AACpD,SAAO,OAAO;AAChB;AASO,SAAS,MACd,QACqD;AACrD,SAAO,CAAC,OAAO;AACjB;AAWO,SAAS,IAAa,QAAsB,IAAmC;AACpF,MAAI,OAAO,IAAI;AACb,WAAO,GAAG,GAAG,OAAO,KAAK,CAAC;AAAA,EAC5B;AACA,SAAO;AACT;AAWO,SAAS,OAAgB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AA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAUM,IAAM,kBAAkF;AAAA,EAC7F,MAAM;AAAA,IACJ,SAAS;AAAA,MACP;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,IACA,WAAW;AAAA,MACT;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAAA,EACA,UAAU;AAAA,IACR,SAAS;AAAA,MACP;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,IACA,WAAW;AAAA,MACT;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAAA,EACA,cAAc;AAAA,IACZ,SAAS;AAAA,MACP;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,IACA,WAAW;AAAA,MACT;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAAA,EACA,eAAe;AAAA,IACb,SAAS;AAAA,MACP;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,IACA,WAAW;AAAA,MACT;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAAA,EACA,SAAS;AAAA,IACP,SAAS;AAAA,MACP;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,M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,UACb;AAAA,UACA,UAAU;AAAA,YACR,YAAY;AAAA,YACZ,YAAY;AAAA,YACZ,WAAW,CAAC;AAAA,YACZ,OAAO;AAAA,UACT;AAAA,QACF,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF;AACF;;;ACzQO,SAAS,cACd,QACA,SACwB;AACxB,QAAMC,UAAS,SAAS,UAAU,gBAAgB,EAAE,WAAW,QAAQ,CAAC;AACxE,QAAM,cAAc,SAAS,eAAe,yBAAyB,aAAaA,OAAM;AAExF,EAAAA,QAAO,KAAK,8CAA8C;AAW1D,OAAK;AAEL,SAAO;AAAA,IACL,OAAO,CAAC,eAAe,iBAAiB,cAAc;AAAA,IACtD,QAAAA;AAAA,IACA;AAAA,EACF;AACF;AAwBO,SAAS,YAAY,MAA0B;AACpD,SAAO;AAAA,IACL,SAAS,CAAC,EAAE,MAAM,QAAQ,KAAK,CAAC;AAAA,EAClC;AACF;AAQO,SAAS,UAAU,SAA6B;AACrD,SAAO;AAAA,IACL,SAAS;AAAA,IACT,SAAS,CAAC,EAAE,MAAM,QAAQ,MAAM,QAAQ,CAAC;AAAA,EAC3C;AACF;;;AClKO,IAAM,UAAU;;;ACWhB,IAAMC,WAAU;","names":["z","z","resolve","resolve","resolve","resolve","DEFAULT_MAX_TOKENS","resolveModelId","getModelCapabilities","mapStopReason","mapMessage","mapTool","resolveModelId","getModelCapabilities","DEFAULT_MAX_TOKENS","mapMessage","mapTool","mapStopReason","DEFAULT_MAX_TOKENS","mapStopReason","mapMessage","mapTool","getModelCapabilities","DEFAULT_MAX_TOKENS","mapStopReason","resolveModelId","getModelCapabilities","resolveModelId","getModelCapabilities","DEFAULT_MAX_TOKENS","mapStopReason","z","resolve","z","z","z","CHARS_PER_TOKEN","z","z","z","generateHeuristicRecommendations","extractJsonFromText","buildBaseOptions","generateHeuristicRecommendations","generateHeuristicRecommendations","buildBaseOptions","generateHeuristicRecommendations","extractJsonFromText","generateHeuristicRecommendations","buildBaseOptions","generateHeuristicRecommendations","extractJsonFromText","z","ExpertConfigSchema","DEFAULT_MAX_TOKENS","ExpertConfigSchema","z","z","z","z","z","sleep","resolve","sleep","z","AgentRoleSchema","path","resolve","buildDependencyGraph","DEFAULT_OPTIONS","resolve","z","InputDefinitionSchema","AgentRoleSchema","WorkflowStepSchema","WorkflowDefinitionSchema","readFile","stat","extname","resolve","sep","validatePath","resolve","sep","WorkflowDefinitionSchema","readFile","extname","extractKeywords","stat","z","z","path","sleep","resolve","logger","path","RateLimiter","logger","logger","z","z","logger","z","z","logger","result","z","z","logger","logger","VERSION"]}
|