Class ActProcessor
AIFileProcessor.
An act is loaded from a TOML definition. Definitions may be bundled on the classpath under "/acts/", provided from a configured local/remote act location, or referenced directly as an explicit ".toml" file. Built-in and custom definitions can be merged, and definitions can inherit another definition through the "basedOn" property. Inherited string and prompt-list values may use "${super.value}" to splice the parent value into the overriding value.
Supported command and configuration markers include:
- ">" — shorthand prefix for an ad-hoc
taskact command. - "public.prompt" — property containing the user prompt visible to act templates.
- "default" — TOML section prefix for default property values that are applied when no explicit value exists.
- "#" — delimiter appended to an act name to select one or more episodes.
- "," — separator for multiple selected episode numbers.
- "!" — suffix for an episode selection that prevents subsequent normal-order episode execution.
- "/acts/" and ".toml" — classpath location prefix and file extension used for built-in act definitions.
- "basedOn" — property name used to declare act inheritance.
- "http://" and "https://" — the supported remote act-location prefixes; non-URL locations are resolved from the project root.
Examples
ActProcessor processor = new ActProcessor(projectDir, "openai:gpt-4o", configurator);
processor.setAct("help");
processor.process(projectLayout);
// Run an ad-hoc task using the shorthand marker.
processor.setAct("> summarize the project structure");
// Run only episodes 1 and 3 of an act, then stop without continuing normally.
processor.setAct("review#1,3! Check concurrency and error handling");
// Use external TOML acts from a local directory or HTTPS location.
processor.setActsLocation("acts");
processor.setAct("custom-review");
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final StringPrefix section designating default fallback values inside the loaded configurations.private static final String(package private) final ResourceBundleResource bundle supplying prompt templates for generators.Map holding the accumulated act configuration properties loaded for execution.static final StringClasspath base directory for built-in act definitions.private StringOptional directory containing external*.tomlact files.Cached automatically selected tools, keyed by act name and episode ID.static final StringKey used to denote inheritance by naming the base configuration to extend.static final StringShorthand command prefix indicating that the raw prompt should be interpreted and executed directly as a standard, ad-hoc agent task command.private booleanWhether normal sequential execution should be skipped after explicit episode processing.static final StringDivider symbol linking the base act name to an optional explicit subset of episodes.private final EpisodesThe episodes container managed by this processor.private static final PatternPre-compiled regex pattern to identify the first whitespace character in arguments.private static final StringProtocol prefix for standard unsecured HTTP endpoints.private static final StringProtocol prefix for secured HTTPS endpoints.static final StringTOML property name containing prompt inputs/episodes.static final StringTOML property name containing the instructions supplied to the AI provider for an act.private static final org.slf4j.LoggerLogger for documentation input processing events.static final StringProperty name representing the user prompt configured publicly inside the properties.List of collected outputs generated during processing.static final StringSeparator character used to delimit collection values like lists of files or episode indices.static final StringCharacter symbol that triggers immediate termination and disables normal order progression.static final StringPlaceholder string used in inherited act definitions to reference and include the parent's value.static final StringExpected file extension for configurations parsed as TOML files.private static final StringFields inherited from class org.machanism.machai.gw.processor.AIFileProcessor
CONTINUE_SPECIAL_PROMPT_COMMAND, ENABLED_TOOLS_PARAM_NAME, EXIT_SPECIAL_PROMPT_COMMAND, FILE_INCLUDED_MARKER, LOG_OUTPUT_PREFIX, PUBLIC_PROP_GROUP_NAMEFields inherited from class org.machanism.machai.project.ProjectProcessor
MACHAI_TEMP_DIR -
Constructor Summary
ConstructorsConstructorDescriptionActProcessor(File projectDir, String genai, Configurator configurator) Creates an act processor. -
Method Summary
Modifier and TypeMethodDescriptionvoidaddResults(String result) Appends a string result item to the execution list.(package private) voidapplyActData(Map<String, Object> properties) Applies loaded act data to this processor's configuration and runtime settings.private voidapplyDefaultValues(Map<String, Object> actData) Populates default properties from the act data, applying configurations and falling back to active configurator values when required.private voidapplyEpisodeSelection(String episodeSelection) Parses and registers specified episode boundaries from an argument string.private voidapplyPromptValues(String prompt, Map<String, Object> actData) Configures user prompt metadata, falling back to act-specified defaults if empty.private voidapplyStringActData(String key, String valueObj) Applies a single string property to processor state or configuration.private voidapplyStringProperty(String key, String value) Applies a resolved string property by dispatching to the matching processor setting.protected voidapplyTools(String instructions, String[] prompts, Genai provider, String[] tools) Applies the tools configured for an act episode, including automatic tool selection requested through the episode's YAML front matter.private static StringgetAbsolutePath(String name, String actsLocation, File rootDir) Resolves an act file path or URL from an act name and configured act source.Returns the merged act properties currently loaded on this processor.private String[]getAutoTools(String query, String instructions, String[] prompts) Selects and caches the tools required for the current act episode by asking the configured provider for a JSON tool list.private StringgetAutoToolSelectionQuery(String toolValue) Extracts the optional query from SnakeYAML's serializedautomapping value.private StringgetInputId(String[] prompts) Builds the cache key for an act episode from the execution metadata in the prompt.Returns the list of all collected outputs.private static booleanisAbsolute(String name) Determines whether the supplied act reference should be treated as an explicit TOML path.private booleanisAutoToolSelection(String toolValue) Determines whether a front-matter tool value requests automatic selection.static voidLoads an act definition into the provided map, supporting inheritance via thebasedOnproperty.private static org.tomlj.TomlParseResultloadActToml(String name) Loads and parses an act TOML document from a local file or remote URL.mergeStringWithListValue(List<String> mainValueList, String value, String key) Merges a single string value into each string item of an inherited list.mergeTomlArrayValues(Object existingValue, List<Object> values, String key) Merges TOML array values with any existing inherited string or list value.private Stringprocess(ProjectLayout projectLayout, File projectDir, String prompt, int episodeId) Executes a single episode prompt after prepending act metadata.protected voidprocessFile(ProjectLayout projectLayout, File file) Executes the act against a single file.protected voidprocessParentFiles(ProjectLayout projectLayout) Processes files and folders under the parent project directory (excluding modules).private static voidStores a string property, merging it with any inherited value already present.private StringresolveInheritedValue(String key, String value) Resolves a property value against the current configurator for inheritance.private static StringresolveMergedValue(List<String> mainValues, int index, String value) Resolves a merged value for an inherited prompt slot.resolvePromptValues(List<String> promptValues) Resolves inherited placeholders for each prompt episode.voidConfigures and initializes the current execution Action (Act) context by parsing the raw command string.(package private) static voidsetActData(Map<String, Object> properties, org.tomlj.TomlParseResult toml) Copies dotted-string keys from the TOML parse results intoproperties.private static voidApplies a single TOML entry to the merged act property map.voidsetActsLocation(String actsLocation) Sets the location used for loading external act definition files (*.toml).voidsetDisableNormalOrder(boolean disableNormalOrder) Enables or disables continuation with the default episode execution order.toStringList(Object existingValue) Converts an inherited property value to a list of strings.static org.tomlj.TomlParseResulttryLoadActFromClasspath(Map<String, Object> properties, String name) Attempts to load an act definition from classpath resources.static org.tomlj.TomlParseResulttryLoadActFromDirectory(Map<String, Object> properties, String name, String actsLocation, File rootDir) Attempts to load an act definition from a user-defined directory.Methods inherited from class org.machanism.machai.gw.processor.AIFileProcessor
addTool, getDefaultPrompt, getDirInfoLine, getInstructions, getModel, getProcessInfo, input, isInteractive, parseLines, parsePath, process, process, processFolder, readFromFilePath, readFromHttpUrl, removeFrontMatterData, scanDocuments, setDefaultPrompt, setInstructions, setInteractive, setModel, tryToGetFromReferenceMethods inherited from class org.machanism.machai.gw.processor.AbstractFileProcessor
addMatchingFile, getConfigurator, getExcludes, getModuleThreadTimeoutMinutes, getPath, getPathMatcher, getPatternPath, getRootDir, isModuleDir, isNonRecursive, isPathPattern, listFiles, listFiles, match, pathDepth, processModulesMultiThreaded, processProjectDir, scanFolder, setExcludes, setModuleThreadTimeoutMinutes, setNonRecursive, setPath, setPathMatcher, setThreads, shouldExcludePath, shouldIncludeInListFiles, shutdownExecutorMethods inherited from class org.machanism.machai.project.ProjectProcessor
getProjectLayout, processModule
-
Field Details
-
logger
private static final org.slf4j.Logger loggerLogger for documentation input processing events. -
TOOL_AUTO_SEARCH_NAME
- See Also:
-
actBundle
Resource bundle supplying prompt templates for generators. -
ACT_EXECUTION_INFORMATION_PREFIX
- See Also:
-
DEFAULT_TASK_MARKER
Shorthand command prefix indicating that the raw prompt should be interpreted and executed directly as a standard, ad-hoc agent task command.When the input command begins with this marker, the runtime automatically expands the shorthand into a fully-qualified task command (e.g.,
> run buildis processed astask run build).- See Also:
-
SUPER_VALUE_PLACEHOLDER
Placeholder string used in inherited act definitions to reference and include the parent's value.- See Also:
-
PUBLIC_USER_PROMPT_PROP_NAME
Property name representing the user prompt configured publicly inside the properties.- See Also:
-
ACT_DEFAULT_PROPS_SECTION_NAME
Prefix section designating default fallback values inside the loaded configurations.- See Also:
-
STOP_SYMBOL
Character symbol that triggers immediate termination and disables normal order progression.- See Also:
-
SEPARATOR_CHARS
Separator character used to delimit collection values like lists of files or episode indices.- See Also:
-
EPISODE_DELIMETER
Divider symbol linking the base act name to an optional explicit subset of episodes.- See Also:
-
ACTS_BASENAME_PREFIX
Classpath base directory for built-in act definitions.- See Also:
-
TOML_EXTENSION
Expected file extension for configurations parsed as TOML files.- See Also:
-
BASED_ON_PROPERTY_NAME
Key used to denote inheritance by naming the base configuration to extend.- See Also:
-
FIRST_WHITESPACE
Pre-compiled regex pattern to identify the first whitespace character in arguments. -
HTTP_PREFIX
Protocol prefix for standard unsecured HTTP endpoints.- See Also:
-
HTTPS_PREFIX
Protocol prefix for secured HTTPS endpoints.- See Also:
-
actsLocation
Optional directory containing external*.tomlact files. -
episodes
The episodes container managed by this processor. -
disableNormalOrder
private boolean disableNormalOrderWhether normal sequential execution should be skipped after explicit episode processing. -
results
List of collected outputs generated during processing. -
actProperties
Map holding the accumulated act configuration properties loaded for execution. -
autoToolsMap
Cached automatically selected tools, keyed by act name and episode ID. -
INSTRUCTIONS_PROPERTY_NAME
TOML property name containing the instructions supplied to the AI provider for an act.- See Also:
-
INPUTS_PROPERTY_NAME
TOML property name containing prompt inputs/episodes.- See Also:
-
-
Constructor Details
-
ActProcessor
Creates an act processor.- Parameters:
projectDir- root directory used as a base for relative pathsgenai- provider key/name (including model)configurator- configuration source
-
-
Method Details
-
setAct
Configures and initializes the current execution Action (Act) context by parsing the raw command string.This method orchestrates the early stage lifecycle of an action. It handles:
- Task Shorthand Expansion: Converting shortcut inputs (beginning
with
DEFAULT_TASK_MARKER) into standard task instructions. - Fallback Fallback Defaults: Defaulting blank actions to
"help". - Token/Argument Extraction: Parsing the action name (first contiguous word) and separating it from any trailing, inline text prompt.
- Episode Slicing: Extracting targeted sub-episode qualifiers
appended via the
EPISODE_DELIMETER(e.g.,my-act#2). - Property Binding: Loading the action files, applying schema defaults, binding prompt argument placeholders, and configuring the target LLM runner model if overridden.
Example Parse Formats
"> build-docs"expands to"task build-docs""bindex/java/mvn-project"runs the full 'bindex/java/mvn-project' action using the default prompt"bindex/java/mvn-project#2"runs only the 2nd episode of the 'bindex/java/mvn-project' action"bindex/java/mvn-project -Dkey=val"runs 'bindex/java/mvn-project' and extracts the arguments intoactProperties
- Parameters:
act- the raw command or action string to parse and execute (e.g.,"task run",">add javadoc","bindex/java/mvn-project#2! use -DskipTests=true")- Throws:
IOException- if an error occurs while loading the action definitions from the target storage location
- Task Shorthand Expansion: Converting shortcut inputs (beginning
with
-
applyDefaultValues
Populates default properties from the act data, applying configurations and falling back to active configurator values when required.- Parameters:
actData- the act data map containing raw values
-
applyPromptValues
Configures user prompt metadata, falling back to act-specified defaults if empty.- Parameters:
prompt- the raw prompt to applyactData- target act properties map
-
applyEpisodeSelection
Parses and registers specified episode boundaries from an argument string.- Parameters:
episodeSelection- boundary definitions containing index selectors and flags
-
setDisableNormalOrder
public void setDisableNormalOrder(boolean disableNormalOrder) Enables or disables continuation with the default episode execution order.- Parameters:
disableNormalOrder-trueto stop after requested episodes,falseto continue with normal order
-
loadAct
public static void loadAct(String name, Map<String, Object> properties, String actsLocation, File rootDir) throws IOExceptionLoads an act definition into the provided map, supporting inheritance via thebasedOnproperty.This method attempts to load the specified act from both a user-defined directory (custom act) and the built-in classpath resources. If both are present, the custom act wraps (overrides) the built-in act, allowing for extension or modification of base act behavior.
If the act specifies a
basedOnproperty, the parent act is loaded first (recursively), and its properties are merged. The child act's properties then override or extend the parent.- Parameters:
name- the name of the act to load (without the.tomlextension)properties- destination map to populate with parsed act propertiesactsLocation- optional directory containing user-defined (custom) act files; may benullrootDir- project root used to resolve relative act locations- Throws:
IOException- if reading act content failsIllegalArgumentException- if the specified act cannot be found in either location
-
tryLoadActFromClasspath
public static org.tomlj.TomlParseResult tryLoadActFromClasspath(Map<String, Object> properties, String name) throws IOExceptionAttempts to load an act definition from classpath resources.- Parameters:
properties- destination for parsed dotted propertiesname- act name (without.toml)- Returns:
- parsed TOML results, or
nullwhen the act is not found - Throws:
IOException- if the resource cannot be read
-
tryLoadActFromDirectory
public static org.tomlj.TomlParseResult tryLoadActFromDirectory(Map<String, Object> properties, String name, String actsLocation, File rootDir) throws IOExceptionAttempts to load an act definition from a user-defined directory.- Parameters:
properties- destination for parsed dotted propertiesname- act name (without.toml)actsLocation- directory containing*.tomlact files (may benull)rootDir- project root used to resolve relative act locations- Returns:
- parsed TOML results, or
nullwhen not found - Throws:
IOException- if the file cannot be read
-
getAbsolutePath
private static String getAbsolutePath(String name, String actsLocation, File rootDir) throws IOException Resolves an act file path or URL from an act name and configured act source.- Parameters:
name- act name or file pathactsLocation- base directory or URL for act definitionsrootDir- project root used to resolve relative act locations- Returns:
- absolute file path or URL string
- Throws:
IOException- if an explicitly referenced local act file does not exist
-
loadActToml
Loads and parses an act TOML document from a local file or remote URL.- Parameters:
name- absolute file path or URL to the TOML resource- Returns:
- parsed TOML results, or
nullif a local file path does not exist - Throws:
IOException- if reading the TOML resource fails
-
isAbsolute
Determines whether the supplied act reference should be treated as an explicit TOML path.- Parameters:
name- act reference to inspect- Returns:
trueif the reference already ends with.toml
-
setActData
Copies dotted-string keys from the TOML parse results intoproperties.If a key already exists in
properties, the new value is formatted into the old value usingString.format(String, Object...).- Parameters:
properties- properties destinationtoml- TOML parse results
-
setActDataEntry
Applies a single TOML entry to the merged act property map.- Parameters:
properties- destination property mapentry- TOML entry to process
-
putStringActData
Stores a string property, merging it with any inherited value already present.- Parameters:
properties- destination property mapkey- property namevalue- property value from the current act
-
mergeStringWithListValue
private static List<String> mergeStringWithListValue(List<String> mainValueList, String value, String key) Merges a single string value into each string item of an inherited list.- Parameters:
mainValueList- inherited list valuevalue- string value to merge throughSUPER_VALUE_PLACEHOLDERkey- property name whose values are being merged- Returns:
- merged list results
-
mergeTomlArrayValues
private static List<String> mergeTomlArrayValues(Object existingValue, List<Object> values, String key) Merges TOML array values with any existing inherited string or list value.- Parameters:
existingValue- existing property value, if anyvalues- TOML array values from the current actkey- property name whose values are being merged- Returns:
- merged string list
-
toStringList
Converts an inherited property value to a list of strings.- Parameters:
existingValue- existing property value- Returns:
- list representation of the value, or an empty list if unsupported
-
resolveMergedValue
Resolves a merged value for an inherited prompt slot.- Parameters:
mainValues- inherited valuesindex- current positionvalue- overriding value for the position- Returns:
- merged value for the position
-
applyActData
Applies loaded act data to this processor's configuration and runtime settings.- Parameters:
properties- properties loaded from TOML acts
-
applyStringActData
Applies a single string property to processor state or configuration.- Parameters:
key- property namevalueObj- property value as an Object
-
resolveInheritedValue
Resolves a property value against the current configurator for inheritance.- Parameters:
key- property namevalue- act-defined value that may containSUPER_VALUE_PLACEHOLDER- Returns:
- resolved property value
-
applyStringProperty
Applies a resolved string property by dispatching to the matching processor setting.- Parameters:
key- property namevalue- resolved property value
-
resolvePromptValues
Resolves inherited placeholders for each prompt episode.- Parameters:
promptValues- prompt values to resolve- Returns:
- resolved prompt list
-
setActsLocation
Sets the location used for loading external act definition files (*.toml).The location may be specified as:
- An absolute path — used as-is (e.g.,
/opt/gw/acts). - A relative path — resolved against the root directory.
- A URL — any value starting with
http://orhttps://, in which case acts are loaded remotely and no local directory validation is performed.
A
nullvalue is ignored and leaves the current setting unchanged.- Parameters:
actsLocation- absolute path, relative path, or URL pointing to the directory (or remote source) containing act files;nullto leave the current value unchanged- Throws:
IllegalArgumentException- ifactsLocationis a non-URL path that does not resolve to an existing directory
- An absolute path — used as-is (e.g.,
-
processParentFiles
Processes files and folders under the parent project directory (excluding modules).- Overrides:
processParentFilesin classAbstractFileProcessor- Parameters:
projectLayout- active project layout metadata context to process- Throws:
IOException- if scanning or executing templates fails
-
process
Executes a single episode prompt after prepending act metadata.- Parameters:
projectLayout- active project layoutprojectDir- file or directory being processedprompt- episode prompt textepisodeId- zero-based episode index- Returns:
- provider results string, if any
-
applyTools
Applies the tools configured for an act episode, including automatic tool selection requested through the episode's YAML front matter.Set
enabledTools: autoto have a separate provider request select the applicable tools from the episode instructions and prompt. The selected tool names are cached for the act episode, then registered on the provider for the actual request. For example:--- enabledTools: auto --- Review this module and use only the tools needed for the task.A YAML mapping can give the automatic selector additional constraints. Its
autovalue is passed to the selector as a query; it guides selection rather than directly disabling tools. For example:--- enabledTools: auto: Don't use web access and system command tools. --- Analyze the local implementation.Any other
enabledToolsvalue is delegated unchanged to the standard tool-registration behavior.- Overrides:
applyToolsin classAIFileProcessor- Parameters:
instructions- resolved system instructions for the episodeprompts- resolved prompt parts, including episode metadataprovider- provider that receives the selected toolstools- configured tool names or automatic-selection marker
-
isAutoToolSelection
Determines whether a front-matter tool value requests automatic selection.- Parameters:
toolValue- serialized scalar or YAML mapping value- Returns:
truewhen the value isautoor anautomapping
-
getAutoToolSelectionQuery
Extracts the optional query from SnakeYAML's serializedautomapping value.- Parameters:
toolValue- serialized scalar or YAML mapping value- Returns:
- query text, or an empty string for a plain
automarker
-
getAutoTools
Selects and caches the tools required for the current act episode by asking the configured provider for a JSON tool list.- Parameters:
instructions- provider instructions; retained for the selection contextquery-prompts- prompt parts containing act execution metadata and the episode prompt- Returns:
- selected tool names, or
nullwhen selection fails - Throws:
IllegalArgumentException- if the provider returns malformed JSON
-
getInputId
private String getInputId(String[] prompts) throws com.fasterxml.jackson.core.JsonProcessingException Builds the cache key for an act episode from the execution metadata in the prompt.- Parameters:
prompts- prompt parts containing serialized act execution metadata- Returns:
- cache key composed of the act name and current episode ID
- Throws:
com.fasterxml.jackson.core.JsonProcessingException- if the execution metadata is not valid JSON
-
processFile
Executes the act against a single file.- Overrides:
processFilein classAbstractFileProcessor- Parameters:
projectLayout- project layoutfile- file to process- Throws:
IOException- if provider execution fails
-
addResults
Appends a string result item to the execution list.- Parameters:
result- result message or payload to record
-
getResults
Returns the list of all collected outputs.- Returns:
- the collected list of run outputs
-
getActProperties
Returns the merged act properties currently loaded on this processor.- Returns:
- the act properties map
-