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
Knowledge Base RAG
You can query knowledge bases directly from code by importing the RAG utilities:
These functions are useful when you want full control over retrieval timing (for example in TRIGGER_EVENT) and how the retrieved context is applied.
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',
});
import { retrieveFromKnowledgeBase, retrieveAndGenerateFromKnowledgeBase } from '@minded-ai/mindedjs';
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