Class CommandFunctionTools
- All Implemented Interfaces:
FunctionTools
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
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionprivate static interfaceFunctional interface used for handling stream read failures.private static final classAuto-closeable wrapper forExecutorServiceso it can be used with try-with-resources.private static interfaceFunctional interface used for streaming output line processing. -
Field Summary
FieldsModifier and TypeFieldDescriptionprivate static final Stringprivate static final StringDefault character set used to decode process output streams.private static final StringDefault maximum number of characters to return from captured process output.private static final Stringprivate static final org.slf4j.LoggerLogger for shell tool execution and diagnostics.private intMaximum time to wait for a started process to complete, in seconds.private static final SecureRandomReusable random instance used for generating lightweight command ids for logging. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionexecuteCommand(String command, Map<String, String> properties, String dir, int tailResultSize, String charsetName, File projectDir, Configurator configurator) Executes a system command using Java's ProcessBuilder for controlled and secure execution.getLogMatches(String logId, String regexp, String charsetName) Searches a persisted command log for all substrings matching the supplied Java regular expression.getPreviousLogChunk(String logId, int tailResultSize, int currentTailOffset, String charsetName) Retrieves the chunk of previously captured command output that immediately precedes the current tail window.private voidreadStream(InputStream inputStream, String charsetName, LogBuilder output, CommandFunctionTools.LineConsumer lineConsumer, CommandFunctionTools.ErrorConsumer errorConsumer) Reads a process stream and appends its content tooutputwhile also passing each line to the provided consumer.resolveWorkingDir(File projectDir, String dir) Resolves a working directory relative to a canonical project directory.waitAndCollect(Process process, LogBuilder output, String logId) Waits for the specified process to complete execution within the configured timeout, collects its output, and returns a report of the captured output.
-
Field Details
-
LOG_FOLDER
- See Also:
-
logger
private static final org.slf4j.Logger loggerLogger for shell tool execution and diagnostics. -
CMD_LOG_PREFIX
- See Also:
-
DEFAULT_RESULT_TAIL_SIZE
Default maximum number of characters to return from captured process output.- See Also:
-
DEFAULT_CHARSET
Default character set used to decode process output streams.- See Also:
-
processTimeoutSeconds
private int processTimeoutSecondsMaximum time to wait for a started process to complete, in seconds. -
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 IOExceptionExecutes 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 substitutionproperties- optional environment variables for the child processdir- relative working directory withinprojectDirtailResultSize- maximum retained output sizecharsetName- character set used to decode process outputprojectDir- project root that bounds command executionconfigurator- 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
This method is exposed as an AI functional tool for paginating captured command output.logId. The returned substring starts atmax(0, currentTailOffset - tailResultSize)and ends atcurrentTailOffset.- Parameters:
logId- command log identifiertailResultSize- size of the preceding output fragmentcurrentTailOffset- offset at which the current tail beginscharsetName- 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 identifierregexp- Java regular expression used to find matchescharsetName- 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
Map<String,Object> waitAndCollect(Process process, LogBuilder output, String logId) throws InterruptedException, TimeoutException, ExecutionException 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 fromoutput- theLogBuilderused to capture and report process outputlogId- 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 waitingTimeoutException- if the process does not complete within the timeoutExecutionException- if an error occurs during output collection
-
resolveWorkingDir
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 directorydir- requested relative directory (or.)- Returns:
- resolved directory, or
nullif 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 tooutputwhile also passing each line to the provided consumer.- Parameters:
inputStream- process streamcharsetName- stream character setoutput- bounded output bufferlineConsumer- callback invoked for each line readerrorConsumer- callback invoked if reading fails
-