All files / src/llm-orchestration/hooks yolo-mode-post-execution.hook.ts

94.23% Statements 49/52
88.88% Branches 8/9
88.88% Functions 8/9
94% Lines 47/50

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 1287x 7x       7x 7x 7x 7x     7x                   7x 16x     16x 16x 16x 16x 16x 16x 16x               27x 1x 1x       26x 1x     1x     25x 25x 18x     7x 7x   7x 1x     1x 1x       6x 1x   6x 1x     1x     5x 5x     5x 4x     4x     4x         4x       4x             4x         4x               4x                
import { forwardRef, Inject, Injectable, Logger } from '@nestjs/common';
import { countTokens } from 'gpt-tokenizer';
import { PostExecutionHook } from './post-execution-hook.interface';
import { PlanExecutionContext } from '../llm-orchestration.interfaces';
import { SessionInput } from '../../core-entities';
import { ApplicationStateService } from '../../application-state/application-state.service';
import { ChatService } from '../../interactive-chat/chat.service';
import { SessionInputsService } from '../../session-inputs/session-inputs.service';
import { SessionsService } from '../../sessions/sessions.service';
import { CreateSessionInputDto } from '../../session-inputs/dto/session-input.dto';
 
const FILE_MODIFICATION_ACTIONS = [
  'create_file',
  'overwrite_file',
  'delete_file',
  'quick_edit',
  'apply_diff',
  'patch',
];
 
@Injectable()
export class YoloModePostExecutionHook implements PostExecutionHook {
  private readonly logger = new Logger(YoloModePostExecutionHook.name);
 
  constructor(
    private readonly appStateService: ApplicationStateService,
    @Inject(forwardRef(() => ChatService))
    private readonly chatService: ChatService,
    @Inject(forwardRef(() => SessionInputsService))
    private readonly sessionInputsService: SessionInputsService,
    @Inject(forwardRef(() => SessionsService))
    private readonly sessionsService: SessionsService,
  ) {}
 
  async run(
    sessionInput: SessionInput,
    context: PlanExecutionContext,
  ): Promise<void> {
    // If a higher-priority hook has already initiated a new turn, do nothing.
    if (context.flags.should_halt_hooks) {
      this.logger.log('YOLO mode hook skipped because hook chain was halted.');
      return;
    }
 
    // If another hook has already initiated a follow-up action, do nothing.
    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;
    }
 
    // Check if any actions failed - check sessionInput.aiActions for failures
    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();
 
      // Check token limit for YOLO follow-up message
      const tokenCount = countTokens(yoloMessage);
 
      // Fetch session to get the followup context template and system_prompt_id
      const session = await this.sessionsService.findOne(
        sessionInput.session_id,
      );
 
      const followupLimit =
        await this.appStateService.getEffectiveFollowupTokenLimit(
          session.system_prompt_id,
        );
 
      Iif (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).`,
      );
 
      // Trigger YOLO follow-up with skip_persistence to avoid empty user messages in history
      const yoloDto: CreateSessionInputDto = {
        user_prompt: yoloMessage,
        execution_strategy: sessionInput.execution_strategy,
        skip_persistence: true, // Don't create SessionInput record
        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}`),
        );
    }
  }
}