import { BestAgentError } from "@best-agent/foundation";
import { decodeTextualToolCall } from "./provider-direct-response-policy.js";
export async function handleProviderControlLeakResponse(input) {
    if (shouldUseTerminalControlLeakSafetyFallback(input)) {
        return input.runtime.terminalOutputFallback(input.turn, new BestAgentError("TERMINAL_OUTPUT_INVALID", "Terminal assistant output contained leaked control payload text instead of a user-visible answer."));
    }
    const decodedTextualToolCall = decodeTextualToolCall(input.decision.text);
    if (decodedTextualToolCall &&
        input.actionPolicy.allowedActions.includes("tool") &&
        input.visibleTools.some((tool) => tool.name === decodedTextualToolCall.toolName)) {
        const message = `Provider emitted textual ${decodedTextualToolCall.toolName} tool-call content instead of a native tool decision.`;
        input.runtime.markDecisionOutcome(input.decision, {
            runtimeOutcome: "failed",
            validation: {
                message,
                reasonCode: "textual-control-payload",
            },
        });
        throw new BestAgentError("PROVIDER_DECISION_INVALID", message);
    }
    if (!input.leakedControlResponse) {
        return undefined;
    }
    const message = "Terminal assistant output contained leaked control payload text instead of a user-visible answer.";
    input.runtime.markDecisionOutcome(input.decision, {
        runtimeOutcome: "failed",
        validation: {
            message,
            reasonCode: "leaked-control-payload",
        },
    });
    throw new BestAgentError("TERMINAL_OUTPUT_INVALID", message);
}
function shouldUseTerminalControlLeakSafetyFallback(input) {
    return (input.leakedControlResponse &&
        input.actionPolicy.directResponseAllowed &&
        input.actionPolicy.allowedActions.includes("respond") &&
        (input.repairAttempt > 0 ||
            input.invokeContext.correctionTrace?.code === "TERMINAL_OUTPUT_INVALID"));
}
//# sourceMappingURL=provider-control-leak-response-handler.js.map