import { RUN_STATUS_TO_A2A, TERMINAL_STATES } from '../../constants/a2a/index.js';
import { extractTextFromA2AMessage, messageToA2A } from './message.js';
export function isTerminalState(state) {
    return TERMINAL_STATES.has(state);
}
export function runStatusToA2AState(status) {
    return RUN_STATUS_TO_A2A[status];
}
function buildTaskStatus(run) {
    const state = runStatusToA2AState(run.status);
    const timestamp = run.completed_at ?? run.started_at ?? run.created_at;
    const message = run.result
        ? { role: 'agent', parts: [{ kind: 'text', text: run.result }] }
        : run.last_error
            ? { role: 'agent', parts: [{ kind: 'text', text: run.last_error }] }
            : undefined;
    return { state, message, timestamp };
}
function buildArtifacts(run) {
    if (!run.result)
        return undefined;
    return [
        {
            artifactId: `${run.id}-result`,
            name: 'Agent Response',
            parts: [{ kind: 'text', text: run.result }],
            metadata: {
                model: run.model,
                iterations: run.iterations,
                duration_ms: run.duration_ms,
                ...(run.usage && {
                    input_tokens: run.usage.input_tokens,
                    output_tokens: run.usage.output_tokens,
                    total_cost_usd: run.usage.total_cost_usd,
                }),
            },
        },
    ];
}
export function runToA2ATask(run, messages) {
    return {
        id: run.id,
        contextId: run.project_id ?? undefined,
        status: buildTaskStatus(run),
        history: messages?.map(messageToA2A),
        artifacts: buildArtifacts(run),
        metadata: {
            agent_id: run.agent_id,
            agent_name: run.agent_name,
            stop_reason: run.stop_reason,
        },
    };
}
export function a2aMessageToCreateRun(agentId, params) {
    const input = extractTextFromA2AMessage(params.message);
    const meta = params.metadata ?? {};
    const config = {
        ...(typeof meta.model === 'string' && { model: meta.model }),
        ...(typeof meta.tokenBudget === 'number' && { tokenBudget: meta.tokenBudget }),
        ...(typeof meta.timeoutMs === 'number' && { timeoutMs: meta.timeoutMs }),
        ...(typeof meta.temperature === 'number' && { temperature: meta.temperature }),
        ...(typeof meta.maxResponseTokens === 'number' && {
            maxResponseTokens: meta.maxResponseTokens,
        }),
        ...((meta.permissionMode === 'plan' || meta.permissionMode === 'auto') && {
            permissionMode: meta.permissionMode,
        }),
        ...(typeof meta.systemPrompt === 'string' && { systemPrompt: meta.systemPrompt }),
    };
    return {
        agentId,
        input,
        projectId: params.contextId,
        config,
    };
}
//# sourceMappingURL=task.js.map