/** * Orchestrator prompt for the generate_solutions tool * * This module defines the system prompt for the GLM 4.7 orchestrator that * generates multiple distinct approach prompts for a given task. Each approach * is then executed by a separate sub-agent. */ import type { LLMClient, ChatMessage } from "../../llm/client.js"; import type { ConcurrencyPool, ProgressCallback } from "../../llm/pool.js"; /** * A sub-agent prompt generated by the orchestrator * * Contains everything needed to spawn a sub-agent for one approach. */ export interface SubAgentPrompt { /** Unique identifier for this approach (1-indexed) */ id: number; /** High-level description of the approach (e.g., "Token bucket algorithm") */ approach: string; /** Full prompt to send to the sub-agent for implementation */ prompt: string; } /** * Successful result from a sub-agent execution * * Contains the complete implementation produced by a sub-agent. */ export interface SubAgentResult { /** Unique identifier for this approach (matches SubAgentPrompt.id) */ id: number; /** High-level description of the approach (from SubAgentPrompt.approach) */ approach: string; /** The complete solution/implementation generated by the sub-agent */ solution: string; } /** * Failure result from a sub-agent execution * * Contains error information when a sub-agent fails. */ export interface SubAgentFailure { /** Unique identifier for this approach (matches SubAgentPrompt.id) */ id: number; /** High-level description of the approach (from SubAgentPrompt.approach) */ approach: string; /** Error message describing what went wrong */ error: string; } /** * Combined results from executing all sub-agents */ export interface SubAgentExecutionResults { /** Successfully completed sub-agent results */ successes: SubAgentResult[]; /** Failed sub-agent executions */ failures: SubAgentFailure[]; } /** * Error thrown when parsing orchestrator response fails */ export declare class OrchestratorParseError extends Error { /** The raw response that failed to parse */ readonly rawResponse: string; /** Specific parsing issue encountered */ readonly parseIssue: string; constructor(message: string, rawResponse: string, parseIssue: string); } /** * System prompt for the GLM 4.7 orchestrator * * This prompt instructs the LLM to: * 1. Analyze the given task and codebase context * 2. Generate N distinct implementation approaches * 3. Return a structured JSON array of sub-agent prompts * * The orchestrator focuses on diversity of approaches rather than * implementing solutions itself. */ export declare const ORCHESTRATOR_SYSTEM_PROMPT = "You are an expert software architect tasked with designing multiple distinct approaches to solve a coding task.\n\n## Your Role\n\nYou are an orchestrator that generates implementation plans. You do NOT implement solutions yourself. Instead, you create detailed prompts for sub-agents who will implement each approach.\n\n## Instructions\n\nGiven a task description and codebase context, you must:\n\n1. **Analyze the Task**: Understand the requirements, constraints, and goals.\n\n2. **Consider the Context**: Use the provided codebase information to understand:\n - Existing patterns and conventions\n - Available dependencies and utilities\n - Code structure and organization\n\n3. **Generate Distinct Approaches**: Create exactly N different approaches where:\n - Each approach uses a fundamentally different algorithm, pattern, or strategy\n - Approaches should vary in trade-offs (e.g., simplicity vs performance, memory vs speed)\n - Avoid minor variations of the same approach\n - Consider both conventional and creative solutions\n\n4. **Create Sub-Agent Prompts**: For each approach, write a detailed prompt that:\n - Clearly explains the approach to take\n - Specifies implementation requirements\n - References relevant codebase context\n - Includes any necessary constraints or guidelines\n - Is self-contained (the sub-agent only sees this prompt)\n\n## Output Format\n\nYou MUST respond with ONLY a valid JSON array. No markdown, no explanation, no code blocks.\n\nEach element in the array must have exactly these fields:\n- \"id\": A unique integer starting from 1\n- \"approach\": A brief name/description of the approach (max 50 characters)\n- \"prompt\": The complete prompt for the sub-agent to implement this approach\n\nExample output structure:\n[\n {\n \"id\": 1,\n \"approach\": \"Token bucket algorithm\",\n \"prompt\": \"Implement a rate limiter using the token bucket algorithm. The rate limiter should...\\n\\nContext:\\n- The codebase uses TypeScript...\\n\\nRequirements:\\n1. Create a TokenBucket class...\\n2. ...\"\n },\n {\n \"id\": 2,\n \"approach\": \"Sliding window counter\",\n \"prompt\": \"Implement a rate limiter using the sliding window counter pattern...\\n\\nContext:\\n...\"\n }\n]\n\n## Guidelines for Good Approaches\n\n1. **Diversity**: Each approach should be meaningfully different:\n - Different algorithms (e.g., BFS vs DFS, iterative vs recursive)\n - Different data structures (e.g., array vs tree vs hash map)\n - Different architectural patterns (e.g., event-driven vs polling)\n - Different libraries or built-in features\n\n2. **Practicality**: All approaches should be implementable and reasonable:\n - Consider the complexity budget\n - Account for the existing codebase structure\n - Ensure compatibility with stated requirements\n\n3. **Trade-off Awareness**: Document the trade-offs in each approach:\n - Performance characteristics\n - Complexity and maintainability\n - Resource usage\n\n## Guidelines for Good Sub-Agent Prompts\n\n1. **Self-Contained**: The sub-agent has no context beyond the prompt you write.\n Include all necessary information about:\n - The task requirements\n - The specific approach to use\n - Relevant codebase context\n - Any constraints or requirements\n\n2. **Clear Structure**: Use a consistent format:\n - Start with the high-level goal\n - Explain the specific approach\n - Provide implementation details\n - List requirements and constraints\n - Include relevant code snippets or file paths from context\n\n3. **Actionable**: The prompt should give the sub-agent clear direction:\n - What to create or modify\n - How to structure the solution\n - What to avoid\n - Success criteria\n\nRemember: Output ONLY the JSON array. No other text."; /** * System prompt for GLM 4.7 sub-agents * * This prompt instructs sub-agents to: * 1. Implement the solution according to the specified approach * 2. Generate complete, working code * 3. Follow the codebase conventions and requirements * * Each sub-agent receives a self-contained prompt from the orchestrator * and produces a complete implementation. */ export declare const SUB_AGENT_SYSTEM_PROMPT = "You are an expert software engineer tasked with implementing a specific solution approach.\n\n## Your Role\n\nYou are an implementation agent. You receive a detailed prompt describing:\n- The task to implement\n- The specific approach to use\n- Relevant codebase context\n- Requirements and constraints\n\nYour job is to produce a complete, working implementation.\n\n## Instructions\n\n1. **Understand the Approach**: Carefully read the approach description and implement exactly that solution. Do not deviate to a different algorithm or pattern.\n\n2. **Follow the Context**: Use the provided codebase information to:\n - Match existing code style and conventions\n - Use available utilities and dependencies\n - Follow the project's file structure patterns\n - Maintain consistency with existing code\n\n3. **Produce Complete Code**: Your output should be:\n - Fully functional and runnable\n - Well-structured with appropriate functions/classes\n - Properly typed (if TypeScript)\n - Reasonably documented with comments for complex logic\n\n4. **Handle Edge Cases**: Consider and handle:\n - Invalid inputs\n - Boundary conditions\n - Error scenarios\n - Empty or null cases\n\n## Output Format\n\nProvide your implementation as complete, ready-to-use code.\n\nStructure your response as follows:\n1. Start with a brief explanation (2-3 sentences) of your implementation\n2. Provide the complete code implementation\n3. End with any important notes about usage or limitations\n\nUse proper markdown code blocks with language specifiers for all code.\n\n## Quality Standards\n\nYour implementation should:\n- Be correct and handle the specified requirements\n- Be readable and maintainable\n- Follow best practices for the language/framework\n- Include appropriate error handling\n- Be efficient for the expected use case\n\nFocus on producing a high-quality, working solution that follows the specified approach."; /** * Build the user message for the orchestrator * * @param task - The task or problem description to solve * @param context - Context about the codebase structure and relevant files * @param count - Number of approaches to generate * @returns Formatted user message string */ declare function buildUserMessage(task: string, context: string, count: number): string; /** * Create the messages array for the orchestrator LLM call * * @param task - The task or problem description to solve * @param context - Context about the codebase structure and relevant files * @param count - Number of approaches to generate (default: 3) * @returns Array of ChatMessage ready for the LLM client */ export declare function createOrchestratorPrompt(task: string, context: string, count?: number): ChatMessage[]; /** * Extract JSON array from LLM response * * Handles various response formats: * - Raw JSON array * - JSON wrapped in markdown code blocks * - JSON with leading/trailing whitespace * * @param response - Raw LLM response string * @returns Extracted JSON string */ declare function extractJSON(response: string): string; /** * Validate a single sub-agent prompt object * * @param obj - Object to validate * @param index - Index in array for error reporting * @returns Validated SubAgentPrompt * @throws Error if validation fails */ declare function validateSubAgentPrompt(obj: unknown, index: number): SubAgentPrompt; /** * Parse and validate orchestrator response into SubAgentPrompt array * * @param response - Raw response string from the orchestrator LLM * @returns Array of validated SubAgentPrompt objects * @throws OrchestratorParseError if parsing or validation fails */ export declare function parseOrchestratorResponse(response: string): SubAgentPrompt[]; /** * Execute a single sub-agent to generate an implementation * * @param client - LLM client for API calls * @param model - Model ID to use for generation * @param subAgentPrompt - The prompt for this sub-agent * @returns Promise resolving to the sub-agent's response content */ declare function executeSubAgent(client: LLMClient, model: string, subAgentPrompt: SubAgentPrompt): Promise; /** * Execute all sub-agents in parallel using the concurrency pool * * Fans out to GLM 4.7 for each sub-agent prompt, with controlled concurrency * to avoid overwhelming the API. Individual failures do not abort the batch; * instead, results are collected into successes and failures arrays. * * @param client - LLM client for API calls * @param model - Model ID to use for generation * @param pool - Concurrency pool for rate limiting * @param subAgentPrompts - Array of sub-agent prompts to execute * @param onProgress - Optional progress callback * @returns Promise resolving to combined results (successes and failures) */ export declare function executeSubAgents(client: LLMClient, model: string, pool: ConcurrencyPool, subAgentPrompts: SubAgentPrompt[], onProgress?: ProgressCallback): Promise; /** * Input options for the generateSolutions function */ export interface GenerateSolutionsOptions { /** The task or problem description to solve */ task: string; /** Number of solution approaches to generate (default: 3) */ count?: number; /** Context about the codebase structure and relevant files */ codebase_context: string; /** If true, return planned approaches without executing sub-agents */ dry_run?: boolean; /** Progress callback for reporting generation progress */ onProgress?: ProgressCallback; } /** * A single approach (used in dry_run mode before execution) */ export interface ApproachPlan { /** Unique identifier for this approach (1-indexed) */ id: number; /** High-level description of the approach */ approach: string; /** The prompt that would be sent to the sub-agent (only in dry_run) */ prompt: string; } /** * A completed solution approach */ export interface ApproachSolution { /** Unique identifier for this approach (1-indexed, converted to string for MCP) */ id: string; /** High-level description of the approach */ approach: string; /** The complete solution generated by the sub-agent */ solution: string; } /** * A failed approach attempt */ export interface ApproachFailure { /** Unique identifier for this approach */ id: string; /** High-level description of the approach */ approach: string; /** Error message describing what went wrong */ error: string; } /** * Output from generateSolutions when dry_run is true */ export interface GenerateSolutionsDryRunOutput { /** True when this is a dry run result */ dry_run: true; /** Planned approaches that would be executed */ approaches: ApproachPlan[]; } /** * Output from generateSolutions when dry_run is false (normal execution) */ export interface GenerateSolutionsExecutionOutput { /** False when this is a full execution result */ dry_run: false; /** Successfully completed solution approaches */ approaches: ApproachSolution[]; /** Failed solution attempts (if any) */ failures?: ApproachFailure[]; } /** * Combined output type for generateSolutions */ export type GenerateSolutionsResult = GenerateSolutionsDryRunOutput | GenerateSolutionsExecutionOutput; /** * Generate multiple solution approaches for a coding task * * This is the main entry point for the generate_solutions tool. It: * 1. Calls the orchestrator LLM to generate distinct approach prompts * 2. If dry_run is true, returns the planned approaches without executing * 3. Otherwise, executes all sub-agents in parallel and collects results * * @param client - LLM client for API calls * @param model - Model ID to use for both orchestrator and sub-agents * @param pool - Concurrency pool for rate limiting sub-agent calls * @param options - Generation options including task, count, context, and dry_run * @returns Promise resolving to approaches (and failures if any) * * @example * ```typescript * // Dry run to preview approaches * const preview = await generateSolutions(client, "glm-4-plus", pool, { * task: "Implement a rate limiter", * count: 3, * codebase_context: "TypeScript project using Express...", * dry_run: true, * }); * console.log(preview.approaches); // Shows planned approaches without executing * * // Full execution * const result = await generateSolutions(client, "glm-4-plus", pool, { * task: "Implement a rate limiter", * count: 3, * codebase_context: "TypeScript project using Express...", * }); * console.log(`${result.approaches.length} succeeded`); * if (result.failures?.length) { * console.log(`${result.failures.length} failed`); * } * ``` */ export declare function generateSolutions(client: LLMClient, model: string, pool: ConcurrencyPool, options: GenerateSolutionsOptions): Promise; export { extractJSON as _extractJSON }; export { validateSubAgentPrompt as _validateSubAgentPrompt }; export { buildUserMessage as _buildUserMessage }; export { executeSubAgent as _executeSubAgent }; //# sourceMappingURL=generate.d.ts.map