/**
 * runAgent — local-process agent runner. The TypeScript equivalent of the
 * backend's run_simple_agent().
 *
 * Takes a config (system prompt, tools, model) + query, runs the
 * chat → tools → check loop to completion, returns the result. No AgentSession,
 * no extensions, no persistence, no TUI.
 *
 * Use cases:
 *  - Subagent child processes
 *  - Local agent that mirrors what the server does
 *  - Tests that need a real agent loop without app infrastructure
 */
import { streamSimple } from '../ai/stream.js';
import { AgentController } from '../core/agent-controller.js';
import { AgentEngine } from '../core/agent-engine.js';
export async function runAgent(config, query) {
    const agent = new AgentController({
        initialState: {
            systemPrompt: config.systemPrompt,
            model: config.model,
            thinkingLevel: config.thinkingLevel ?? 'off',
            tools: config.tools
        },
        runtime: new AgentEngine({
            convertToLlm: config.convertToLlm,
            streamFn: config.streamFn ?? streamSimple,
            getApiKey: config.getApiKey,
            requestAssistantResponse: config.requestAssistantResponse
        })
    });
    if (config.onEvent) {
        agent.subscribe(config.onEvent);
    }
    if (config.signal) {
        const onAbort = () => agent.abort();
        config.signal.addEventListener('abort', onAbort, { once: true });
    }
    try {
        await agent.prompt(query);
        const messages = agent.state.messages;
        const finalContent = extractFinalContent(messages);
        const lastMsg = findLastAssistant(messages);
        const error = lastMsg?.stopReason === 'error' ? lastMsg.errorMessage || 'Unknown error' : undefined;
        const cancelled = lastMsg?.stopReason === 'aborted';
        return { messages, finalContent, error, cancelled };
    }
    catch (err) {
        return {
            messages: agent.state.messages,
            finalContent: '',
            error: err?.message || String(err),
            cancelled: config.signal?.aborted ?? false
        };
    }
}
function findLastAssistant(messages) {
    for (let i = messages.length - 1; i >= 0; i--) {
        if (messages[i].role === 'assistant')
            return messages[i];
    }
    return undefined;
}
function extractFinalContent(messages) {
    const last = findLastAssistant(messages);
    if (!last)
        return '';
    return last.content
        .filter((c) => c.type === 'text')
        .map((c) => c.text)
        .join('');
}
//# sourceMappingURL=run-agent.js.map