Class CommandFunctionTools

java.lang.Object
org.machanism.machai.gw.tools.CommandFunctionTools
All Implemented Interfaces:
FunctionTools

public class CommandFunctionTools extends Object implements FunctionTools
Provides function tools for executing and managing system commands within a project context.

This class exposes methods for:

  • Securely executing system commands with controlled environment variables, working directory, output tailing, and character encoding
  • Retrieving and searching command execution logs, including paginated log chunks and regular expression matches
  • Resolving working directories and securely handling command input/output
  • Replacing placeholders in command strings using project configuration

All command execution is subject to security checks and is logged for diagnostics. Output is captured and can be retrieved or searched after execution.

Methods in this class are typically invoked by an AI provider or workflow engine to enable dynamic, tool-augmented project automation.

Author:
Viktor Tovstyi
  • Field Details

    • LOG_FOLDER

      private static final String LOG_FOLDER
      See Also:
    • logger

      private static final org.slf4j.Logger logger
      Logger for shell tool execution and diagnostics.
    • CMD_LOG_PREFIX

      private static final String CMD_LOG_PREFIX
      See Also:
    • DEFAULT_RESULT_TAIL_SIZE

      private static final String DEFAULT_RESULT_TAIL_SIZE
      Default maximum number of characters to return from captured process output.
      See Also:
    • DEFAULT_CHARSET

      private static final String DEFAULT_CHARSET
      Default character set used to decode process output streams.
      See Also:
    • processTimeoutSeconds

      private int processTimeoutSeconds
      Maximum time to wait for a started process to complete, in seconds.
    • RANDOM

      private static final SecureRandom RANDOM
      Reusable random instance used for generating lightweight command ids for logging.
  • Constructor Details

    • CommandFunctionTools

      public CommandFunctionTools()
  • Method Details

    • executeCommand

      public Object executeCommand(String command, Map<String,String> properties, String dir, int tailResultSize, String charsetName, File projectDir, Configurator configurator) throws IOException
      Executes a system command using Java's ProcessBuilder for controlled and secure execution.

      Only explicitly allowed commands can be executed for security reasons. Supports setting environment variables, working directory, output tail size, and character encoding. This method is exposed as an AI functional tool for controlled system-command execution.

      Parameters:
      command - command line to execute after configuration substitution
      properties - optional environment variables for the child process
      dir - relative working directory within projectDir
      tailResultSize - maximum retained output size
      charsetName - character set used to decode process output
      projectDir - project root that bounds command execution
      configurator - configuration used for substitutions and security rules
      Returns:
      command execution report, or an error message for an invalid directory
      Throws:
      IOException - if the process cannot be started or its output cannot be collected
    • getPreviousLogChunk

      public Object getPreviousLogChunk(String logId, int tailResultSize, int currentTailOffset, String charsetName) throws IOException
      Retrieves the chunk of previously captured command output that immediately precedes the current tail window.

      The command output is read from the persisted log file associated with the supplied logId. The returned substring starts at max(0, currentTailOffset - tailResultSize) and ends at currentTailOffset.

      This method is exposed as an AI functional tool for paginating captured command output.
      Parameters:
      logId - command log identifier
      tailResultSize - size of the preceding output fragment
      currentTailOffset - offset at which the current tail begins
      charsetName - character set used to decode the log
      Returns:
      the requested preceding log fragment
      Throws:
      IOException - if the log cannot be found or read
    • getLogMatches

      public Object getLogMatches(String logId, String regexp, String charsetName) throws FileNotFoundException
      Searches a persisted command log for all substrings matching the supplied Java regular expression. This method is exposed as an AI functional tool for searching captured command output.
      Parameters:
      logId - command log identifier
      regexp - Java regular expression used to find matches
      charsetName - character set used to decode the log
      Returns:
      a list of matching text segments and their positions
      Throws:
      FileNotFoundException - if the command log does not exist
    • waitAndCollect

      Waits for the specified process to complete execution within the configured timeout, collects its output, and returns a report of the captured output.

      If the process does not finish within processTimeoutSeconds, it is forcibly terminated, and a timeout message is appended to the output. The method then returns the collected output as a report.

      Parameters:
      process - the process to wait for and collect output from
      output - the LogBuilder used to capture and report process output
      logId - the identifier used for log correlation
      Returns:
      a map containing the collected output and related information
      Throws:
      InterruptedException - if the current thread is interrupted while waiting
      TimeoutException - if the process does not complete within the timeout
      ExecutionException - if an error occurs during output collection
    • resolveWorkingDir

      public File resolveWorkingDir(File projectDir, String dir)
      Resolves a working directory relative to a canonical project directory.

      Absolute paths are rejected and attempts to traverse outside the project directory are blocked.

      Parameters:
      projectDir - canonical project directory
      dir - requested relative directory (or .)
      Returns:
      resolved directory, or null if invalid
    • readStream

      private void readStream(InputStream inputStream, String charsetName, LogBuilder output, CommandFunctionTools.LineConsumer lineConsumer, CommandFunctionTools.ErrorConsumer errorConsumer)
      Reads a process stream and appends its content to output while also passing each line to the provided consumer.
      Parameters:
      inputStream - process stream
      charsetName - stream character set
      output - bounded output buffer
      lineConsumer - callback invoked for each line read
      errorConsumer - callback invoked if reading fails