Class CommandFunctionTools

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

public class CommandFunctionTools extends Object implements FunctionTools
Installs command-execution and process-termination tools into a Genai.

The installed tools provide a controlled wrapper around ProcessBuilder to execute a host command line within a validated working directory and capture both stdout and stderr into a bounded buffer (see LimitedStringBuilder).

Security model

Command execution is intended to be restricted by the host application. This implementation supports:

Installed tools

  • run_command_line_tool – executes a command line and returns output
  • terminate_process – aborts execution by throwing a ProcessTerminationException
Author:
Viktor Tovstyi
  • Field Details

    • TASK_TERMINATED_BY_FUNCTION_TOOL_MESSAGE

      static final String TASK_TERMINATED_BY_FUNCTION_TOOL_MESSAGE
      See Also:
  • Constructor Details

    • CommandFunctionTools

      public CommandFunctionTools()
  • Method Details

    • applyTools

      public void applyTools(Genai provider)
      Registers system command and process control tools with the provided Genai.

      The following tools are installed:

      • run_command_line_tool – Executes a system command using Java's ProcessBuilder.
        Parameters:
        • command (string, required): The command to execute.
        • env (string, optional): Environment variables as NAME=VALUE pairs separated by newline characters (\n).
        • dir (string, optional): Working directory relative to the project directory; defaults to ..
        • tailResultSize (integer, optional): Maximum number of characters to return from captured output; defaults to DEFAULT_RESULT_TAIL_SIZE.
        • charsetName (string, optional): Character set used to decode process output; defaults to DEFAULT_CHARSET.
      • terminate_process – Throws an exception to immediately terminate execution.
        Parameters:
        • message (string, optional): Exception message; defaults to "Process terminated by function tool."
        • cause (string, optional): Optional cause message; wrapped in an Exception.
        • exitCode (integer, optional): Exit code; defaults to 0.
      Specified by:
      applyTools in interface FunctionTools
      Parameters:
      provider - the provider instance to which tools will be registered
    • terminateExecution

      public String terminateExecution(com.fasterxml.jackson.databind.JsonNode props, File projectDir)
      Implements the terminate_task tool.

      Reads message, cause, and exitCode from the supplied JsonNode and throws a ProcessTerminationException. This mechanism allows a tool invocation to abort the overall workflow with an explicit exit code.

      Parameters:
      params - tool invocation parameters (expects a single JsonNode argument)
      Returns:
      never returns; always throws
      Throws:
      ProcessTerminationException - always thrown to terminate execution
    • endTask

      public String endTask(com.fasterxml.jackson.databind.JsonNode props, File projectDir)
      Completes the current task by throwing a EndTaskException exception.

      This method is intended to be used as a function tool for terminating a process when requested by the user or dictated by process logic. It logs the task completion and uses a custom message if provided in the properties.

      Parameters:
      props - JSON node containing optional properties, such as a custom completion message.
      projectDir - The project directory associated with the task.
      Returns:
      This method does not return normally; it always throws EndTaskException.
      Throws:
      EndTaskException - Always thrown to signal task completion.
    • executeCommand

      public String executeCommand(com.fasterxml.jackson.databind.JsonNode props, File projectDir) throws IOException
      Implements the run_command_line_tool tool.

      Expected parameters:

      1. JsonNode containing command and optional settings
      2. File project working directory supplied by the provider runtime
      Parameters:
      params - tool arguments
      Returns:
      command output bounded to the configured tail size
      Throws:
      IOException - if the task cannot be started or I/O occurs while resolving paths
    • getPreviousLogChunk

      public Object getPreviousLogChunk(com.fasterxml.jackson.databind.JsonNode props, File projectDir) 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 commandId. The returned substring starts at max(0, currentTailOffset - tailResultSize) and ends at currentTailOffset, after being clamped to the available log length.

      Parameters:
      props - tool arguments containing commandId, tailResultSize, currentTailOffset, and an optional charsetName
      projectDir - project root directory used to resolve the command log file
      Returns:
      the previous log chunk, or an empty string if no earlier chunk exists
      Throws:
      IOException - if the command log path cannot be resolved
    • getCommandLogMatches

      public Object getCommandLogMatches(com.fasterxml.jackson.databind.JsonNode props, File projectDir)
      Searches a persisted command log for all substrings matching the supplied Java regular expression.
      Parameters:
      props - tool arguments containing commandId, regexp, and an optional charsetName
      projectDir - project root directory used to resolve the command log file
      Returns:
      a list of match descriptors, each containing the matched text, start and end offsets within the line, and the zero-based line number
      Throws:
      IllegalArgumentException - if required parameters are missing or the log file does not exist
    • waitAndCollect

      String waitAndCollect(Process process, Future<?> stdoutFuture, Future<?> stderrFuture, LimitedStringBuilder output, String commandId) throws InterruptedException, TimeoutException, ExecutionException
      Waits for the process to finish (up to processTimeoutSeconds) and then returns collected output.

      This method also waits briefly for stdout/stderr reader tasks to complete so that output is not lost.

      Parameters:
      process - process being observed
      stdoutFuture - future representing the stdout reader task
      stderrFuture - future representing the stderr reader task
      output - bounded output buffer
      commandId - id used for log correlation
      Returns:
      collected output, followed by an exit-code line
      Throws:
      InterruptedException - if the current thread is interrupted while waiting
      TimeoutException - if collecting output times out
      ExecutionException - if a reader task fails
    • 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
    • parseEnv

      public static Map<String,String> parseEnv(String envString, Configurator conf)
      Parses the env parameter string into a map of environment variables.

      Lines are separated by \n (or \n); empty lines and lines starting with # are ignored.

      Parameters:
      envString - environment string
      conf -
      Returns:
      parsed environment variables
    • setConfigurator

      public void setConfigurator(Configurator configurator)
      Configures this tool set with the shared application configurator and initializes the command security checker.
      Specified by:
      setConfigurator in interface FunctionTools
      Parameters:
      configurator - configuration source used by command and environment processing
    • replace

      public static String replace(String value, Configurator conf)
      Resolves ${...} placeholders using the provided configurator.

      Unresolvable placeholders are left as-is.

      Parameters:
      value - raw value that may contain placeholders
      conf - configurator used for lookup; if null, the value is returned unchanged
      Returns:
      resolved value