import { runProviderToolFollowUp } from "./provider-tool-follow-up-runner.js";
import { isProviderToolLoopRoutingDowngradeEligible } from "./provider-tool-loop-context.js";
import { buildProviderToolFollowUpDecisionSystemPrompt } from "./provider-tool-follow-up-prompt.js";
export { buildProviderToolLoopFollowUpState, } from "./provider-tool-follow-up-state.js";
export { buildToolFollowUpMessages, renderStructuredToolObservation, toProviderHistoryCompletedToolCall, } from "./provider-tool-observation.js";
import { buildProviderToolLoopFollowUpState } from "./provider-tool-follow-up-state.js";
export async function continueProviderToolOutputBoundary(input) {
    const { context, runtime, turn } = input;
    const currentToolResult = await runtime.checkpoints.restoreToolOutputCheckpointArtifacts(turn, context, input.toolResultItem, input.evidenceRecords, input);
    const profile = input.invokeContext.profile;
    const approvalTurn = await runtime.approvals.resolveApprovalTurn(turn, context);
    if (context.mode === "tool-plan") {
        return `Tool ${context.toolName} result: ${currentToolResult?.output ?? input.toolOutput}`;
    }
    const loopFollowUp = buildProviderToolLoopFollowUpState({
        context,
        currentToolResult,
        renderToolInputForProviderHistory: runtime.observations.renderToolInputForProviderHistory,
        toolInputStableDigest: input.toolInputStableDigest,
        toolOutput: input.toolOutput,
        toolReplayPolicyForFollowUp: runtime.observations.toolReplayPolicyForFollowUp,
    });
    const { completedToolCalls, consumedToolStepCount, nextExecutionFailureCount, nextRepairAttempt, nextToolCall, remainingToolCalls, unresolvedRequiredToolConstraint, } = loopFollowUp;
    if (nextToolCall && currentToolResult?.outcome !== "error") {
        const nextToolInput = await runtime.checkpoints.resolveReplayToolInput(nextToolCall);
        const nextContext = {
            ...context,
            completedToolCalls,
            executionFailureCount: nextExecutionFailureCount,
            pendingToolCalls: remainingToolCalls,
            providerTurnBudgeted: input.invokeContext.budget.enabled,
            providerTurnCount: input.invokeContext.budget.used,
            repairAttempt: nextRepairAttempt,
            reasoning: undefined,
            requiredToolConstraint: unresolvedRequiredToolConstraint,
            toolCallId: nextToolCall.toolCallId,
            toolInput: nextToolInput,
            toolName: nextToolCall.toolName,
            providerToolName: nextToolCall.providerToolName,
            toolStepCount: context.toolStepCount,
        };
        const nextToolOutput = await runtime.execution.executeToolInvocation({
            activeSkillIds: context.activeSkillIds,
            approvalTurn,
            profile,
            resumeContext: nextContext,
            toolCallId: nextToolCall.toolCallId,
            toolInput: nextToolInput,
            toolName: nextToolCall.toolName,
            turn,
        });
        return continueProviderToolOutputBoundary({
            context: nextContext,
            invokeContext: input.invokeContext,
            runtime,
            toolOutput: nextToolOutput,
            turn,
        });
    }
    const followUpMessages = loopFollowUp.followUpMessages;
    const pendingToolHookContextPrompt = runtime.observations.takePendingToolHookContextPrompt(turn.threadId);
    const followUpVisibleTools = loopFollowUp.followUpVisibleTools;
    const advancedPhaseEscalationLevel = context.advancedPhase
        ? await runtime.routing.advancedPhaseReopenCount(turn.id)
        : 0;
    const followUpRoute = runtime.routing.resolveProviderRoute({
        downgradeEligible: isProviderToolLoopRoutingDowngradeEligible(context.phaseName),
        escalationLevel: advancedPhaseEscalationLevel,
        fixedRouteConfigOverride: context.fixedRouteConfigOverride,
        operation: "tool-followup",
        phaseName: context.phaseName,
        profileName: profile.name,
        routeConfigOverride: context.routeConfigOverride,
        threadId: turn.threadId,
        toolStepCount: consumedToolStepCount,
        turnId: turn.id,
    });
    const followUpDecisionSystemPrompt = buildProviderToolFollowUpDecisionSystemPrompt({
        completedToolCalls,
        context,
        pendingToolHookContextPrompt,
        unresolvedRequiredToolConstraint,
    });
    const followUpResult = await runProviderToolFollowUp({
        advancedPhaseEscalationLevel,
        completedToolCalls,
        consumedToolStepCount,
        context,
        followUpDecisionSystemPrompt,
        followUpMessages,
        followUpRouteConfig: followUpRoute.config,
        followUpVisibleTools,
        invokeContext: input.invokeContext,
        pendingToolHookContextPrompt,
        runtime,
        turn,
        unresolvedRequiredToolConstraint,
    });
    if (followUpResult.kind === "response") {
        return followUpResult.responseText;
    }
    return runtime.resolveProviderDecision({
        approvalTurn,
        availableTools: context.availableTools,
        cacheControl: context.cacheControl,
        controls: {
            allowPhaseResult: context.allowPhaseResult ?? false,
            allowPlanUpdate: context.allowPlanUpdate ?? false,
            ...(context.phaseResultPhaseName
                ? { phaseResultPhaseName: context.phaseResultPhaseName }
                : {}),
        },
        decision: followUpResult.decision,
        invokeContext: followUpResult.invokeContext,
        messages: followUpResult.followUpMessages,
        objective: followUpResult.invokeContext.objective ?? context.objective,
        operation: "tool-followup",
        repairAttempt: nextRepairAttempt,
        requiredToolConstraint: unresolvedRequiredToolConstraint,
        resolvePreviewToolCallId: followUpResult.resolvePreviewToolCallId,
        systemPrompt: followUpResult.followUpDecisionSystemPrompt,
        toolStepCount: consumedToolStepCount,
        turn,
        visibleTools: followUpVisibleTools,
    });
}
//# sourceMappingURL=provider-tool-loop.js.map