import { z } from 'zod';
import { ClaudeRunner } from '../services/ClaudeRunner.js';
import { storeRun } from '../memory/MemoryFactory.js';
import { getWorkspaceDir } from '../lib/config.js';
import { deleteSessionId } from '../lib/sessions.js';
export const runClaudeSchema = z
    .object({
    prompt: z.string().describe("Le prompt à envoyer à l'agent Claude"),
    sessionId: z.string().optional(),
    agentName: z
        .string()
        .optional()
        .describe("Nom de l'agent (pour logging/monitoring et persistance)"),
    autoResume: z
        .boolean()
        .optional()
        .default(false)
        .describe('Si true (et agentName fourni), reprend automatiquement la dernière conversation de cet agent'),
    model: z.string().optional().describe('Modèle à utiliser (override env.ANTHROPIC_MODEL)'),
    path: z.string().optional().describe('Répertoire de travail'),
    config: z.string().optional().describe('Répertoire racine Overmind'),
    silent: z.boolean().optional().default(false).describe('Mode silencieux'),
    signal: z.custom().optional().describe("AbortSignal pour annuler l'agent"),
})
    .passthrough();
export async function runClaudeAgent(args) {
    const runner = new ClaudeRunner();
    const { prompt, agentName, autoResume, sessionId, model, path: argPath, config: argConfig, silent, signal, } = args;
    const finalPath = argPath || getWorkspaceDir();
    const finalConfig = argConfig || getWorkspaceDir();
    const start = Date.now();
    let result = await runner.runAgent({
        prompt,
        agentName,
        autoResume,
        sessionId,
        model,
        cwd: finalPath,
        configPath: finalConfig,
        silent,
        signal,
    });
    if (result.error?.includes('No conversation found') ||
        result.error?.includes('session') ||
        result.error?.includes('EXIT_CODE_1') ||
        result.error === 'JSON_PARSE_ERROR') {
        if (!silent) {
            console.warn(`[run_claude] Session invalide ou erreur JSON, création nouvelle session...`);
        }
        if (agentName) {
            await deleteSessionId(agentName, finalConfig, 'claude');
        }
        result = await runner.runAgent({
            prompt,
            agentName,
            autoResume: false,
            sessionId: undefined,
            model,
            cwd: finalPath,
            configPath: finalConfig,
            silent,
            signal,
        });
    }
    const durationMs = Date.now() - start;
    // Auto-instrument: record every run in OverMind memory
    try {
        await storeRun({
            runner: 'claude',
            agentName,
            prompt,
            result: result.result,
            error: result.error,
            durationMs,
            success: !result.error,
            sessionId: result.sessionId,
        });
    }
    catch (e) {
        console.error(`[run_claude] ⚠️ Memory store failed: ${e instanceof Error ? e.message : String(e)}`);
    }
    if (result.error?.startsWith('INVALID_AGENT')) {
        return {
            content: [{ type: 'text', text: `❌ Agent '${agentName}' introuvable.` }],
            isError: true,
        };
    }
    if (result.error)
        return {
            content: [{ type: 'text', text: `❌ Erreur Claude: ${result.error}` }],
            isError: true,
        };
    return {
        content: [
            { type: 'text', text: result.result },
            ...(result.sessionId
                ? [{ type: 'text', text: `SESSION_ID: ${result.sessionId}` }]
                : []),
        ],
    };
}
//# sourceMappingURL=run_claude.js.map