import { INTERRUPTED_SUMMARY } from '../constants.js';
import { HeddleEventType } from '../../../core/event-types.js';
/**
 * Owns terminal run outcomes and final RunResult shaping.
 */
export class AgentRunFinisher {
    static maybeInterrupted(context, logMessage) {
        if (!context.shouldStop?.()) {
            return undefined;
        }
        return AgentRunFinisher.finishInterrupted(context, logMessage);
    }
    static finishInterrupted(context, logMessage) {
        return AgentRunFinisher.finish(context, 'interrupted', INTERRUPTED_SUMMARY, {
            logLevel: 'info',
            logMessage,
        });
    }
    static finishAssistantResponse(context, response) {
        if (!response.content) {
            return AgentRunFinisher.finish(context, 'error', 'Model returned an empty response');
        }
        context.live.trace({
            type: HeddleEventType.assistantTurn,
            content: response.content,
            diagnostics: response.diagnostics,
            requestedTools: false,
            step: context.state.step,
            timestamp: context.now(),
        });
        context.messages.push({ role: 'assistant', content: response.content });
        return AgentRunFinisher.finish(context, 'done', response.content, {
            logLevel: 'info',
            logMessage: 'Agent run finished',
        });
    }
    static maxSteps(context) {
        return AgentRunFinisher.finish(context, 'max_steps', `Reached maximum step limit (${context.maxSteps})`, {
            logLevel: 'warn',
            logMessage: 'Budget exhausted',
        });
    }
    static finish(context, outcome, summary, logging) {
        context.state.outcome = outcome;
        context.state.summary = summary;
        if (logging) {
            context.log[logging.logLevel]({ step: context.state.step, outcome, maxSteps: context.maxSteps }, logging.logMessage);
        }
        context.live.trace({
            type: HeddleEventType.runFinished,
            outcome,
            summary,
            step: context.state.step,
            timestamp: context.now(),
        });
        return {
            outcome,
            summary,
            trace: context.trace.getTrace(),
            transcript: context.messages.slice(1),
            usage: context.state.usage,
        };
    }
    static isRunResult(value) {
        return 'outcome' in value;
    }
}
//# sourceMappingURL=run-finisher.js.map