Class Chrome
- All Implemented Interfaces:
ContextProvider, PropertyChangeSource, Rebindable
This toolkit manages a fleet of BrowserDrone instances, supporting
both headless execution and live connection to the user's active Chrome profiles.
- Author:
- anahata
-
Field Summary
Fields inherited from class AbstractBrowser
dronesModifier and TypeFieldDescriptionprotected final Map<String, BrowserDrone> The centralized registry mapping drone IDs to their stateful objects.Fields inherited from class AnahataToolkit
childrenProviders, propertyChangeSupportModifier and TypeFieldDescriptionprotected List<ContextProvider> The list of child context providers managed by this toolkit.protected PropertyChangeSupportSupport for firing property change events.Fields inherited from class ToolContext
toolkitModifier and TypeFieldDescriptionprotected JavaObjectToolkitThe toolkit instance that owns this context. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionprivate StringclearSingletonLockInternal(String userDataDir) Internal implementation to clear the Chrome Singleton Lock files.Scans the OS process table to find running Chrome instances bound to the requesteddataDir.private StringconnectToExistingInternal(BrowserDrone d, int port) Internal implementation to connect to an existing Chrome instance on a port.private StringdetectActiveProfile(String userDataDir) Detects which profile is currently active in the user data directory.private StringdetectPortFromFiles(String userDataDir, String profileDir) Detects the remote debugging port from active profile files.private StringextractArg(String cmdLine, String argName) Extracts an argument value from the command line string.private StringAttempts to resolve the full command line of a process.org.openqa.selenium.WebDriverResolves the active WebDriver for the requested drone.private StringGenerates a human-readable markdown report of all active Chrome processes on the host system.Gets a list of system instruction strings provided by this context provider.private booleanChecks if a directory contains any active lock files.private voidinitDriver(BrowserDrone d, org.openqa.selenium.chrome.ChromeOptions options, Map<String, String> environment) Initializes the ChromeDriver instance with specified options and environment.voidPerforms initial setup for a newly created toolkit instance.killAll()Closes all active browser processes.private StringInternal implementation to kill all running Chrome and ChromeDriver processes.private StringlaunchProfileChromeInternal(BrowserDrone d, String initialUrl) Internal implementation to launch Chrome with a specific profile.Lists all open tabs/windows in the specified drone.voidpopulateMessage(RagMessage ragMessage) Populates the givenRagMessagewith dynamic, just-in-time context parts.private StringresetExitStateInternal(String userDataDir, String profileDir) Internal implementation to reset Chrome's exit state.Methods inherited from class AbstractBrowser
clickElement, close, executeScript, fillForm, getPageSource, getPageText, getScreenshot, getStatus, goBack, goForward, inspectForm, locateElementGracefully, navigate, openNewTab, refresh, scrollToElement, switchToTab, waitForElementModifier and TypeMethodDescriptionclickElement(String droneId, String identifier) Performs a stateful click by first attempting to locate the element using a multi-strategy search (ID, Name, Link Text, XPath text content).Closes the browser session and removes it from the registry.executeScript(String droneId, String script) Executes arbitrary JavaScript in the current browser session.Fills a web form with the provided data.getPageSource(String droneId) Gets the full HTML source of the current page.getPageText(String droneId) Gets the visible text content of the current page.getScreenshot(String droneId, String name) Takes a screenshot of the current page and attaches it to the session.Gets the current status of the browser driver for a specific drone.Navigates back in the browser history.Navigates forward in the browser history.inspectForm(String droneId) Inspects the current page for input fields and buttons.protected org.openqa.selenium.WebElementlocateElementGracefully(org.openqa.selenium.WebDriver driver, String identifier) Helper method to safely locate elements using a cascading fallback strategy.Navigates the specified drone to a new URL.openNewTab(String droneId, String url) Refreshes the current page.scrollToElement(String droneId, String identifier) Scrolls the specified element into view.switchToTab(String droneId, int index) Switches the active tab/window by its index.waitForElement(String droneId, String cssSelector, int timeoutSeconds) Safely executes a CSS-based visibility check usingWebDriverWait.Methods inherited from class AnahataToolkit
getChildrenProviders, getDescription, getId, getName, getParentProvider, getPropertyChangeSupport, isEffectivelyProviding, postActivate, rebindModifier and TypeMethodDescriptionGets the list of immediate child context providers.Gets a detailed description of what this context provider does.getId()Gets the unique identifier for this context provider.getName()Gets the human-readable name of this context provider.Gets the parent context provider in the hierarchy, if any.Gets the PropertyChangeSupport instance for this object.booleanOverride to also take into consideration theAbstractToolkit.enabledvoidCallback method triggered by the Asi Container once the Agi session has been fully deserialized and associated to the ASI container.voidrebind()Rebinds the toolkit after deserialization.Methods inherited from class ToolContext
addAttachment, addAttachment, addAttachment, addAttachment, error, error, error, getAgi, getApplicationMap, getAsiContainer, getAsiContainerMap, getCall, getExecutorService, getModelId, getModelMessage, getResourceManager, getResponse, getSessionMap, getThreadSafeLogger, getTool, getToolContext, getToolkit, getToolManager, getTurnMap, isToolExecution, log, peekResponse, runAsyncModifier and TypeMethodDescriptionvoidaddAttachment(byte[] data, String mimeType) Attaches a binary blob to the current tool's response.voidaddAttachment(byte[] data, String mimeType, Path sourcePath) Attaches a binary blob to the current tool's response with source file path traceability.voidaddAttachment(File file) Convenience method to attach a file to the current tool's response.voidaddAttachment(Path path) Convenience method to attach a file from a Path to the current tool's response.voidAdds an error message to the current tool's response.voidAdds an error message and exception stack trace to the current tool's response.voidAdds an exceptions stack trace to the current tool's response.getAgi()Convenience method to get the parent agi container for the current execution.Gets a static, application-scoped map for sharing objects across all containers in the current JVM.Gets the current ASI container hosting this Agi container is running.Gets a map for sharing objects across all sessions within the current ASI container.getCall()Convenience method to get the current tool call that initiated this execution.Convenience method to get the executor service for the current agi session.The id of model that is executing the tool.The id of model that is executing the tool.Convenience method to get the application's ResourceManager.Gets the current tool response from the thread-local context.Gets a shared map for storing state across turns within the current agi session.Gets a thread-safe logging consumer that automatically propagates the current tool execution context whenever a message is logged.getTool()Convenience method to get the metadata for the tool currently being executed.Returns a thread-safe snapshot of this context.<T> TgetToolkit(Class<T> toolkitClass) Retrieves the singleton instance of a registered toolkit class.Convenience method to get the application's global ToolManager.Gets a shared map for storing state across turns within the current agi session.booleanChecks if the current thread or this context instance is associated with an active tool execution.voidAdds a standard log message to the current tool's response.protected JavaMethodToolResponseInternal helper to retrieve the response if it exists, without throwing an exception.voidExecutes a task asynchronously in the session's executor service, automatically propagating the current tool execution context to the background thread.Methods inherited from class Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface ContextProvider
getAgi, getContextPosition, getFlattenedHierarchy, getFullyQualifiedId, getHeader, getIconId, getInstructionsTokenCount, getRagTokenCount, isProviding, setParentProvider, setProvidingModifier and TypeMethodDescriptiongetAgi()Gets the parent AGI session this context provider is registered under.default ContextPositionGets the designated position of this provider's content in the AI prompt.default List<ContextProvider> getFlattenedHierarchy(boolean providingOnly) Gets a flattened list of this provider and all its descendants in the hierarchy.default StringGets the fully qualified ID of this provider, reflecting its position in the hierarchy.default StringGenerates a machine-readable header string for this context provider, used to identify the source of injected context in the final prompt.default StringGets an optional icon identifier for this provider.default intCalculates the token count for the system instructions provided by this instance using the active model.default intCalculates the token count for the RAG content provided by this instance using the active model.booleanChecks if this context provider is currently active and providing context.default voidsetParentProvider(ContextProvider parent) Sets the parent context provider for this instance.default voidsetProviding(boolean enabled) Sets whether this context provider is enabled.
-
Constructor Details
-
Chrome
public Chrome()Public constructor to instantiate the Chrome automation toolkit.
-
-
Method Details
-
initialize
public void initialize()Performs initial setup for a newly created toolkit instance.This method is called exactly once by the
ToolManagerafter the toolkit has been instantiated and registered. It provides a clean hook for toolkits to perform one-time initialization logic that requires the tool environment to be fully configured, such as scanning for project instructions or registering default resources.Implementation details: Disables the toolkit by default to prevent accidental drone spawns in environments without local browsers.
- Overrides:
initializein classAnahataToolkit
-
getSystemInstructions
Gets a list of system instruction strings provided by this context provider. These are typically prepended to the conversation as high-level guidance.Provides context-specific instructions to the ASI regarding Chrome automation.
- Returns:
- A list of system instruction strings.
-
populateMessage
Populates the givenRagMessagewith dynamic, just-in-time context parts. These parts are appended to the end of the user's prompt (RAG).Populates the RAG message with current Chrome environment state.
- Parameters:
ragMessage- The message to be augmented with context.
-
connect
public String connect(String droneId, String profile, Boolean headless, String dataDir, String binaryPath) throws AgiToolException Scans the OS process table to find running Chrome instances bound to the requesteddataDir. If a matching process is found in debug mode, it attaches to the existing port; otherwise, it launches a fresh instance with a dynamic debug port.- Parameters:
droneId- A unique ID for this drone.profile- An optional profile name (e.g., 'Default', 'Profile 1').headless- Whether to launch in an invisible headless mode.dataDir- The path to the user data directory.binaryPath- Optional absolute path to the chrome executable.- Returns:
- A status message confirming the connection.
- Throws:
AgiToolException- If the droneId is already in use.
-
killAll
Closes all active browser processes.- Specified by:
killAllin classAbstractBrowser- Returns:
- A status message describing the cleanup operations.
-
listTabs
Lists all open tabs/windows in the specified drone.Implementations should ideally use native DevTools protocols to avoid forcing window focus and causing screen flickering.
Implementation details: Iterates over all window handles and uses the Chrome DevTools Protocol (CDP)
Target.getTargetInfocommand to retrieve titles and URLs without forcing window focus. Falls back to standardswitchTo().window()if CDP fails.- Specified by:
listTabsin classAbstractBrowser- Parameters:
droneId- The ID of the drone to inspect.- Returns:
- A list of strings describing each open tab.
-
getDriver
Resolves the active WebDriver for the requested drone.Implementation details: This is an internal lifecycle method. If the connection is lost, concrete implementations should attempt to re-establish it using the cached port and profile data.
- Specified by:
getDriverin classAbstractBrowser- Parameters:
droneId- The unique ID of the drone.- Returns:
- The active WebDriver, or
nullif it cannot be resolved.
-
initDriver
private void initDriver(BrowserDrone d, org.openqa.selenium.chrome.ChromeOptions options, Map<String, String> environment) Initializes the ChromeDriver instance with specified options and environment.- Parameters:
d- the browser drone to initializeoptions- the ChromeOptions to applyenvironment- custom environment variables for the driver service
-
getProcessReport
Generates a human-readable markdown report of all active Chrome processes on the host system.Uses
ProcessHandleand OS-specific command line extraction (via/procon Linux orwmicon Windows) to identify ports and data directories.- Returns:
- A markdown string containing process PIDs, modes, and command lines.
-
getCommandLine
Attempts to resolve the full command line of a process.On Linux, this reads directly from
/proc/[pid]/cmdlinefor maximum fidelity. On other platforms or as a fallback, it uses Shell-based queries.- Parameters:
p- The process handle to inspect.- Returns:
- The full command line string.
-
extractArg
-
detectPortFromFiles
-
detectActiveProfile
-
hasLock
Checks if a directory contains any active lock files.- Parameters:
dir- the directory to check- Returns:
trueif a lock is detected,falseotherwise
-
killAllInternal
Internal implementation to kill all running Chrome and ChromeDriver processes.- Returns:
- status message describing the kill count
-
resetExitStateInternal
-
clearSingletonLockInternal
-
launchProfileChromeInternal
Internal implementation to launch Chrome with a specific profile.- Parameters:
d- the browser droneinitialUrl- optional initial URL to navigate to- Returns:
- status message describing the launch
-
connectToExistingInternal
Internal implementation to connect to an existing Chrome instance on a port.- Parameters:
d- the browser droneport- the remote debugging port- Returns:
- status message of the connection
-

