All files / src/session-inputs session-input-context.service.ts

87.77% Statements 79/90
83.87% Branches 26/31
77.77% Functions 7/9
87.35% Lines 76/87

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 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 25016x     16x 16x 16x 16x 16x               16x 22x     22x 22x 22x 22x             21x 21x   21x 12x     11x 9x       9x   9x 11x 11x 10x       10x   1x     1x         9x         9x                       21x 21x   21x               21x                     21x   21x                     21x           21x 21x                   21x 21x 3x 3x               21x       21x   21x       21x   21x 3x   3x     3x     21x 1x     1x 1x   1x     1x           1x     1x     21x                 21x 21x 16x 16x     21x                 21x 21x         21x   21x   21x 1x 1x     1x     20x 1x     1x         19x     19x                        
import { Injectable, Logger, BadRequestException } from '@nestjs/common';
import { ContextTemplate } from '../core-entities';
import { CreateSessionInputDto } from './dto/session-input.dto';
import { ContextGenerationService } from '../context-generation/context-generation.service';
import { ApplicationStateService } from '../application-state/application-state.service';
import { ContextSnippetsService } from '../context-snippets/context-snippets.service';
import { countTokens } from 'gpt-tokenizer';
import { CustomVariablesService } from '../custom-variables/custom-variables.service';
 
interface ContextDefinition {
  files?: string[];
  folders?: string[];
  command_outputs?: string[];
}
@Injectable()
export class SessionInputContextService {
  private readonly logger = new Logger(SessionInputContextService.name);
 
  constructor(
    private readonly contextGenerationService: ContextGenerationService,
    private readonly applicationStateService: ApplicationStateService,
    private readonly contextSnippetsService: ContextSnippetsService,
    private readonly customVariablesService: CustomVariablesService,
  ) {}
 
  private async resolveContextSnippets(
    prompt: string,
  ): Promise<{ resolvedContent: string; cleanedPrompt: string }> {
    // Regex to find !handle that is a whole word (preceded by space/start, followed by space/end)
    const snippetRegex = /(^|\s)\!(\w[-\w]*)(?=\s|$)/g;
    const matches = [...prompt.matchAll(snippetRegex)];
 
    if (matches.length === 0) {
      return { resolvedContent: '', cleanedPrompt: prompt };
    }
 
    const snippetHandles = matches.map((match) => match[2]);
    this.logger.log(
      `Found context snippet handles: ${snippetHandles.join(', ')}`,
    );
 
    const resolvedContents: string[] = [];
 
    for (const handle of snippetHandles) {
      try {
        const snippet = await this.contextSnippetsService.findByHandle(handle);
        const content = await this.contextGenerationService.render(
          snippet.template_content,
          {}, // Pass an empty data object to make helpers available
        );
        resolvedContents.push(content);
      } catch (error) {
        this.logger.error(
          `Failed to resolve context snippet "!${handle}": ${error.message}`,
        );
        resolvedContents.push(`Error resolving !${handle}: ${error.message}`);
      }
    }
 
    // Remove only the exclamation mark, preserving the handle text in the prompt.
    const cleanedPrompt = prompt
      .replace(/(^|\s)\!(\w[-\w]*)(?=\s|$)/g, '$1$2')
      .replace(/\s{2,}/g, ' ')
      .trim();
 
    return {
      resolvedContent: resolvedContents.join('\n\n'),
      cleanedPrompt,
    };
  }
 
  async generateContext(
    dto: CreateSessionInputDto,
    contextTemplate: ContextTemplate | null,
    previousActionsSummary?: string,
  ): Promise<string> {
    const { resolvedContent: context_snippets_content, cleanedPrompt } =
      await this.resolveContextSnippets(dto.user_prompt);
    dto.user_prompt = cleanedPrompt; // Update DTO with cleaned prompt for template rendering
 
    this.logger.log(
      `Generating context. Template: ${
        contextTemplate?.template_name || 'None'
      }. Ad-hoc: ${!!dto.ad_hoc_context_definition}. Snippets: ${
        context_snippets_content.length > 0 ? 'Yes' : 'No'
      }.`,
    );
 
    const defaultTemplate = `<%~ it.context_snippets_content %>
 
<%~ it.adhoc_files_content %>
 
<%~ it.adhoc_folders_content %>
 
<%~ it.adhoc_command_outputs_content %>
 
<%~ it.user_input %>`;
 
    const templateContent =
      contextTemplate?.template_content ?? defaultTemplate;
 
    Iif (templateContent.trim() === '') {
      this.logger.warn(
        'Context template is empty. Using only the user prompt.',
      );
      return dto.user_prompt;
    }
 
    const adHocData: {
      adhoc_files_content: string;
      adhoc_folders_content: string;
      adhoc_command_outputs_content: string;
    } = {
      adhoc_files_content: '',
      adhoc_folders_content: '',
      adhoc_command_outputs_content: '',
    };
 
    let templateContextDef: ContextDefinition = {};
    Iif (contextTemplate?.context_definition) {
      try {
        templateContextDef = JSON.parse(contextTemplate.context_definition);
      } catch (e) {
        this.logger.warn(
          `Could not parse context_definition from template ID ${contextTemplate.id}`,
        );
      }
    }
 
    let adhocContextDef: ContextDefinition = {};
    if (dto.ad_hoc_context_definition) {
      try {
        adhocContextDef = JSON.parse(dto.ad_hoc_context_definition);
      } catch (e) {
        this.logger.warn(
          `Could not parse ad_hoc_context_definition as JSON: ${dto.ad_hoc_context_definition}`,
        );
      }
    }
 
    const mergedFiles = [
      ...(templateContextDef.files || []),
      ...(adhocContextDef.files || []),
    ];
    const uniqueFiles = [...new Set(mergedFiles)];
 
    const mergedFolders = [
      ...(templateContextDef.folders || []),
      ...(adhocContextDef.folders || []),
    ];
    const uniqueFolders = [...new Set(mergedFolders)];
 
    if (uniqueFiles.length > 0) {
      const fileContents = await Promise.all(
        uniqueFiles.map((filePath: string) =>
          this.contextGenerationService.secureReadFile(filePath),
        ),
      );
      adHocData.adhoc_files_content = fileContents.join('\n\n');
    }
 
    if (uniqueFolders.length > 0) {
      const folderContexts = await Promise.all(
        uniqueFolders.map(async (folderPath: string) => {
          const tree =
            await this.contextGenerationService.secureTree(folderPath);
          const header = `// Tree for: ${folderPath}\n\`\`\`\n${tree}\n\`\`\``;
 
          const filesInFolder = await this.contextGenerationService.secureGlob(
            `${folderPath}/**/*`,
          );
          const fileContents = await Promise.all(
            filesInFolder.map((filePath: string) =>
              this.contextGenerationService.secureReadFile(filePath),
            ),
          );
 
          return [header, ...fileContents].join('\n\n');
        }),
      );
      adHocData.adhoc_folders_content = folderContexts.join('\n\n---\n\n');
    }
 
    Iif (
      adhocContextDef.command_outputs &&
      adhocContextDef.command_outputs.length > 0
    ) {
      adHocData.adhoc_command_outputs_content = adhocContextDef.command_outputs
        .map((output) => `// Command Output:\n\`\`\`\n${output}\n\`\`\``)
        .join('\n\n');
    }
 
    const enabledVariables = await this.customVariablesService.findAllEnabled();
    const variableMap = enabledVariables.reduce((acc, curr) => {
      acc[curr.key] = curr.value;
      return acc;
    }, {});
 
    const data = {
      ad_hoc_context_definition: dto.ad_hoc_context_definition || null,
      user_input: dto.user_prompt,
      user_prev_action: previousActionsSummary || '',
      context_snippets_content,
      ...adHocData,
      VAR: variableMap,
    };
 
    try {
      const generatedString = await this.contextGenerationService.render(
        templateContent,
        data,
      );
 
      const tokenCount = countTokens(generatedString);
      const TOKEN_LIMIT =
        await this.applicationStateService.getContextTokenLimit();
 
      if (tokenCount > TOKEN_LIMIT) {
        const errorMessage = `The context you requested is too large (${tokenCount} tokens, limit is ${TOKEN_LIMIT}). Please ask for a smaller context.`;
        this.logger.warn(
          `Generated context exceeds token limit. Size: ${tokenCount} tokens. Limit: ${TOKEN_LIMIT} tokens.`,
        );
        return errorMessage;
      }
 
      if (!templateContent.includes('it.user_input')) {
        this.logger.warn(
          "Template does not explicitly use 'it.user_input'. Appending user prompt to the end.",
        );
        return generatedString.trim()
          ? `${generatedString}\n\n${dto.user_prompt}`
          : dto.user_prompt;
      }
 
      this.logger.log(
        `Generated context string of length ${generatedString.length} (${tokenCount} tokens)`,
      );
      return generatedString;
    } catch (error) {
      this.logger.error(
        `Context generation failed: ${error.message}`,
        error.stack,
      );
      throw new BadRequestException(
        `Failed to generate context from template: ${error.message}`,
      );
    }
  }
}