"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var YoloModePostExecutionHook_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.YoloModePostExecutionHook = void 0;
const common_1 = require("@nestjs/common");
const gpt_tokenizer_1 = require("gpt-tokenizer");
const application_state_service_1 = require("../../application-state/application-state.service");
const chat_service_1 = require("../../interactive-chat/chat.service");
const session_inputs_service_1 = require("../../session-inputs/session-inputs.service");
const sessions_service_1 = require("../../sessions/sessions.service");
const FILE_MODIFICATION_ACTIONS = [
    'create_file',
    'overwrite_file',
    'delete_file',
    'quick_edit',
    'apply_diff',
    'patch',
];
let YoloModePostExecutionHook = YoloModePostExecutionHook_1 = class YoloModePostExecutionHook {
    constructor(appStateService, chatService, sessionInputsService, sessionsService) {
        this.appStateService = appStateService;
        this.chatService = chatService;
        this.sessionInputsService = sessionInputsService;
        this.sessionsService = sessionsService;
        this.logger = new common_1.Logger(YoloModePostExecutionHook_1.name);
    }
    async run(sessionInput, context) {
        if (context.flags.should_halt_hooks) {
            this.logger.log('YOLO mode hook skipped because hook chain was halted.');
            return;
        }
        if (context.flags.follow_up_initiated) {
            this.logger.log('YOLO mode hook skipped because follow-up was already initiated.');
            return;
        }
        const isYoloMode = await this.appStateService.getYoloModeEnabled();
        if (!isYoloMode) {
            return;
        }
        const hasFinalAction = context.originalParsedActions.some((a) => a.tool_name === 'final');
        if (hasFinalAction) {
            this.logger.log('YOLO mode: "final" action detected. Disabling YOLO mode.');
            await this.appStateService.setYoloModeEnabled(false);
            return;
        }
        const failedActions = sessionInput.aiActions?.filter((action) => action.status === 'EXECUTION_FAILED');
        if (failedActions && failedActions.length > 0) {
            this.logger.log(`YOLO mode: ${failedActions.length} failed action(s) detected. Skipping YOLO follow-up.`);
            return;
        }
        const hasFileModification = context.originalParsedActions.some((a) => FILE_MODIFICATION_ACTIONS.includes(a.tool_name));
        if (hasFileModification) {
            const yoloMessage = await this.appStateService.getYoloModeMessage();
            const tokenCount = (0, gpt_tokenizer_1.countTokens)(yoloMessage);
            const session = await this.sessionsService.findOne(sessionInput.session_id);
            const followupLimit = await this.appStateService.getEffectiveFollowupTokenLimit(session.system_prompt_id);
            if (tokenCount > followupLimit) {
                this.logger.warn(`YOLO message exceeds token limit (${tokenCount} > ${followupLimit}). Skipping YOLO follow-up.`);
                return;
            }
            this.logger.log(`YOLO mode: File modification detected. Triggering "${yoloMessage}" prompt (${tokenCount} tokens).`);
            const yoloDto = {
                user_prompt: yoloMessage,
                execution_strategy: sessionInput.execution_strategy,
                skip_persistence: true,
                ad_hoc_context_definition: undefined,
                context_template_id: session.default_followup_context_template_id,
            };
            await this.sessionInputsService
                .create(sessionInput.session_id, yoloDto)
                .catch((err) => this.logger.error(`YOLO follow-up failed: ${err.message}`));
        }
    }
};
exports.YoloModePostExecutionHook = YoloModePostExecutionHook;
exports.YoloModePostExecutionHook = YoloModePostExecutionHook = YoloModePostExecutionHook_1 = __decorate([
    (0, common_1.Injectable)(),
    __param(1, (0, common_1.Inject)((0, common_1.forwardRef)(() => chat_service_1.ChatService))),
    __param(2, (0, common_1.Inject)((0, common_1.forwardRef)(() => session_inputs_service_1.SessionInputsService))),
    __param(3, (0, common_1.Inject)((0, common_1.forwardRef)(() => sessions_service_1.SessionsService))),
    __metadata("design:paramtypes", [application_state_service_1.ApplicationStateService,
        chat_service_1.ChatService,
        session_inputs_service_1.SessionInputsService,
        sessions_service_1.SessionsService])
], YoloModePostExecutionHook);
//# sourceMappingURL=yolo-mode-post-execution.hook.js.map