All files / src/llm-orchestration/action-handlers create-file.handler.ts

84.21% Statements 48/57
75% Branches 12/16
75% Functions 6/8
83.63% Lines 46/55

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 2257x             7x 7x 7x 7x             7x 7x 7x 7x     7x 13x 13x 13x         13x   13x                                                                   2x           2x                                                   2x                 2x                           2x       17x 17x 1x       16x 16x 1x       15x             20x 20x 20x 3x 3x   3x                 17x 17x   15x 15x 15x     14x   13x   13x 13x         13x                                                     14x                   1x     1x            
import {
  BadRequestException,
  Injectable,
  InternalServerErrorException,
  Logger,
  Optional,
} from '@nestjs/common';
import * as fs from 'fs/promises';
import * as path from 'path';
import { plainToClass } from 'class-transformer';
import { validate } from 'class-validator';
import { ActionHandler } from './action-handler.interface';
import {
  ActionExecutionResult,
  PlanExecutionContext,
  ToolMetadata,
} from '../llm-orchestration.interfaces';
import { CreateFileArgsDto } from './dto/create-file.args.dto';
import { generateToolCall, generateToolCallJson } from '../../utils';
import { SyntaxValidationService } from '../../syntax-validation/syntax-validation.service';
import { ApplicationStateService } from '../../application-state/application-state.service';
 
@Injectable()
export class CreateFileHandler implements ActionHandler {
  readonly toolName = 'create_file';
  private readonly logger = new Logger(CreateFileHandler.name);
  private readonly projectRoot: string =
    process.env.REPOBURG_PROJECT_PATH || process.cwd();
 
  constructor(
    @Optional()
    private readonly syntaxValidator?: SyntaxValidationService,
    @Optional()
    private readonly appStateService?: ApplicationStateService,
  ) {}
 
  getMetadata(): ToolMetadata {
    return {
      name: this.toolName,
      description: this.getDefinition(true),
      arguments: [
        {
          name: 'file_path',
          type: 'string',
          description: 'The relative path for the new file.',
          required: true,
        },
        {
          name: 'content',
          type: 'string',
          description: 'The full content of the new file.',
          required: true,
        },
      ],
    };
  }
 
  /**
   * 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 exampleContent = `\`\`\`typescript
import { v4 as uuidv4 } from 'uuid';
 
export interface UserProfile {
  id: string;
  username: string;
  email: string;
  createdAt: Date;
}
 
/**
 * Creates a new user profile with a unique ID and creation date.
 * @param username The user's chosen username.
 * @param email The user's email address.
 * @returns A new UserProfile object.
 */
export function createProfile(username: string, email: string): UserProfile {
  return {
    id: uuidv4(),
    username,
    email,
    createdAt: new Date(),
  };
}
\`\`\``.trim();
 
    const example = this.generateExample(
      {
        tool_name: this.toolName,
        file_path: 'src/modules/users/profiles.util.ts',
        content: exampleContent,
      },
      useJsonFormat,
    );
 
    const definition = `
-------------
### ${this.toolName}
  Creates a new file with the specified content. It will create any necessary parent directories.
 
  #### Parameters
  - "file_path": (string) The relative path for the new file.
  - "content": (string) The full content of the new file.
 
  #### Example
    Explanation: Create a new utility file for creating user profiles.
:${example}
-------------
`;
    return `\n${definition.trim()}\n`;
  }
 
  private resolveAndValidatePath(unsafePath: string): string {
    const normalizedPath = path.normalize(unsafePath);
    if (path.isAbsolute(normalizedPath)) {
      throw new BadRequestException(
        `Absolute paths are not allowed: ${unsafePath}`,
      );
    }
    const resolvedPath = path.resolve(this.projectRoot, normalizedPath);
    if (!resolvedPath.startsWith(this.projectRoot)) {
      throw new BadRequestException(
        `Path traversal is not allowed: ${unsafePath}`,
      );
    }
    return resolvedPath;
  }
 
  async execute(
    args: { [key: string]: any },
    _context: PlanExecutionContext,
  ): Promise<ActionExecutionResult> {
    const validatedArgs = plainToClass(CreateFileArgsDto, 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 { file_path, content } = validatedArgs;
    const safePath = this.resolveAndValidatePath(file_path);
 
    try {
      await fs.mkdir(path.dirname(safePath), { recursive: true });
      await fs.writeFile(safePath, content, 'utf8');
 
      // Syntax validation after file creation
      if (this.syntaxValidator && this.appStateService) {
        const isValidationEnabled =
          await this.appStateService.getSyntaxValidationEnabled();
 
        if (isValidationEnabled) {
          const validationError = await this.syntaxValidator.validate(
            file_path,
            content,
          );
 
          Iif (validationError) {
            this.logger.warn(
              `Syntax validation failed for newly created file "${file_path}"`,
            );
            let errorMessage =
              this.syntaxValidator.formatErrors(validationError);
            errorMessage += `\n**CORRECTION:** The file content you provided contains syntax errors. `;
            errorMessage += `Please review the errors above and fix the syntax issues. `;
            errorMessage += `Common issues include: missing closing brackets/braces, unclosed strings, malformed imports, or invalid operators. `;
            errorMessage += `Use \`create_file\` again with the corrected content.`;
 
            // Delete corrupted file to prevent it from persisting
            await fs.unlink(safePath).catch(() => {
              // Ignore deletion errors
            });
 
            return {
              status: 'FAILURE',
              summary: `File "${file_path}" contains syntax errors and was not saved.`,
              error_message: errorMessage,
              persisted_args: validatedArgs,
              execution_log: { output: '', error_message: errorMessage },
            };
          }
        }
      }
 
      return {
        status: 'SUCCESS',
        summary: `File "${file_path}" created.`,
        persisted_args: { file_path, content },
        execution_log: {
          output: `${file_path} has been created.`,
          error_message: '',
        },
      };
    } catch (error) {
      this.logger.error(
        `Failed to create file at ${file_path}: ${error.message}`,
      );
      throw new InternalServerErrorException(
        `Failed to create file "${file_path}": ${error.message}`,
      );
    }
  }
}