Class AIFileProcessor
- Direct Known Subclasses:
ActProcessor,GuidanceProcessor
Genai provider with
project-aware context, prompt metadata, optional external prompt inclusions,
public configuration substitution, and function-tool registration.
The processor can handle a single file, a project folder, or a path/pattern
scan. Before a prompt is sent to the provider it is normalized, include
markers are resolved recursively, public configuration placeholders are
substituted, project layout details are stored for project-context tools, and
processing metadata is supplied to the provider as JSON. The processing
metadata is generated by getProcessInfo(ProjectLayout, File) and
includes the processed file's project-relative path, the interactive or
non-interactive processing mode, and the operating-system name. This metadata
is serialized as JSON and is supplied as provider context so tools and model
prompts can identify the file and execution environment being processed.
Supported special markers and parameters
FILE_INCLUDED_MARKER: a line prefix used to include UTF-8 content fromhttp://,https://, orfile://references. Included content is parsed again, so includes may be nested.EXIT_SPECIAL_PROMPT_COMMAND: in interactive mode, entering this command exits processing successfully.CONTINUE_SPECIAL_PROMPT_COMMAND: in interactive mode, entering this command accepts the current provider response and continues without another provider prompt.ENABLED_TOOLS_PARAM_NAME: YAML front-matter property used to limit the provider tools enabled for the current prompt.PUBLIC_PROP_GROUP_NAME: configuration-property prefix whose values are exposed for substitution in prompts, for example${public.projectName}.
Supported prompt input parameters
Prompts may start with YAML front matter delimited by ---. Supported
properties include gw.model, which overrides the configured provider
or model for the prompt, and enabledTools, which may be either a
scalar or a YAML list naming tools to enable. String values in the metadata
are resolved with the active configurator before use.
Examples
AIFileProcessor processor = new AIFileProcessor(rootDir, configurator, "openai:gpt-4.1");
processor.setInstructions("Follow the project coding standards.");
processor.setDefaultPrompt(">>> file://docs/review-prompt.md\nReview the project.");
processor.processFolder(projectLayout);
---
gw.model: ${public.reviewModel}
enabledTools:
- get_project_context_variable
- read_file
---
Analyze ${public.projectName} and use
```
>>> file://docs/checklist.md
```
as checklist input.
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final StringInteractive-mode command that accepts the current response and continues processing without sending another prompt to the provider.private StringDefault fallback prompt used to process directories or projects when no specific file prompt is given.static final StringParameter name used to configure the list of tool definitions exposed to the LLM agent during an episode.static final StringInteractive-mode command that terminates processing immediately by throwing aProcessTerminationExceptionwith exit code0.static final StringPrefix marker for prompt lines that include external content.private static final Stringprivate List<FunctionTools>Collection of user-configured function tools that are registered with and made available to the AI provider.private static FunctionToolsLoaderLoader utility responsible for discovering, instantiating, and applying functional tools to the AI provider.private StringBase instructions that set the persona, tone, and scope for the AI provider during execution.private booleanFlag indicating whether interactive mode is active, allowing continuous prompt looping and execution.static final StringThe format pattern used to prepend logger output blocks when reporting responses generated by the AI provider.private static final org.slf4j.Loggerprivate StringThe specific AI model identifier or provider label being utilized for operations.private static final StringInteractive-mode command that accepts the current response and continues processing in a non-interactive mode, running to completion without prompting the user again.static final String[]Prefix for property groups whose values are exposed and injectable directly into prompt templates.Fields inherited from class org.machanism.machai.project.ProjectProcessor
MACHAI_TEMP_DIR -
Constructor Summary
ConstructorsConstructorDescriptionAIFileProcessor(File rootDir, Configurator configurator, String genai) Creates a processor for the given project directory and AI provider identifier. -
Method Summary
Modifier and TypeMethodDescriptionvoidaddTool(FunctionTools toolFunction) Adds a tool definition that will be exposed to the AI provider.protected voidapplyTools(String instructions, String[] prompts, Genai provider, String[] tools) Registers the selected discovered tools and the tools explicitly added to this processor with the provider for the current request.private StringextractInputParams(String prompt, Map<String, Object> inputProps) Extracts supported YAML front-matter input parameters from the beginning of a prompt.Returns the default prompt used for folder processing.(package private) com.fasterxml.jackson.databind.node.ArrayNodegetDirInfoLine(Collection<String> sources, File projectDir) Returns a JsonNode (ArrayNode) containing the names of directories from the given collection that exist within the specified project directory.private String[]getEnabledTools(Map<String, Object> inputProps, LayeredConfigurator conf) Resolves the tool names enabled for the current processing request.Returns the current base instructions used for processing.getModel()Returns the configured AI model or provider identifier.getProcessInfo(ProjectLayout projectLayout, File file) Generates a structured JSON string containing execution metadata about the file being processed and the current processing environment context.protected Stringinput()Obtains the next input from an interactive user session.booleanIndicates whether interactive processing mode is enabled.parseLines(String data, File projectDir, Configurator conf) Normalizes multi-line input and resolves supported line references such as HTTP URLs andfile:references.(package private) StringResolves the effective scan directory and converts it into a glob expression when required.private Stringprocess(ProjectLayout projectLayout, File file, String prompt) Processes the given file using the currently configured instructions.protected Stringprocess(ProjectLayout projectLayout, File file, String instructions, String... prompts) Processes a specified file within a project layout by configuring and invoking a Generative AI (GenAI) provider using a sequence of instructions and prompts.voidprocessFolder(ProjectLayout projectLayout) Processes the project root folder using the configured default prompt.(package private) StringreadFromFilePath(String filePath, File projectDir) Reads UTF-8 text content from the given file path.(package private) static StringreadFromHttpUrl(String urlString) Reads UTF-8 text content from the given HTTP or HTTPS URL.(package private) static StringremoveFrontMatterData(String prompt) private ObjectresolveInputParamValue(Object value) voidscanDocuments(File projectDir, String path) Configures scanning based on the provided directory or path pattern and then starts scanning the project folder.voidsetDefaultPrompt(String defaultPrompt) Sets the default prompt used for folder processing.voidsetInstructions(String instructions) Sets the base instructions used for processing after normalizing line content and resolving supported references.voidsetInteractive(boolean interactive) Enables or disables interactive processing mode.voidSets the AI model or provider identifier.private voidsetProjectLayoutContext(ProjectLayout projectLayout) Extracts context metadata from the providedProjectLayoutand registers it in the project context registry.(package private) StringtryToGetFromReference(String data, File projectDir, Configurator conf) Resolves a single instruction line that may point to external content.Methods inherited from class org.machanism.machai.gw.processor.AbstractFileProcessor
addMatchingFile, getConfigurator, getExcludes, getModuleThreadTimeoutMinutes, getPath, getPathMatcher, getPatternPath, getRootDir, isModuleDir, isNonRecursive, isPathPattern, listFiles, listFiles, match, pathDepth, processFile, processModulesMultiThreaded, processParentFiles, processProjectDir, scanFolder, setExcludes, setModuleThreadTimeoutMinutes, setNonRecursive, setPath, setPathMatcher, setThreads, shouldExcludePath, shouldIncludeInListFiles, shutdownExecutorMethods inherited from class org.machanism.machai.project.ProjectProcessor
getProjectLayout, processModule
-
Field Details
-
FRONT_MATTER_MARKER
- See Also:
-
logger
private static final org.slf4j.Logger logger -
ENABLED_TOOLS_PARAM_NAME
Parameter name used to configure the list of tool definitions exposed to the LLM agent during an episode.This parameter is typically declared as YAML metadata inside an episode's head block. It accepts a comma-separated list of tool names to selectively restrict the agent's toolset for that specific stage. If omitted or left empty, all registered tools remain available to the agent.
Example Usage
- Restrict tools inside an Episode YAML head block:
--- enabledTools: - get_bindex - pick_libraries --- # Episode Instructions Locate and validate our integration boundaries...
- See Also:
- Restrict tools inside an Episode YAML head block:
-
PUBLIC_PROP_GROUP_NAME
Prefix for property groups whose values are exposed and injectable directly into prompt templates.Any configuration property starting with this prefix (e.g.,
public.schemaUrl) will be automatically collected and made available as a fully-prefixed variable placeholder (e.g.,${public.schemaUrl}) inside LLM prompt files or system instructions.Example Usage
- Define the property in a configuration file (e.g.,
mcp.properties):public.schemaUrl=https://raw.githubusercontent.com/machanism-org/bindex/schema-v2.json public.projectName=Bindex Core - Reference the property in an Act prompt template:
# Load Bindex Schema Validate your JSON against this schema: ${public.schemaUrl} Processing context for: ${public.projectName}
- Define the property in a configuration file (e.g.,
-
FILE_INCLUDED_MARKER
Prefix marker for prompt lines that include external content. A line beginning with this marker is treated as a reference. Supported references arehttp://...,https://..., andfile://....For
Referenced content is read as UTF-8 and recursively parsed, so included files may contain additional include markers.file://references, the path is resolved relative to the active project directory.Example:
>>> file://docs/instructions.md(resolves to<projectDir>/docs/instructions.md)- See Also:
-
LOG_OUTPUT_PREFIX
The format pattern used to prepend logger output blocks when reporting responses generated by the AI provider.- See Also:
-
EXIT_SPECIAL_PROMPT_COMMAND
Interactive-mode command that terminates processing immediately by throwing aProcessTerminationExceptionwith exit code0.Example interactive input:
.- See Also:
-
CONTINUE_SPECIAL_PROMPT_COMMAND
Interactive-mode command that accepts the current response and continues processing without sending another prompt to the provider.Example interactive input:
>- See Also:
-
NO_INTERACTIVE_SPECIAL_PROMPT_COMMAND
Interactive-mode command that accepts the current response and continues processing in a non-interactive mode, running to completion without prompting the user again.Example interactive input:
>>- See Also:
-
model
The specific AI model identifier or provider label being utilized for operations. -
instructions
Base instructions that set the persona, tone, and scope for the AI provider during execution. -
defaultPrompt
Default fallback prompt used to process directories or projects when no specific file prompt is given. -
interactive
private boolean interactiveFlag indicating whether interactive mode is active, allowing continuous prompt looping and execution. -
functionTools
Collection of user-configured function tools that are registered with and made available to the AI provider. -
functionToolsLoader
Loader utility responsible for discovering, instantiating, and applying functional tools to the AI provider.
-
-
Constructor Details
-
AIFileProcessor
Creates a processor for the given project directory and AI provider identifier.- Parameters:
rootDir- the project root directoryconfigurator- the application configurationgenai- the AI provider or model identifier
-
-
Method Details
-
process
Processes the given file using the currently configured instructions.- Parameters:
projectLayout- the current project layout metadatafile- the file to processprompt- the prompt to send to the AI provider- Returns:
- the provider response, or
nullwhen no response is produced
-
process
protected String process(ProjectLayout projectLayout, File file, String instructions, String... prompts) Processes a specified file within a project layout by configuring and invoking a Generative AI (GenAI) provider using a sequence of instructions and prompts.This method performs the following operations:
- Establishes the thread context for the provided
ProjectLayout. - Extracts input parameters from the provided array of prompts.
- Resolves the GenAI model configuration (falling back to the default
configured model if not explicitly overridden in prompt metadata via
gw.model). - Instantiates the target
Genaiprovider and registers enabled toolkits and custom function tools. - Constructs system instructions by combining default bundle instructions
with any custom parameters passed to
instructions. - Feeds file-specific contextual metadata and substituted prompts to the AI provider.
- Executes the AI operation and returns the generated content.
Supported Input Properties (extracted dynamically from the prompts' metadata):
gw.model(String) - Overrides the default model identifier used to initialize the GenAI provider. If not present, the method falls back to the default instance model.enabledTools(String or List<?>) - Configures which toolkits or tools should be enabled for the AI provider. Defined via the constantENABLED_TOOLS_PARAM_NAME.- Other YAML properties are retained as prompt configuration values and string values may be resolved through the active configurator before they are used. Properties not recognized by the processor are available for configuration substitution but do not otherwise alter processing.
- Parameters:
projectLayout- the directory structure and metadata context of the active projectfile- the target file currently being processedinstructions- additional custom system instructions to append to the default system instructions; can benullor blankprompts- a variable-length list or array of user prompt sequences to be evaluated and sent to the GenAI model- Returns:
- the output string containing the model's response if processing was
successful;
nullif prompts were empty or blank - Throws:
IllegalArgumentException- if the resolved GenAI model identifier is missing or no matching provider can be initialized
- Establishes the thread context for the provided
-
applyTools
Registers the selected discovered tools and the tools explicitly added to this processor with the provider for the current request.- Parameters:
instructions- the resolved system instructionsprompts- the resolved promptsprovider- the provider that receives the toolstools- the selected tool names, ornullfor the default set
-
getEnabledTools
Resolves the tool names enabled for the current processing request.Prompt front matter takes precedence over the configured value. A string is split on whitespace, commas, and semicolons; a YAML list is converted to an array of item strings. Other value types are treated as though no explicit tool selection was supplied. When neither source provides a value,
nullis returned so the provider can use its default tool set.- Parameters:
inputProps- prompt parameters extracted from YAML front matterconf- layered configuration used as the fallback source- Returns:
- enabled tool names, or
nullwhen no selection is configured
-
extractInputParams
Extracts supported YAML front-matter input parameters from the beginning of a prompt.A prompt may start with a YAML block delimited by
---. The block is removed from the returned prompt content and each YAML entry is merged intoinputProps. String values are resolved with the processor configurator; non-string values, such as YAML lists, are preserved.Supported special input parameters include:
gw.model: model or provider identifier to use for this prompt.enabledTools: a string or YAML list naming provider tools that should be enabled.
Example:
--- gw.model: ${public.ai.model} enabledTools: - project-context - file-system --- Analyze this file.- Parameters:
prompt- the input prompt string which may contain a leading YAML configuration blockinputProps- the map to populate with extracted and resolved parameters- Returns:
- the stripped prompt content when a configuration block is present; otherwise, the original prompt string
-
removeFrontMatterData
-
resolveInputParamValue
-
getProcessInfo
Generates a structured JSON string containing execution metadata about the file being processed and the current processing environment context.This method builds a map structure containing processing details and attempts to serialize it to a JSON format. The generated map holds the following properties:
"PROCESSED_FILE_REL_PATH"- The relative path of the processed file with respect to the project directory."PROCESS_MODE"- The current interaction mode, returning"INTERACTIVE"if the execution is interactive, otherwise"NOT-INTERACTIVE".
Serialization Fallback: If Jackson's
ObjectMapperfails to serialize the map to a standard JSON string, the method falls back to the default string representation of the map (viaObject.toString()).- Parameters:
projectLayout- the layout configuration of the project, used to resolve the base project directory for path relative-ization; must not benullfile- the file currently undergoing processing, used to determine its relative path; must not benull- Returns:
- a string representation of the processing information map; ideally a valid JSON-formatted string, or a stringified map representation if serialization fails
- See Also:
-
ProjectLayout.getRelativePath(File, File)ObjectMapper.writeValueAsString(Object)
-
perform
-
input
Obtains the next input from an interactive user session.The default implementation does not read from standard input because this processor may run without a supported interactive console. Subclasses can override this method to provide console or UI input.
- Returns:
- the next command or prompt, or
nullwhen input is unavailable
-
setProjectLayoutContext
Extracts context metadata from the providedProjectLayoutand registers it in the project context registry.This method evaluates essential environment information (such as the operating system), project structure configurations (like name, IDs, and relative paths), and maps directory definitions (such as source files, tests, documentation, and sub-modules) into a centralized storage registry managed by
ProjectContextFunctionTools.Directory collections are consolidated into formatted string information lines relative to the project directory before registration.
- Parameters:
projectLayout- theProjectLayoutcontaining the current project structure, directories, and parent configurations; must not benull- Throws:
IllegalArgumentException- if an error occurs during JSON serialization or parsing of the layout information (wrapsJsonProcessingException)- See Also:
-
getDirInfoLine
com.fasterxml.jackson.databind.node.ArrayNode getDirInfoLine(Collection<String> sources, File projectDir) Returns a JsonNode (ArrayNode) containing the names of directories from the given collection that exist within the specified project directory. Each directory name is wrapped in backticks.- Parameters:
sources- a collection of directory names (relative to projectDir) to check for existenceprojectDir- the base directory in which to check for the existence of each source directory- Returns:
- a JsonNode (ArrayNode) of existing directory names, each wrapped in backticks (e.g., ["`src`", "`resources`"])
-
setInstructions
Sets the base instructions used for processing after normalizing line content and resolving supported references.- Parameters:
instructions- the raw instruction text
-
getInstructions
Returns the current base instructions used for processing.- Returns:
- the configured instruction text
-
parseLines
Normalizes multi-line input and resolves supported line references such as HTTP URLs andfile:references.- Parameters:
data- the input text to parseprojectDir- the project root used to resolve relative file referencesconf- the configurator used to substitute public properties- Returns:
- the normalized text
-
tryToGetFromReference
Resolves a single instruction line that may point to external content.If the instruction contains an external reference marker, it will be fetched and resolved. URLs starting with
http://orhttps://are fetched remotely. URIs starting withfile://are resolved and loaded relative to the provided project directory.- Parameters:
data- the instruction line to inspectprojectDir- the root directory of the project, used as the base context to resolve relativefile://referencesconf-- Returns:
- the resolved content, or the original line when no reference is
found, or
nullwhen the input isnull - Throws:
IOException- if the referenced remote content or local file cannot be read
-
readFromHttpUrl
Reads UTF-8 text content from the given HTTP or HTTPS URL.- Parameters:
urlString- the URL to read- Returns:
- the response content as text
- Throws:
IOException- if the URL cannot be read
-
readFromFilePath
Reads UTF-8 text content from the given file path.- Parameters:
filePath- the absolute or project-relative file pathprojectDir- the project root used to resolve a relative path- Returns:
- the file content as text
- Throws:
IOException- if the file cannot be opened or read
-
scanDocuments
Configures scanning based on the provided directory or path pattern and then starts scanning the project folder.The
pathargument may be specified as:- An absolute path — used as-is to scan a specific location.
- A relative path — resolved against
projectDir. - A glob pattern — e.g.,
"glob:**/*.java", matched against files underprojectDir. - A regex pattern — e.g.,
"regex:.*\\.java", matched against files underprojectDir.
pathequals the absolute path ofprojectDir, the entire project directory is scanned without applying any pattern matching.- Parameters:
projectDir- the project root directory; must not benullpath- the directory, relative path, glob pattern, or regex pattern used to match files to scan; must not be blank- Throws:
IllegalArgumentException- ifprojectDirisnullorpathis blankIOException- if scanning fails
-
parsePath
Resolves the effective scan directory and converts it into a glob expression when required.- Parameters:
projectDir- the base project directorypath- the configured scan directory- Returns:
- the resolved path matcher expression
-
getDefaultPrompt
Returns the default prompt used for folder processing.- Returns:
- the default prompt
-
setDefaultPrompt
Sets the default prompt used for folder processing.- Parameters:
defaultPrompt- the default prompt text
-
processFolder
Processes the project root folder using the configured default prompt.- Overrides:
processFolderin classAbstractFileProcessor- Parameters:
projectLayout- the current project layout metadata
-
getModel
Returns the configured AI model or provider identifier.- Returns:
- the model or provider identifier
-
setModel
Sets the AI model or provider identifier.- Parameters:
genai- the model or provider identifier
-
setInteractive
public void setInteractive(boolean interactive) Enables or disables interactive processing mode.- Parameters:
interactive-trueto enable interactive mode; otherwisefalse
-
isInteractive
public boolean isInteractive()Indicates whether interactive processing mode is enabled.- Returns:
truewhen interactive mode is enabled; otherwisefalse
-
addTool
Adds a tool definition that will be exposed to the AI provider.- Parameters:
toolFunction- the tool definition to add
-