All files / src/llm-orchestration/action-handlers request-context.handler.ts

90% Statements 54/60
75% Branches 9/12
87.5% Functions 7/8
89.28% Lines 50/56

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 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 1997x           7x 7x 7x   7x 7x 7x 7x     7x 14x 14x     14x 14x                                                                     4x           2x                 2x               2x                                 2x             9x 9x 9x 2x 2x   2x                 7x 7x 7x   7x 7x     7x 7x   7x 6x   1x 1x         7x 2x 2x     2x 4x   4x 4x                             7x     7x   7x       7x   1x     1x       1x                 6x                
import { Injectable, Logger } from '@nestjs/common';
import { ActionHandler } from './action-handler.interface';
import {
  ActionExecutionResult,
  ToolMetadata,
} from '../llm-orchestration.interfaces';
import { RequestContextArgsDto } from './dto/request-context.args.dto';
import { plainToClass } from 'class-transformer';
import { validate } from 'class-validator';
 
import { generateToolCall, generateToolCallJson } from '../../utils';
import { ContextGenerationService } from '../../context-generation/context-generation.service';
import { ApplicationStateService } from '../../application-state/application-state.service';
import { countTokens } from 'gpt-tokenizer';
 
@Injectable()
export class RequestContextHandler implements ActionHandler {
  readonly toolName = 'request_context';
  private readonly logger = new Logger(RequestContextHandler.name);
 
  constructor(
    private readonly contextGenerationService: ContextGenerationService,
    private readonly applicationStateService: ApplicationStateService,
  ) {}
 
  getMetadata(): ToolMetadata {
    return {
      name: this.toolName,
      description: this.getDefinition(true),
      arguments: [
        {
          name: 'files',
          type: 'string',
          description: 'A comma-separated list of relative file paths to read.',
          required: false,
        },
        {
          name: 'folders',
          type: 'string',
          description:
            'A comma-separated list of relative folder paths to read.',
          required: false,
        },
      ],
    };
  }
 
  /**
   * Generates a tool call example in the specified format.
   * @param toolCall - The tool call object to format
   * @param useJson - If true, uses JSON format; otherwise uses XML-style format
   * @returns Formatted tool call string
   */
  private generateExample(
    toolCall: Record<string, any>,
    useJson: boolean = false,
  ): string {
    return useJson
      ? generateToolCallJson(toolCall)
      : generateToolCall(toolCall);
  }
 
  getDefinition(useJsonFormat: boolean = false): string {
    const filesExample = this.generateExample(
      {
        tool_name: this.toolName,
        files:
          'src/App.tsx,src/theme/ThemeProvider.tsx,src/store/session.slice.ts,src/lib/api/client.ts',
      },
      useJsonFormat,
    );
 
    const foldersExample = this.generateExample(
      {
        tool_name: this.toolName,
        folders: 'src/components/common,src/hooks',
      },
      useJsonFormat,
    );
 
    const definition = `
-------------
### ${this.toolName}
  Requests content of files or entire folders to build context before making changes.
  This is a crucial exploration tool. It is efficient to request many files at once.
 
  #### Parameters
  - "files": (string, optional) A comma-separated list of relative file paths to read.
  - "folders": (string, optional) A comma-separated list of relative folder paths to read.
 
  #### Example: Files
:${filesExample}
 
  #### Example: Folders
:${foldersExample}
-------------
`;
    return `\n${definition.trim()}\n`;
  }
 
  async execute(
    args: { [key: string]: any },
    context: { system_prompt_id?: string | null },
  ): Promise<ActionExecutionResult> {
    const validatedArgs = plainToClass(RequestContextArgsDto, args);
    const errors = await validate(validatedArgs);
    if (errors.length > 0) {
      const errorMessages = errors
        .map((err) => Object.values(err.constraints || {}).join(', '))
        .join('; ');
      return {
        status: 'FAILURE',
        summary: `Invalid arguments for ${this.toolName}.`,
        error_message: errorMessages,
        persisted_args: args,
        execution_log: { output: '', error_message: errorMessages },
      };
    }
 
    const { files, folders } = validatedArgs;
    const fileList = files ? files.split(',').map((f) => f.trim()) : [];
    const folderList = folders ? folders.split(',').map((f) => f.trim()) : [];
 
    const outputParts: string[] = [];
    let errorMessage = '';
 
    // Fetch files
    for (const filePath of fileList) {
      try {
        const content =
          await this.contextGenerationService.secureReadFile(filePath);
        outputParts.push(content);
      } catch (error) {
        this.logger.warn(`Failed to fetch file ${filePath}: ${error.message}`);
        outputParts.push(`Error: File not found at '${filePath}'`);
      }
    }
 
    // Fetch folders using glob
    for (const folderPath of folderList) {
      try {
        const folderFiles = await this.contextGenerationService.secureGlob(
          `${folderPath}/**/*`,
        );
        for (const file of folderFiles) {
          try {
            const content =
              await this.contextGenerationService.secureReadFile(file);
            outputParts.push(content);
          } catch (error) {
            this.logger.warn(`Failed to fetch file ${file}: ${error.message}`);
            outputParts.push(`Error: Could not read file '${file}'`);
          }
        }
      } catch (error) {
        this.logger.warn(
          `Failed to glob folder ${folderPath}: ${error.message}`,
        );
        outputParts.push(`Error: Could not read folder '${folderPath}'`);
        errorMessage += `Failed to read folder '${folderPath}'. `;
      }
    }
 
    const output = outputParts.join('\n\n');
 
    // Check token limit
    const tokenCount = countTokens(output);
    const tokenLimit =
      await this.applicationStateService.getEffectiveFollowupTokenLimit(
        context.system_prompt_id,
      );
 
    if (tokenCount > tokenLimit) {
      const limitErrorMessage =
        `Context too large: ${tokenCount} tokens (limit: ${tokenLimit}). ` +
        `Request fewer files or smaller folders. Consider using specific file paths instead of entire folders.`;
 
      this.logger.warn(
        `Context request exceeded token limit: ${tokenCount} > ${tokenLimit}`,
      );
 
      return {
        status: 'FAILURE',
        summary: `Context request exceeded token limit.`,
        error_message: limitErrorMessage,
        persisted_args: validatedArgs,
        execution_log: { output: '', error_message: limitErrorMessage },
      };
    }
 
    return {
      status: 'SUCCESS',
      summary: `Fetched ${fileList.length} files and ${folderList.length} folders (${tokenCount} tokens).`,
      persisted_args: validatedArgs,
      execution_log: { output, error_message: errorMessage },
    };
  }
}