All files / src/llm-orchestration/action-handlers run-command.handler.ts

82.14% Statements 69/84
70% Branches 28/40
75% Functions 6/8
81.7% Lines 67/82

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 2947x             7x 7x 7x   7x 7x 7x 7x 7x 7x     7x 19x 19x 19x   19x             19x                                                                     10x           2x               2x               2x               2x               2x                 2x                                                   2x                   16x     16x 3x 3x 3x         16x               16x 16x 16x 16x 3x 3x   3x                 13x 13x     13x       13x 13x         13x     13x       13x     13x   13x   13x         13x   2x 2x 2x 2x 2x 11x   1x 1x 1x 1x 1x   10x   10x                         13x                   13x   13x       13x                                   13x                        
import { Injectable, Logger } from '@nestjs/common';
import { ActionHandler } from './action-handler.interface';
import {
  ActionExecutionResult,
  PlanExecutionContext,
  ToolMetadata,
} from '../llm-orchestration.interfaces';
import { RunCommandArgsDto } from './dto/run-command.args.dto';
import { plainToClass } from 'class-transformer';
import { validate } from 'class-validator';
 
import { generateToolCall, generateToolCallJson } from '../../utils';
import { execWithProcessGroupKill } from '../../utils/spawn-with-kill';
import * as fs from 'fs/promises';
import * as path from 'path';
import { ApplicationStateService } from '../../application-state/application-state.service';
import { countTokens } from 'gpt-tokenizer';
 
@Injectable()
export class RunCommandHandler implements ActionHandler {
  readonly toolName = 'run_command';
  private readonly logger = new Logger(RunCommandHandler.name);
  private readonly projectRoot: string =
    process.env.REPOBURG_PROJECT_PATH || process.cwd();
  private readonly tempDir: string = path.join(
    this.projectRoot,
    '.repoburg',
    'temp',
  );
 
  constructor(
    private readonly applicationStateService: ApplicationStateService,
  ) {}
 
  getMetadata(): ToolMetadata {
    return {
      name: this.toolName,
      description: this.getDefinition(true),
      arguments: [
        {
          name: 'command_string',
          type: 'string',
          description: 'The shell command to execute.',
          required: true,
        },
        {
          name: 'timeout',
          type: 'number',
          description:
            'Optional timeout in milliseconds (default: 60000ms, min: 1000ms).',
          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 treeExample = this.generateExample(
      {
        tool_name: this.toolName,
        command_string: 'tree -L 2 src',
      },
      useJsonFormat,
    );
 
    const rgExample = this.generateExample(
      {
        tool_name: this.toolName,
        command_string: 'rg "TODO|FIXME" .',
      },
      useJsonFormat,
    );
 
    const gitExample = this.generateExample(
      {
        tool_name: this.toolName,
        command_string: 'git status',
      },
      useJsonFormat,
    );
 
    const installExample = this.generateExample(
      {
        tool_name: this.toolName,
        command_string: 'npm install lodash',
      },
      useJsonFormat,
    );
 
    const timeoutExample = this.generateExample(
      {
        tool_name: this.toolName,
        command_string: 'npm run build',
        timeout: 120000,
      },
      useJsonFormat,
    );
 
    const definition = `
-------------
### ${this.toolName}
  Executes a shell command in the root of the project.
  Used for system modifications, running scripts, package management, or git operations.
 
  #### Parameters
  - "command_string": (string) The shell command to execute.
  - "timeout": (number, optional) Timeout in milliseconds. Default is 60000ms (1 minute), minimum is 1000ms.
 
  #### Example: Tree
:${treeExample}
 
  #### Example: RipGrep
:${rgExample}
 
  #### Example: Git
:${gitExample}
 
  #### Example: Install
:${installExample}
 
  #### Example: With Timeout
:${timeoutExample}
-------------
`;
    return `\n${definition.trim()}\n`;
  }
 
  /**
   * Normalizes common parameter name mistakes before validation.
   * Maps intuitive but incorrect names to the expected schema.
   * @param args - The raw arguments from the LLM
   * @returns Normalized arguments with correct parameter names
   */
  private normalizeArgs(args: Record<string, any>): Record<string, any> {
    const normalized = { ...args };
 
    // Map 'command' to 'command_string'
    if ('command' in normalized && !('command_string' in normalized)) {
      normalized.command_string = normalized.command;
      delete normalized.command;
      this.logger.debug(
        'Auto-corrected parameter name: "command" → "command_string"',
      );
    }
 
    return normalized;
  }
 
  async execute(
    args: { [key: string]: any },
    _context: PlanExecutionContext,
  ): Promise<ActionExecutionResult> {
    // Auto-correct common parameter name mistakes before validation
    const normalizedArgs = this.normalizeArgs(args);
    const validatedArgs = plainToClass(RunCommandArgsDto, normalizedArgs);
    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 { command_string, timeout } = validatedArgs;
    const commandTimeout = timeout ?? 60000;
    let unifiedOutput: string;
    let summary: string;
    let status: 'SUCCESS' | 'FAILURE' = 'SUCCESS';
    let errorMessage: string | undefined;
 
    // Create temp directory and script
    await fs.mkdir(this.tempDir, { recursive: true });
    const scriptPath = path.join(
      this.tempDir,
      `run-${Date.now()}-${Math.random().toString(36).substring(7)}.sh`,
    );
 
    try {
      // Write command to a shell script
      // Explicitly cd to project root because login shells might reset cwd to home
      const scriptContent = `
cd "${this.projectRoot}"
${command_string}
`;
      await fs.writeFile(scriptPath, scriptContent, { mode: 0o755 });
 
      // Determine shell (default to bash) and run as login shell (-l) to load profile
      const shell = process.env.SHELL || '/bin/bash';
      // Prepend cd to project root to ensure correct context before shell start
      const command = `cd "${this.projectRoot}" && ${shell} -l "${scriptPath}"`;
 
      const result = await execWithProcessGroupKill(command, {
        cwd: this.projectRoot,
        timeout: commandTimeout,
      });
 
      if (result.killed) {
        // Process was killed due to timeout
        unifiedOutput = `COMMAND TIMED OUT after ${commandTimeout}ms\n\nSTDOUT:\n${result.stdout || 'N/A'}\n\nSTDERR:\n${result.stderr || 'N/A'}`;
        summary = `Command "${command_string}" timed out after ${commandTimeout}ms.`;
        status = 'FAILURE';
        errorMessage = `Command timed out after ${commandTimeout}ms.`;
        this.logger.warn(`Command timed out: ${command_string}`);
      } else if (result.exitCode !== 0) {
        // Non-zero exit code
        unifiedOutput = `COMMAND FAILED with exit code ${result.exitCode}\n\nSTDOUT:\n${result.stdout || 'N/A'}\n\nSTDERR:\n${result.stderr || 'N/A'}`;
        summary = `Command "${command_string}" failed.`;
        status = 'FAILURE';
        errorMessage = `Command failed with exit code ${result.exitCode}.`;
        this.logger.error(`Command failed: ${unifiedOutput}`);
      } else {
        unifiedOutput =
          result.stdout || result.stderr || '(Command produced no output)';
        summary = `Command "${command_string}" executed.`;
      }
    } catch (error) {
      const execError = error as any;
      unifiedOutput = `COMMAND FAILED: ${execError.message}\n\nSTDOUT:\n${
        execError.stdout || 'N/A'
      }\n\nSTDERR:\n${execError.stderr || 'N/A'}`;
      summary = `Command "${command_string}" failed.`;
      status = 'FAILURE';
      errorMessage = execError.message;
      this.logger.error(`Error executing command: ${unifiedOutput}`);
    } finally {
      // Cleanup temp file
      await fs
        .unlink(scriptPath)
        .catch((err) =>
          this.logger.warn(
            `Failed to cleanup temp file ${scriptPath}: ${err.message}`,
          ),
        );
    }
 
    // Check token limit
    const tokenCount = countTokens(unifiedOutput);
    const tokenLimit =
      await this.applicationStateService.getEffectiveFollowupTokenLimit(
        _context.system_prompt_id,
      );
 
    Iif (tokenCount > tokenLimit) {
      // Truncate output proportionally
      const ratio = tokenLimit / tokenCount;
      const truncatedLength = Math.floor(unifiedOutput.length * ratio);
      const truncatedOutput = unifiedOutput.slice(0, truncatedLength);
 
      const truncationWarning = `\n\n[OUTPUT TRUNCATED: ${tokenCount} tokens exceeds limit of ${tokenLimit}. Consider redirecting large outputs to a file and using request_context to read it.]`;
 
      unifiedOutput = truncatedOutput + truncationWarning;
      errorMessage =
        (errorMessage || '') +
        `Output truncated due to size limit (${tokenCount} > ${tokenLimit} tokens).`;
 
      this.logger.warn(
        `Command output truncated: ${tokenCount} tokens exceeds limit of ${tokenLimit}`,
      );
    }
 
    return {
      status,
      summary: `${summary} Output captured.`,
      persisted_args: { command_string, timeout: commandTimeout },
      error_message: errorMessage,
      execution_log: {
        output: unifiedOutput,
        error_message: errorMessage || '',
      },
    };
  }
}