All files / src/ai-actions ai-action-batch.service.ts

75.12% Statements 148/197
54% Branches 27/50
80% Functions 12/15
74.87% Lines 146/195

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 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 4897x                 7x 7x 7x 7x 7x 7x 7x 7x             7x 7x 7x 7x 7x 7x   7x     7x 16x 16x         16x   16x 16x 16x 16x 16x 16x 16x 16x 16x         4x 4x         4x   4x           4x       7x 2x 2x 2x 2x 2x 2x                   7x 1x 1x 1x 1x 1x 1x                   7x 1x 1x 1x       1x 1x 1x                     7x                                                                 7x         3x         3x 3x                         11x     11x 1x         10x               10x 1x     1x     9x   9x 12x 12x 12x   12x 12x     12x   5x         1x       4x 4x 4x   1x                 1x 1x 1x   1x     1x                                                                   5x 5x 4x 4x 1x       3x         3x 3x 1x     1x       3x 3x   3x                         1x       3x     8x 8x 8x   4x       4x 4x 4x     12x         12x   12x   12x           9x           2x     2x           2x                   2x             2x 2x 4x 4x 4x       4x         2x           2x     2x           2x             2x             2x 2x 2x 2x 2x       2x       2x           4x     4x 1x         3x               3x             3x 3x 5x     5x           3x     3x      
import {
  Injectable,
  Logger,
  NotFoundException,
  Inject,
  forwardRef,
  InternalServerErrorException,
  BadRequestException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { In, Repository } from 'typeorm';
import * as fs from 'fs/promises';
import * as path from 'path';
import { exec } from 'child_process';
import { promisify } from 'util';
import { AIAction, SessionInput } from '../core-entities';
import {
  AIActionsService,
  AIActionStatus,
  ActionResult,
  ConfirmedActionInfo,
  DiscardedActionInfo,
} from './ai-actions.service';
import { ExecutionLogsService } from '../execution-logs/execution-logs.service';
import { ApplicationStateService } from '../application-state/application-state.service';
import { ChatService } from '../interactive-chat/chat.service';
import { LlmResponsesService } from '../llm-responses/llm-responses.service';
import { McpService } from '../mcp/mcp.service';
import { Trace } from '../utils';
 
const execAsync = promisify(exec);
 
@Injectable()
export class AIActionBatchService {
  private readonly logger = new Logger(AIActionBatchService.name);
  private readonly projectRoot: string =
    process.env.REPOBURG_PROJECT_PATH || process.cwd();
 
  constructor(
    @InjectRepository(AIAction)
    private aiActionsRepository: Repository<AIAction>,
    @InjectRepository(SessionInput)
    private sessionInputsRepository: Repository<SessionInput>,
    private readonly aiActionsService: AIActionsService,
    private readonly executionLogsService: ExecutionLogsService,
    private readonly applicationStateService: ApplicationStateService,
    @Inject(forwardRef(() => ChatService))
    private readonly chatService: ChatService,
    @Inject(forwardRef(() => LlmResponsesService))
    private readonly llmResponsesService: LlmResponsesService,
    private readonly mcpService: McpService,
  ) {}
 
  // --- Start of Consolidated Logic from ActionExecutionService ---
  private resolveAndValidatePath(unsafePath: string): string {
    const normalizedPath = path.normalize(unsafePath);
    Iif (path.isAbsolute(normalizedPath)) {
      throw new BadRequestException(
        `Absolute paths are not allowed: ${unsafePath}`,
      );
    }
    const resolvedPath = path.resolve(this.projectRoot, normalizedPath);
 
    Iif (!resolvedPath.startsWith(this.projectRoot)) {
      this.logger.warn(`Path traversal attempt detected: ${unsafePath}`);
      throw new BadRequestException(
        `Path traversal is not allowed. Access denied for path: ${unsafePath}`,
      );
    }
    return resolvedPath;
  }
 
  @Trace()
  private async createFile(filePath: string, content: string): Promise<void> {
    const safePath = this.resolveAndValidatePath(filePath);
    const dir = path.dirname(safePath);
    try {
      await fs.mkdir(dir, { recursive: true });
      await fs.writeFile(safePath, content, 'utf8');
      this.logger.log(`Created file: ${safePath}`);
    } catch (error) {
      this.logger.error(`Error creating file ${safePath}: ${error.message}`);
      throw new InternalServerErrorException(
        `Failed to create file "${filePath}": ${error.message}`,
      );
    }
  }
 
  @Trace()
  private async editFile(filePath: string, newContent: string): Promise<void> {
    const safePath = this.resolveAndValidatePath(filePath);
    try {
      const dir = path.dirname(safePath);
      await fs.mkdir(dir, { recursive: true });
      await fs.writeFile(safePath, newContent, 'utf8');
      this.logger.log(`Edited file: ${safePath}`);
    } catch (error) {
      this.logger.error(`Error editing file ${safePath}: ${error.message}`);
      throw new InternalServerErrorException(
        `Failed to edit file "${filePath}": ${error.message}`,
      );
    }
  }
 
  @Trace()
  private async deleteFile(filePath: string): Promise<void> {
    const safePath = this.resolveAndValidatePath(filePath);
    try {
      await fs.access(safePath); // Check if file exists
      await fs.unlink(safePath);
      this.logger.log(`Deleted file: ${safePath}`);
    } catch (error) {
      this.logger.error(`Error deleting file ${safePath}: ${error.message}`);
      if (error.code === 'ENOENT') {
        throw new NotFoundException(
          `File not found, cannot delete: "${filePath}"`,
        );
      }
      throw new InternalServerErrorException(
        `Failed to delete file "${filePath}": ${error.message}`,
      );
    }
  }
 
  @Trace()
  private async runCommand(
    commandString: string,
  ): Promise<{ stdout: string; stderr: string }> {
    this.logger.log(`Executing command: ${commandString}`);
    try {
      const { stdout, stderr } = await execAsync(commandString, {
        cwd: this.projectRoot,
        maxBuffer: 128 * 1024 * 1024,
        timeout: 15000,
      });
      Iif (stderr) {
        this.logger.warn(
          `Command "${commandString}" produced stderr: ${stderr}`,
        );
      }
      this.logger.log(
        `Command "${commandString}" stdout: ${stdout || '(no stdout)'}`,
      );
      return { stdout, stderr };
    } catch (error) {
      this.logger.error(
        `Error executing command "${commandString}": ${error.message}`,
        error.stack,
      );
      const execError = error as any;
      const unifiedOutput = `COMMAND FAILED: ${execError.message}\n\nSTDOUT:\n${
        execError.stdout || 'N/A'
      }\n\nSTDERR:\n${execError.stderr || 'N/A'}`;
      return { stdout: unifiedOutput, stderr: '' };
    }
  }
 
  @Trace()
  private async useMcpTool(
    serverName: string,
    toolName: string,
    args: any,
  ): Promise<{ stdout: string; stderr: string }> {
    this.logger.log(
      `Executing MCP tool: ${serverName}.${toolName} with args ${JSON.stringify(
        args,
      )}`,
    );
    try {
      return await this.mcpService.executeMcpTool(serverName, toolName, args);
    } catch (error) {
      this.logger.error(
        `Error executing MCP tool "${serverName}.${toolName}": ${error.message}`,
        error.stack,
      );
      const unifiedOutput = `MCP TOOL FAILED: ${error.message}`;
      return { stdout: unifiedOutput, stderr: '' };
    }
  }
  // --- End of Consolidated Logic ---
 
  async applyApprovedActions(inputId: string): Promise<ActionResult[]> {
    const sessionInput = await this.sessionInputsRepository.findOneBy({
      id: inputId,
    });
    if (!sessionInput) {
      throw new NotFoundException(
        `SessionInput with ID "${inputId}" not found.`,
      );
    }
 
    const actionsToApply = await this.aiActionsRepository.find({
      where: {
        input_id: inputId,
        status: AIActionStatus.APPROVED_FOR_APPLY,
      },
      order: { order_of_execution: 'ASC', created_at: 'ASC' },
    });
 
    if (actionsToApply.length === 0) {
      this.logger.log(
        `No actions in "approved_for_apply" state for input ID "${inputId}".`,
      );
      return [];
    }
 
    const results: ActionResult[] = [];
 
    for (const action of actionsToApply) {
      let outcomeMessage = '';
      let errorMessage: string | undefined = undefined;
      let actionSucceeded = false;
 
      try {
        this.logger.log(
          `Attempting to apply action ID ${action.id}, type ${action.action_type}`,
        );
        switch (action.action_type) {
          case 'create_file':
            if (
              !action.file_path ||
              action.content === null ||
              action.content === undefined
            ) {
              throw new Error(
                'Missing file_path or content for create_file action.',
              );
            }
            await this.createFile(action.file_path, action.content);
            outcomeMessage = `File "${action.file_path}" created successfully.`;
            break;
          case 'overwrite_file':
            Iif (
              !action.file_path ||
              action.content === null ||
              action.content === undefined
            ) {
              throw new Error(
                'Missing file_path or content for overwrite_file action.',
              );
            }
            await this.editFile(action.file_path, action.content);
            outcomeMessage = `File "${action.file_path}" overwritten successfully.`;
            break;
          case 'delete_file':
            Iif (!action.file_path) {
              throw new Error('Missing file_path for delete_file action.');
            }
            await this.deleteFile(action.file_path);
            outcomeMessage = `File "${action.file_path}" deleted successfully.`;
            break;
          case 'run_command':
            Iif (!action.command_string) {
              throw new Error('Missing command_string for run_command action.');
            }
            const cmdResult = await this.runCommand(action.command_string);
            outcomeMessage = `Command "${
              action.command_string
            }" executed. Output: ${cmdResult.stdout || '(no stdout)'}`;
            Iif (cmdResult.stderr) {
              this.logger.warn(
                `Command stderr for action ${action.id}: ${cmdResult.stderr}`,
              );
              outcomeMessage += `\nStderr: ${cmdResult.stderr}`;
            }
 
            const isManualFlow =
              await this.applicationStateService.getManualLlmEnabled();
            const message = `The previous 'run_command' action produced this output. Please analyze it and continue with the next logical step based on the original request. Do not just describe the output; use it to proceed.\n\nOUTPUT:\n${cmdResult.stdout}`;
 
            this.chatService
              .sendMessage(sessionInput.session_id, message, isManualFlow)
              .catch((err) => {
                this.logger.error(
                  `Follow-up LLM call from run_command failed: ${err.message}`,
                  err.stack,
                );
              });
 
            break;
          default: {
            // Handle MCP tool calls (serverName__toolName pattern)
            const mcpMatch = action.action_type.match(/^([^_]+)__(.+)$/);
            if (mcpMatch) {
              const [, serverName, toolName] = mcpMatch;
              if (!action.arguments) {
                throw new Error(
                  `Missing arguments for MCP tool action: ${action.action_type}`,
                );
              }
              const mcpResult = await this.useMcpTool(
                serverName,
                toolName,
                JSON.parse(action.arguments),
              );
              outcomeMessage = `MCP Tool "${serverName}.${toolName}" executed. Output: ${mcpResult.stdout || '(no stdout)'}`;
              if (mcpResult.stderr) {
                this.logger.warn(
                  `MCP Tool stderr for action ${action.id}: ${mcpResult.stderr}`,
                );
                outcomeMessage += `\nStderr: ${mcpResult.stderr}`;
              }
 
              const isMcpManualFlow =
                await this.applicationStateService.getManualLlmEnabled();
              const mcpMessage = `The previous MCP tool "${serverName}.${toolName}" produced this output. Please analyze it and continue with the next logical step based on the original request. Do not just describe the output; use it to proceed.\n\nTOOL: ${serverName}.${toolName}\nOUTPUT:\n${mcpResult.stdout}`;
 
              this.chatService
                .sendMessage(
                  sessionInput.session_id,
                  mcpMessage,
                  isMcpManualFlow,
                )
                .catch((err) => {
                  this.logger.error(
                    `Follow-up LLM call from MCP tool failed: ${err.message}`,
                    err.stack,
                  );
                });
            } else {
              throw new Error(
                `Unsupported action_type: "${action.action_type}"`,
              );
            }
            break;
          }
        }
        action.status = AIActionStatus.CONFIRMED_KEPT;
        actionSucceeded = true;
        this.logger.log(`Action ID ${action.id} applied successfully.`);
      } catch (error) {
        this.logger.error(
          `Failed to apply action ID ${action.id}: ${error.message}`,
          error.stack,
        );
        action.status = AIActionStatus.EXECUTION_FAILED;
        errorMessage = error.message;
        outcomeMessage = `Failed to apply action: ${error.message}`;
      }
 
      const log = await this.executionLogsService.createLog({
        action_id: action.id,
        output: actionSucceeded ? outcomeMessage : undefined,
        error_message: errorMessage,
      });
      await this.aiActionsRepository.save(action);
 
      const reloadedAction = await this.aiActionsService.findOne(action.id);
 
      results.push({
        action_id: action.id,
        status: reloadedAction.status,
        logs: reloadedAction.executionLogs || [log],
      });
    }
    return results;
  }
 
  async discardAllActionsForInput(
    inputId: string,
  ): Promise<DiscardedActionInfo[]> {
    const sessionInput = await this.sessionInputsRepository.findOneBy({
      id: inputId,
    });
    Iif (!sessionInput) {
      throw new NotFoundException(
        `SessionInput with ID "${inputId}" not found.`,
      );
    }
 
    const actionsToDiscard = await this.aiActionsRepository.find({
      where: {
        input_id: inputId,
        status: In([
          AIActionStatus.PROPOSED,
          AIActionStatus.APPROVED_FOR_APPLY,
        ]),
      },
    });
 
    Iif (actionsToDiscard.length === 0) {
      this.logger.log(
        `No actions in "proposed" or "approved_for_apply" state for input ID "${inputId}" to discard.`,
      );
      return [];
    }
 
    const results: DiscardedActionInfo[] = [];
    for (const action of actionsToDiscard) {
      action.status = AIActionStatus.REJECTED_BEFORE_APPLY;
      await this.aiActionsRepository.save(action);
      results.push({
        action_id: action.id,
        status: action.status,
      });
      this.logger.log(
        `Action ID ${action.id} for input ${inputId} discarded, status set to ${action.status}.`,
      );
    }
 
    return results;
  }
 
  async confirmAllAppliedActionsForInput(
    inputId: string,
  ): Promise<ConfirmedActionInfo[]> {
    const sessionInput = await this.sessionInputsRepository.findOneBy({
      id: inputId,
    });
    Iif (!sessionInput) {
      throw new NotFoundException(
        `SessionInput with ID "${inputId}" not found.`,
      );
    }
 
    const actionsToConfirm = await this.aiActionsRepository.find({
      where: {
        input_id: inputId,
        status: AIActionStatus.APPLIED_PENDING_REVIEW,
      },
    });
 
    Iif (actionsToConfirm.length === 0) {
      this.logger.log(
        `No actions in "${AIActionStatus.APPLIED_PENDING_REVIEW}" state for input ID "${inputId}" to confirm.`,
      );
      return [];
    }
 
    const results: ConfirmedActionInfo[] = [];
    for (const action of actionsToConfirm) {
      action.status = AIActionStatus.CONFIRMED_KEPT;
      await this.aiActionsRepository.save(action);
      results.push({
        action_id: action.id,
        status: action.status,
      });
      this.logger.log(
        `Action ID ${action.id} for input ${inputId} confirmed kept, status set to ${action.status}.`,
      );
    }
    return results;
  }
 
  async revertAllAppliedActionsForInput(
    inputId: string,
  ): Promise<ActionResult[]> {
    const sessionInput = await this.sessionInputsRepository.findOneBy({
      id: inputId,
    });
    if (!sessionInput) {
      throw new NotFoundException(
        `SessionInput with ID "${inputId}" not found. Cannot revert actions.`,
      );
    }
 
    const actionsToRevert = await this.aiActionsRepository.find({
      where: {
        input_id: inputId,
        status: AIActionStatus.APPLIED_PENDING_REVIEW,
      },
      order: { order_of_execution: 'DESC', created_at: 'DESC' }, // Revert in reverse order
    });
 
    Iif (actionsToRevert.length === 0) {
      this.logger.log(
        `No actions in "${AIActionStatus.APPLIED_PENDING_REVIEW}" state for input ID "${inputId}" to revert.`,
      );
      return [];
    }
 
    const results: ActionResult[] = [];
    for (const action of actionsToRevert) {
      const revertedAction = await this.aiActionsService.revertAction(
        action.id,
      );
      results.push({
        action_id: revertedAction.id,
        status: revertedAction.status,
        logs: revertedAction.executionLogs || [],
      });
    }
    this.logger.log(
      `Attempted to revert ${actionsToRevert.length} actions for input ID "${inputId}".`,
    );
    return results;
  }
}