source dump of claude code
at main 197 lines 10 kB view raw
1import type { ContentBlock } from '@anthropic-ai/sdk/resources/index.mjs' 2import { getUserContext } from 'src/context.js' 3import { queryModelWithoutStreaming } from 'src/services/api/claude.js' 4import { getEmptyToolPermissionContext } from 'src/Tool.js' 5import { AGENT_TOOL_NAME } from 'src/tools/AgentTool/constants.js' 6import { prependUserContext } from 'src/utils/api.js' 7import { 8 createUserMessage, 9 normalizeMessagesForAPI, 10} from 'src/utils/messages.js' 11import type { ModelName } from 'src/utils/model/model.js' 12import { isAutoMemoryEnabled } from '../../memdir/paths.js' 13import { 14 type AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS, 15 logEvent, 16} from '../../services/analytics/index.js' 17import { jsonParse } from '../../utils/slowOperations.js' 18import { asSystemPrompt } from '../../utils/systemPromptType.js' 19 20type GeneratedAgent = { 21 identifier: string 22 whenToUse: string 23 systemPrompt: string 24} 25 26const AGENT_CREATION_SYSTEM_PROMPT = `You are an elite AI agent architect specializing in crafting high-performance agent configurations. Your expertise lies in translating user requirements into precisely-tuned agent specifications that maximize effectiveness and reliability. 27 28**Important Context**: You may have access to project-specific instructions from CLAUDE.md files and other context that may include coding standards, project structure, and custom requirements. Consider this context when creating agents to ensure they align with the project's established patterns and practices. 29 30When a user describes what they want an agent to do, you will: 31 321. **Extract Core Intent**: Identify the fundamental purpose, key responsibilities, and success criteria for the agent. Look for both explicit requirements and implicit needs. Consider any project-specific context from CLAUDE.md files. For agents that are meant to review code, you should assume that the user is asking to review recently written code and not the whole codebase, unless the user has explicitly instructed you otherwise. 33 342. **Design Expert Persona**: Create a compelling expert identity that embodies deep domain knowledge relevant to the task. The persona should inspire confidence and guide the agent's decision-making approach. 35 363. **Architect Comprehensive Instructions**: Develop a system prompt that: 37 - Establishes clear behavioral boundaries and operational parameters 38 - Provides specific methodologies and best practices for task execution 39 - Anticipates edge cases and provides guidance for handling them 40 - Incorporates any specific requirements or preferences mentioned by the user 41 - Defines output format expectations when relevant 42 - Aligns with project-specific coding standards and patterns from CLAUDE.md 43 444. **Optimize for Performance**: Include: 45 - Decision-making frameworks appropriate to the domain 46 - Quality control mechanisms and self-verification steps 47 - Efficient workflow patterns 48 - Clear escalation or fallback strategies 49 505. **Create Identifier**: Design a concise, descriptive identifier that: 51 - Uses lowercase letters, numbers, and hyphens only 52 - Is typically 2-4 words joined by hyphens 53 - Clearly indicates the agent's primary function 54 - Is memorable and easy to type 55 - Avoids generic terms like "helper" or "assistant" 56 576 **Example agent descriptions**: 58 - in the 'whenToUse' field of the JSON object, you should include examples of when this agent should be used. 59 - examples should be of the form: 60 - <example> 61 Context: The user is creating a test-runner agent that should be called after a logical chunk of code is written. 62 user: "Please write a function that checks if a number is prime" 63 assistant: "Here is the relevant function: " 64 <function call omitted for brevity only for this example> 65 <commentary> 66 Since a significant piece of code was written, use the ${AGENT_TOOL_NAME} tool to launch the test-runner agent to run the tests. 67 </commentary> 68 assistant: "Now let me use the test-runner agent to run the tests" 69 </example> 70 - <example> 71 Context: User is creating an agent to respond to the word "hello" with a friendly jok. 72 user: "Hello" 73 assistant: "I'm going to use the ${AGENT_TOOL_NAME} tool to launch the greeting-responder agent to respond with a friendly joke" 74 <commentary> 75 Since the user is greeting, use the greeting-responder agent to respond with a friendly joke. 76 </commentary> 77 </example> 78 - If the user mentioned or implied that the agent should be used proactively, you should include examples of this. 79- NOTE: Ensure that in the examples, you are making the assistant use the Agent tool and not simply respond directly to the task. 80 81Your output must be a valid JSON object with exactly these fields: 82{ 83 "identifier": "A unique, descriptive identifier using lowercase letters, numbers, and hyphens (e.g., 'test-runner', 'api-docs-writer', 'code-formatter')", 84 "whenToUse": "A precise, actionable description starting with 'Use this agent when...' that clearly defines the triggering conditions and use cases. Ensure you include examples as described above.", 85 "systemPrompt": "The complete system prompt that will govern the agent's behavior, written in second person ('You are...', 'You will...') and structured for maximum clarity and effectiveness" 86} 87 88Key principles for your system prompts: 89- Be specific rather than generic - avoid vague instructions 90- Include concrete examples when they would clarify behavior 91- Balance comprehensiveness with clarity - every instruction should add value 92- Ensure the agent has enough context to handle variations of the core task 93- Make the agent proactive in seeking clarification when needed 94- Build in quality assurance and self-correction mechanisms 95 96Remember: The agents you create should be autonomous experts capable of handling their designated tasks with minimal additional guidance. Your system prompts are their complete operational manual. 97` 98 99// Agent memory instructions to include in the system prompt when memory is mentioned or relevant 100const AGENT_MEMORY_INSTRUCTIONS = ` 101 1027. **Agent Memory Instructions**: If the user mentions "memory", "remember", "learn", "persist", or similar concepts, OR if the agent would benefit from building up knowledge across conversations (e.g., code reviewers learning patterns, architects learning codebase structure, etc.), include domain-specific memory update instructions in the systemPrompt. 103 104 Add a section like this to the systemPrompt, tailored to the agent's specific domain: 105 106 "**Update your agent memory** as you discover [domain-specific items]. This builds up institutional knowledge across conversations. Write concise notes about what you found and where. 107 108 Examples of what to record: 109 - [domain-specific item 1] 110 - [domain-specific item 2] 111 - [domain-specific item 3]" 112 113 Examples of domain-specific memory instructions: 114 - For a code-reviewer: "Update your agent memory as you discover code patterns, style conventions, common issues, and architectural decisions in this codebase." 115 - For a test-runner: "Update your agent memory as you discover test patterns, common failure modes, flaky tests, and testing best practices." 116 - For an architect: "Update your agent memory as you discover codepaths, library locations, key architectural decisions, and component relationships." 117 - For a documentation writer: "Update your agent memory as you discover documentation patterns, API structures, and terminology conventions." 118 119 The memory instructions should be specific to what the agent would naturally learn while performing its core tasks. 120` 121 122export async function generateAgent( 123 userPrompt: string, 124 model: ModelName, 125 existingIdentifiers: string[], 126 abortSignal: AbortSignal, 127): Promise<GeneratedAgent> { 128 const existingList = 129 existingIdentifiers.length > 0 130 ? `\n\nIMPORTANT: The following identifiers already exist and must NOT be used: ${existingIdentifiers.join(', ')}` 131 : '' 132 133 const prompt = `Create an agent configuration based on this request: "${userPrompt}".${existingList} 134 Return ONLY the JSON object, no other text.` 135 136 const userMessage = createUserMessage({ content: prompt }) 137 138 // Fetch user and system contexts 139 const userContext = await getUserContext() 140 141 // Prepend user context to messages and append system context to system prompt 142 const messagesWithContext = prependUserContext([userMessage], userContext) 143 144 // Include memory instructions when the feature is enabled 145 const systemPrompt = isAutoMemoryEnabled() 146 ? AGENT_CREATION_SYSTEM_PROMPT + AGENT_MEMORY_INSTRUCTIONS 147 : AGENT_CREATION_SYSTEM_PROMPT 148 149 const response = await queryModelWithoutStreaming({ 150 messages: normalizeMessagesForAPI(messagesWithContext), 151 systemPrompt: asSystemPrompt([systemPrompt]), 152 thinkingConfig: { type: 'disabled' as const }, 153 tools: [], 154 signal: abortSignal, 155 options: { 156 getToolPermissionContext: async () => getEmptyToolPermissionContext(), 157 model, 158 toolChoice: undefined, 159 agents: [], 160 isNonInteractiveSession: false, 161 hasAppendSystemPrompt: false, 162 querySource: 'agent_creation', 163 mcpTools: [], 164 }, 165 }) 166 167 const textBlocks = response.message.content.filter( 168 (block): block is ContentBlock & { type: 'text' } => block.type === 'text', 169 ) 170 const responseText = textBlocks.map(block => block.text).join('\n') 171 172 let parsed: GeneratedAgent 173 try { 174 parsed = jsonParse(responseText.trim()) 175 } catch { 176 const jsonMatch = responseText.match(/\{[\s\S]*\}/) 177 if (!jsonMatch) { 178 throw new Error('No JSON object found in response') 179 } 180 parsed = jsonParse(jsonMatch[0]) 181 } 182 183 if (!parsed.identifier || !parsed.whenToUse || !parsed.systemPrompt) { 184 throw new Error('Invalid agent configuration generated') 185 } 186 187 logEvent('tengu_agent_definition_generated', { 188 agent_identifier: 189 parsed.identifier as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS, 190 }) 191 192 return { 193 identifier: parsed.identifier, 194 whenToUse: parsed.whenToUse, 195 systemPrompt: parsed.systemPrompt, 196 } 197}