// Planu — Agent Spec Adapter
// SPEC-016a: Generates specialized agent spec content when type is "agent".
// Criteria 1, 11, 12.
// See agent-spec-adapter-b.ts for: generateAgentContract, generateMemoryContract,
//   generateInterAgentContract, buildAgentHuSection (criteria 16, 17, 18).
export { generateAgentContract, generateMemoryContract, generateInterAgentContract, buildAgentHuSection, } from './agent-spec-adapter-b.js';
// === Beginner output (criterion 11) ===
/**
 * Generate a step-by-step beginner guide for an agent spec.
 */
export function generateBeginnerAgentGuide(title, description) {
    const lines = [
        `## Step-by-Step Guide: ${title}`,
        '',
        '### What this agent does',
        description,
        '',
        '### Step 1: Define the goal',
        'Write a single sentence describing what the agent accomplishes.',
        '',
        '### Step 2: Identify triggers',
        'List events that start the agent: user message, scheduled task, webhook, etc.',
        '',
        '### Step 3: Choose tools',
        'Pick tools the agent can call: web search, database, email, calendar, etc.',
        '',
        '### Step 4: Define outputs',
        'Decide what the agent returns: text, JSON, action taken, file, notification.',
        '',
        '### Step 5: Handle errors',
        'Plan what happens when a tool fails or the agent gets confused.',
        '',
        '### Step 6: Set limits',
        'Configure max iterations to prevent infinite loops.',
        '',
        '> Tip: Start simple — one tool, one output. Add complexity once the basic flow works.',
    ];
    return lines.join('\n');
}
// === Expert spec generation (criterion 12) ===
/**
 * Generate a complete expert agent spec with system prompt, tool definitions,
 * RAG pipeline notes, and evaluation criteria.
 */
export function generateExpertAgentSpec(title, description, knowledge) {
    const lang = knowledge?.language ?? 'TypeScript';
    const framework = knowledge?.framework ?? 'unknown';
    const lines = [
        `## Expert Agent Spec: ${title}`,
        '',
        '### System Prompt Template',
        '```',
        `You are ${title}, a specialized AI agent.`,
        `Your mission: ${description}`,
        '',
        'Operating constraints:',
        '- Only call tools when you have sufficient context',
        '- Verify tool outputs before acting on them',
        '- Escalate to human when confidence < 0.7',
        '- Never exceed MAX_ITERATIONS tool calls',
        '```',
        '',
        '### Tool Definitions',
        '```json',
        JSON.stringify([
            {
                name: 'primary_tool',
                description: `Main tool for ${title}`,
                input_schema: {
                    type: 'object',
                    properties: { query: { type: 'string', description: 'Input query' } },
                    required: ['query'],
                },
            },
        ], null, 2),
        '```',
        '',
        '### RAG Pipeline',
        `Language: ${lang} | Framework: ${framework}`,
        '',
        '1. **Ingest**: Load knowledge sources into vector store',
        '2. **Embed**: Convert documents to embeddings (text-embedding-3-small or claude)',
        '3. **Retrieve**: Semantic search with top-k=5, cosine similarity',
        '4. **Augment**: Inject retrieved context into system prompt',
        '5. **Generate**: LLM generates grounded response',
        '',
        '### Evaluation Criteria',
        '- **Accuracy**: Ground truth comparison on test cases (target > 90%)',
        '- **Faithfulness**: Response grounded in retrieved context (target > 95%)',
        '- **Latency**: P95 < 3s for tool calls, < 10s for full response',
        '- **Safety**: Zero harmful outputs on adversarial test suite',
        '- **Cost**: < $0.01 per request at P50',
    ];
    return lines.join('\n');
}
// === Agent spec content generation (criterion 1) ===
export function buildDefaultAgentTools(description) {
    const lower = description.toLowerCase();
    const tools = [];
    if (lower.includes('search') || lower.includes('web') || lower.includes('research')) {
        tools.push({
            name: 'web_search',
            description: 'Search the web for current information',
            inputSchema: { query: { type: 'string' }, maxResults: { type: 'number' } },
            outputSchema: { results: { type: 'array' } },
            sideEffects: [],
        });
    }
    if (lower.includes('email') || lower.includes('notify') || lower.includes('alert')) {
        tools.push({
            name: 'send_email',
            description: 'Send email notification',
            inputSchema: {
                to: { type: 'string' },
                subject: { type: 'string' },
                body: { type: 'string' },
            },
            outputSchema: { messageId: { type: 'string' }, sent: { type: 'boolean' } },
            sideEffects: ['network-call', 'external-service'],
        });
    }
    if (lower.includes('database') || lower.includes('data') || lower.includes('record')) {
        tools.push({
            name: 'query_database',
            description: 'Query the application database',
            inputSchema: { query: { type: 'string' }, params: { type: 'array' } },
            outputSchema: { rows: { type: 'array' }, count: { type: 'number' } },
            sideEffects: ['database-read'],
        });
    }
    // Always add a fallback tool
    if (tools.length === 0) {
        tools.push({
            name: 'execute_task',
            description: 'Execute the primary task',
            inputSchema: { input: { type: 'string' } },
            outputSchema: { result: { type: 'string' }, status: { type: 'string' } },
            sideEffects: [],
        });
    }
    return tools;
}
export function generateAgentSpec(title, description) {
    const tools = buildDefaultAgentTools(description);
    return {
        goal: `${title}: ${description}`,
        triggers: ['user-message', 'scheduled-task', 'webhook-event'],
        tools,
        knowledgeSources: ['project-documentation', 'knowledge-base'],
        decisionRules: [
            'Use tools only when user intent is clear',
            'Verify tool outputs before proceeding',
            'Escalate to human when confidence < 0.7',
            'Stop after max_iterations to prevent infinite loops',
        ],
        outputs: ['structured-response', 'action-confirmation', 'error-report'],
        errorHandling: 'On tool failure: retry once with backoff, then return graceful error to user. Log all failures.',
    };
}
// === Agent Constitution (criterion 9) ===
export function generateAgentConstitution() {
    return {
        accuracy: [
            'Always verify information from at least 2 sources before presenting as fact',
            'Acknowledge uncertainty explicitly — use "I believe" or "According to..."',
            'Never hallucinate tool outputs — use actual tool call results only',
            'Cross-validate numerical data before presenting',
        ],
        safety: [
            'Never execute destructive operations without explicit user confirmation',
            'Refuse requests that could harm users or third parties',
            'Implement rate limiting: max 10 tool calls per conversation turn',
            'Sanitize all tool inputs to prevent injection attacks',
        ],
        privacy: [
            'Never log personally identifiable information (PII)',
            'Do not retain conversation history beyond configured retention period',
            'Mask sensitive fields (passwords, API keys, SSNs) in all outputs',
            'Comply with user data deletion requests immediately',
        ],
        escalation: [
            'Escalate when confidence < 0.7 on critical decisions',
            'Escalate when tool has failed more than once on the same request',
            'Escalate when user expresses frustration or confusion',
            'Always provide escalation context: what was attempted, what failed, why',
        ],
    };
}
//# sourceMappingURL=agent-spec-adapter.js.map