// Planu — Agent Documentation Generator
// SPEC-016a criterion 10: generate agent usage manual, configuration guide, troubleshooting.
/**
 * Detect if the project is an AI agent project.
 */
function isAgentProject(knowledge) {
    // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
    const stack = (knowledge.stack ?? []).map((s) => s.toLowerCase());
    const agentSignals = [
        '@anthropic-ai/sdk',
        '@mastra/core',
        'langgraph',
        'crewai',
        'autogen',
        'langchain',
        '@ai-sdk/anthropic',
        'mem0',
    ];
    return agentSignals.some((sig) => stack.some((s) => s.includes(sig)));
}
/**
 * Generate agent usage manual.
 */
function buildUsageManual(knowledge, specs) {
    const agentSpecs = specs.filter((s) => s.type === 'agent' || s.title.toLowerCase().includes('agent'));
    const specList = agentSpecs.map((s) => `- **${s.id}**: ${s.title}`).join('\n');
    const installCmd = knowledge.packageManager === 'pnpm'
        ? 'pnpm install'
        : knowledge.packageManager === 'yarn'
            ? 'yarn install'
            : 'npm install';
    return [
        '# Agent Usage Manual',
        '',
        `**Framework:** ${knowledge.framework ?? 'Custom'} | **Language:** ${knowledge.language}`,
        '',
        '## Overview',
        'This manual describes how to interact with the AI agent system.',
        '',
        '## Available Agents',
        specList || '- No agent specs defined yet. Run `create_spec` with `type: "agent"`.',
        '',
        '## How to Start an Agent',
        '```bash',
        '# 1. Set required environment variables',
        'export ANTHROPIC_API_KEY="your-key-here"',
        '',
        '# 2. Install dependencies',
        installCmd,
        '',
        '# 3. Run the agent',
        knowledge.buildCommand ?? 'npm start',
        '```',
        '',
        '## Input Format',
        'Send a message to the agent in the following format:',
        '```json',
        JSON.stringify({ message: 'Your task description', context: {}, priority: 'medium' }, null, 2),
        '```',
        '',
        '## Output Format',
        '```json',
        JSON.stringify({
            response: 'Agent response',
            toolsUsed: ['tool_name'],
            iterationsUsed: 3,
            confidence: 0.95,
        }, null, 2),
        '```',
        '',
        '## Limitations',
        '- Max iterations per request: 10 (configurable)',
        '- Max tokens per context window: depends on model',
        '- Rate limits: 60 requests/minute (default)',
        '- Cost: billed per token — monitor with LangSmith/Langfuse',
    ].join('\n');
}
/**
 * Generate agent configuration guide.
 */
function buildConfigurationGuide(knowledge) {
    return [
        '# Agent Configuration Guide',
        '',
        '## Environment Variables',
        '',
        '| Variable | Required | Description | Example |',
        '|----------|----------|-------------|---------|',
        '| `ANTHROPIC_API_KEY` | Yes | Anthropic API key | `sk-ant-...` |',
        '| `AGENT_MAX_ITERATIONS` | No | Max tool calls per turn (default: 10) | `10` |',
        '| `AGENT_TEMPERATURE` | No | LLM temperature (default: 0 for determinism) | `0` |',
        '| `AGENT_LOG_LEVEL` | No | Logging level | `info` |',
        '| `VECTOR_STORE_URL` | Conditional | Required for RAG/memory | `https://...` |',
        '| `MEM0_API_KEY` | Conditional | Required for mem0 memory | `m0-...` |',
        '',
        '## Model Selection',
        '',
        `Current framework: \`${knowledge.framework ?? 'custom'}\``,
        '',
        '| Use case | Recommended model |',
        '|----------|-------------------|',
        '| Complex reasoning, planning | `claude-opus-4-5` |',
        '| General tasks, tool use | `claude-sonnet-4-5` |',
        '| Simple tasks, high volume | `claude-haiku-4-5` |',
        '',
        '## Memory Configuration',
        '',
        '```typescript',
        '// In-context memory (simple, no external dependencies)',
        'const agent = { memory: "in-context", maxTurns: 20 };',
        '',
        '// Vector store memory (for large knowledge bases)',
        'const agent = { memory: "vector-store", vectorStoreUrl: process.env.VECTOR_STORE_URL };',
        '',
        '// mem0 persistent memory (cross-session)',
        'const agent = { memory: "mem0", userId: "user-123" };',
        '```',
        '',
        '## Tool Registration',
        '',
        '```typescript',
        '// Register tools before agent run',
        'const tools = [',
        '  { name: "search", description: "Search the web", execute: searchFn },',
        '  { name: "database", description: "Query database", execute: dbFn },',
        '];',
        '```',
    ].join('\n');
}
/**
 * Generate agent troubleshooting guide.
 */
function buildTroubleshootingGuide() {
    return [
        '# Agent Troubleshooting Guide',
        '',
        '## Common Issues',
        '',
        '### 1. Agent loops infinitely',
        '**Symptom:** Agent keeps calling tools without completing the task.',
        '**Solution:**',
        '- Check `AGENT_MAX_ITERATIONS` is set (default: 10)',
        '- Look for circular tool call patterns in logs',
        '- Add explicit termination condition to agent instructions',
        '',
        '### 2. Hallucinated tool parameters',
        '**Symptom:** Tool calls fail with parameter validation errors.',
        '**Solution:**',
        '- Add JSON Schema validation to all tool inputs',
        '- Use structured output / strict mode when available',
        '- Log rejected tool calls for pattern analysis',
        '',
        '### 3. Context window exceeded',
        '**Symptom:** ContextLengthExceededError or silent truncation.',
        '**Solution:**',
        '- Enable token counting: check usage in response metadata',
        '- Implement conversation summarization after N turns',
        '- Move knowledge to vector store instead of in-context',
        '',
        '### 4. Rate limit errors',
        '**Symptom:** 429 Too Many Requests from API.',
        '**Solution:**',
        '- Implement exponential backoff: 100ms * 2^attempt',
        '- Add token budget per user session',
        '- Consider batching requests or using async queue',
        '',
        '### 5. Prompt injection detected',
        '**Symptom:** Agent behavior changes unexpectedly after tool call.',
        '**Solution:**',
        '- Sanitize tool outputs before adding to context',
        '- Filter for instruction-like patterns in tool returns',
        '- Use separate system/user message boundaries',
        '',
        '### 6. High costs',
        '**Symptom:** Unexpected token consumption or billing.',
        '**Solution:**',
        '- Enable LangSmith/Langfuse tracing to audit token usage',
        '- Set hard cost cap per request (max_tokens parameter)',
        '- Use Haiku for simple tasks, Sonnet for moderate, Opus for complex',
        '',
        '## Debugging Commands',
        '```bash',
        '# View agent run logs',
        'AGENT_LOG_LEVEL=debug npm start 2>&1 | grep "tool_call"',
        '',
        '# Count tokens in a request',
        'npx ts-node scripts/count-tokens.ts "Your input message"',
        '',
        '# Test prompt injection defense',
        'npm test -- --grep "prompt injection"',
        '```',
        '',
        '## Support',
        '- Open an issue with: agent logs, input message, expected vs actual output',
        '- Include model name and version, tool list, and iteration count',
    ].join('\n');
}
// === Public API ===
/**
 * Generate agent documentation if the project is an AI agent project.
 * Criterion 10: generates usage manual, configuration guide, troubleshooting.
 */
export function generateAgentDocumentation(knowledge, specs) {
    if (!isAgentProject(knowledge)) {
        return null;
    }
    return {
        usageManual: buildUsageManual(knowledge, specs),
        configurationGuide: buildConfigurationGuide(knowledge),
        troubleshootingGuide: buildTroubleshootingGuide(),
    };
}
//# sourceMappingURL=agent-docs-generator.js.map