The Agent class is the core component of MindedJS that orchestrates conversations, manages state, and coordinates flows. This document covers the initialization options and key methods available on the Agent instance.
Constructor
The Agent constructor accepts configuration options to customize its behavior:
parseSessionIdFromTrigger: Optional function to extract session ID from triggers (defaults to triggerBody.sessionId)
Key Methods
updateState
Updates the state of an active session. This method allows you to programmatically modify the conversation state, including messages, memory, and other state properties.
Signature
Parameters
sessionId (string): The unique identifier of the session to update
state (Partial): An object containing the state properties to update. Can include:
messages: Array of messages to add or update
memory: Partial memory object to merge with existing memory
goto: Node ID to override the next execution point
Any other state properties defined in your agent
Usage Examples
Update Memory
Add Messages
Update Multiple State Properties
Common Use Cases
Tool State Updates: Tools can update state after execution
External Event Handling: Update state based on external events
Voice Session Corrections: Update messages during voice conversations
getState
Retrieves the current state of a session.
Signature
Parameters
sessionId (string): The unique identifier of the session
Returns
A State object containing:
sessionId: The session identifier
memory: The current memory state
messages: Array of conversation messages
sessionType: The type of session (TEXT, VOICE, etc.)
Other state properties
Usage Example
compiledGraph
Access to the underlying LangGraph compiled graph for advanced operations.
Usage Example
State Management Best Practices
1. Partial Updates
Always use partial updates to avoid overwriting existing state:
2. Atomic Operations
Group related updates together:
3. State Validation
The state updates are validated against your memory schema:
4. Tool State Updates
Tools should return state updates rather than calling updateState directly when possible:
Tool Execution API
ToolExecutor
The ToolExecutor class enables standalone tool execution, particularly useful for browser automation and external tool invocations.
Setting Up Tool Execution
Tool Configuration for Execution
Tools must explicitly opt-in to be executable via requests:
Executing Tools
CDP URL and Browser Automation
When tools are executed in a browser-use context, the Chrome DevTools Protocol (CDP) URL is available in the state:
Accessing CDP URL in Tools
Browser-Use Integration Flow
Browser-use requests tool execution via socket
ToolExecutor receives request with CDP URL
CDP info is injected into state (state.cdp)
Tool connects to browser using CDP URL from state.cdp.url
Tool performs automation and returns results
State updates are automatically applied
Security Considerations
Tools must have allowExecutionRequests: true to be executable via ToolExecutor
CDP URLs are only available during browser-use execution context
Tools should validate CDP URL availability before attempting browser operations
Always handle connection failures gracefully
Integration with Other Features
With Browser Use Tools
When using browser automation tools, state updates happen automatically through the ToolExecutor:
With Voice Sessions
Voice sessions use updateState for real-time corrections:
With Events
State can be updated in event handlers:
Error Handling
Always handle potential errors when updating state:
Related Documentation
Memory - Learn about memory schemas and management
import { HumanMessage, AIMessage } from '@langchain/core/messages';
// Add a new message to the conversation
await agent.updateState({
sessionId: 'session-123',
state: {
messages: [new HumanMessage('User input'), new AIMessage('Agent response')],
},
});
// Update both memory and messages
await agent.updateState({
sessionId: 'session-123',
state: {
memory: {
conversation: {
topic: 'Order inquiry',
urgency: 'high',
},
},
messages: [new HumanMessage('I need help with my order')],
},
});
// Inside a tool's execute method
async execute({ input, state, agent }) {
// Perform tool logic
const result = await processOrder(input.orderId);
// Update state with results
await agent.updateState({
sessionId: state.sessionId,
state: {
memory: {
order: {
id: result.orderId,
status: result.status
}
}
}
});
return { result };
}
// Get current state
const state = await agent.getState('session-123');
// Access memory
console.log('User name:', state.memory.user?.name);
// Check conversation history
console.log('Message count:', state.messages.length);
// Get session type
console.log('Session type:', state.sessionType);
// Get LangGraph state directly
const graphState = await agent.compiledGraph.getState(agent.getLangraphConfig(sessionId));
// Update state with LangGraph API
await agent.compiledGraph.updateState(agent.getLangraphConfig(sessionId), {
messages: [newMessage],
goto: 'specific-node',
});
try {
await agent.updateState({
sessionId,
state: {
memory: {
user: {
email: 'invalid-email', // Will fail validation if email has format validation
},
},
},
});
} catch (err) {
logger.error({ message: 'State validation failed', err });
}
// ✅ Preferred - Return state updates
async execute({ input, state }) {
const result = await processData(input);
return {
result,
state: {
memory: {
processedData: result.data
}
}
};
}
// ⚠️ Use only when necessary - Direct update
async execute({ input, state, agent }) {
const result = await processData(input);
await agent.updateState({
sessionId: state.sessionId,
state: {
memory: { processedData: result.data }
}
});
return { result };
}
import { ToolExecutor } from '@minded-ai/mindedjs';
// Create a tool executor
const toolExecutor = new ToolExecutor(agent);
// Register tools that can be executed via requests
// Only tools with allowExecutionRequests: true will be registered
toolExecutor.registerTools(tools);
import { Tool } from '@minded-ai/mindedjs';
const myBrowserTool: Tool<typeof schema, Memory> = {
name: 'browserAction',
description: 'Performs browser automation',
input: schema,
allowExecutionRequests: true, // Required for ToolExecutor
execute: async ({ input, state, agent }) => {
// Access CDP URL if available (browser-use context)
if (state.cdp?.url) {
// Connect to browser using Playwright or similar
const browser = await chromium.connectOverCDP(state.cdp.url);
const page = browser.contexts()[0].pages()[0];
// Perform browser automation
await page.goto(input.url);
const title = await page.title();
return {
result: { pageTitle: title },
state: {
memory: {
lastVisitedUrl: input.url,
},
},
};
}
// Fallback for non-browser context
return { result: 'Browser context not available' };
},
};
// Browser tools can update state via the ToolExecutor
const toolExecutor = new ToolExecutor(agent);
toolExecutor.registerTools(browserTools);
// State updates are handled internally when tools return state changes
// The CDP info is automatically injected when available in state.cdp
// Voice session correction flow
const voiceSession = new VoiceSession(agent, sessionId);
// Corrections use updateState internally