Class CommandFunctionTools
- All Implemented Interfaces:
FunctionTools
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:
- A deny-list heuristic check via
CommandSecurityChecker - Project-root confinement for the working directory (see
resolveWorkingDir(File, String))
Installed tools
run_command_line_tool– executes a command line and returns outputterminate_process– aborts execution by throwing aProcessTerminationException
- Author:
- Viktor Tovstyi
-
Field Summary
Fields -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoidapplyTools(Genai provider) Registers system command and process control tools with the providedGenai.Completes the current task by throwing aEndTaskExceptionexception.executeCommand(com.fasterxml.jackson.databind.JsonNode props, File projectDir) Implements therun_command_line_tooltool.getCommandLogMatches(com.fasterxml.jackson.databind.JsonNode props, File projectDir) Searches a persisted command log for all substrings matching the supplied Java regular expression.getPreviousLogChunk(com.fasterxml.jackson.databind.JsonNode props, File projectDir) Retrieves the chunk of previously captured command output that immediately precedes the current tail window.parseEnv(String envString, Configurator conf) Parses theenvparameter string into a map of environment variables.static Stringreplace(String value, Configurator conf) Resolves ${...} placeholders using the provided configurator.resolveWorkingDir(File projectDir, String dir) Resolves a working directory relative to a canonical project directory.voidsetConfigurator(Configurator configurator) Configures this tool set with the shared application configurator and initializes the command security checker.terminateExecution(com.fasterxml.jackson.databind.JsonNode props, File projectDir) Implements theterminate_tasktool.(package private) StringwaitAndCollect(Process process, Future<?> stdoutFuture, Future<?> stderrFuture, LimitedStringBuilder output, String commandId) Waits for the process to finish (up toprocessTimeoutSeconds) and then returns collected output.
-
Field Details
-
TASK_TERMINATED_BY_FUNCTION_TOOL_MESSAGE
- See Also:
-
-
Constructor Details
-
CommandFunctionTools
public CommandFunctionTools()
-
-
Method Details
-
applyTools
Registers system command and process control tools with the providedGenai.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=VALUEpairs 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:
applyToolsin interfaceFunctionTools- Parameters:
provider- the provider instance to which tools will be registered
- run_command_line_tool – Executes a system command using Java's
-
terminateExecution
Implements theterminate_tasktool.Reads
message,cause, andexitCodefrom the suppliedJsonNodeand throws aProcessTerminationException. This mechanism allows a tool invocation to abort the overall workflow with an explicit exit code.- Parameters:
params- tool invocation parameters (expects a singleJsonNodeargument)- Returns:
- never returns; always throws
- Throws:
ProcessTerminationException- always thrown to terminate execution
-
endTask
Completes the current task by throwing aEndTaskExceptionexception.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 therun_command_line_tooltool.Expected parameters:
JsonNodecontainingcommandand optional settingsFileproject 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 atmax(0, currentTailOffset - tailResultSize)and ends atcurrentTailOffset, after being clamped to the available log length.- Parameters:
props- tool arguments containingcommandId,tailResultSize,currentTailOffset, and an optionalcharsetNameprojectDir- 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
Searches a persisted command log for all substrings matching the supplied Java regular expression.- Parameters:
props- tool arguments containingcommandId,regexp, and an optionalcharsetNameprojectDir- 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 toprocessTimeoutSeconds) 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 observedstdoutFuture- future representing the stdout reader taskstderrFuture- future representing the stderr reader taskoutput- bounded output buffercommandId- id used for log correlation- Returns:
- collected output, followed by an exit-code line
- Throws:
InterruptedException- if the current thread is interrupted while waitingTimeoutException- if collecting output times outExecutionException- if a reader task fails
-
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
-
parseEnv
Parses theenvparameter 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 stringconf-- Returns:
- parsed environment variables
-
setConfigurator
Configures this tool set with the shared application configurator and initializes the command security checker.- Specified by:
setConfiguratorin interfaceFunctionTools- Parameters:
configurator- configuration source used by command and environment processing
-
replace
Resolves ${...} placeholders using the provided configurator.Unresolvable placeholders are left as-is.
- Parameters:
value- raw value that may contain placeholdersconf- configurator used for lookup; ifnull, the value is returned unchanged- Returns:
- resolved value
-