Class: Agent
Defined in: agent.ts:982
Agent class - orchestrates LLM interactions with tool use
Example
const agent = new Agent({
provider: new ClaudeProvider({ apiKey: 'sk-...' }),
systemPrompt: 'You are a helpful assistant.',
});
agent.registerTool(readFileTool);
agent.registerTool(writeFileTool);
const result = await agent.run('Read the contents of package.json');
console.log(result.response);
Constructors
Constructor
new Agent(config): Agent;
Defined in: agent.ts:1088
Parameters
| Parameter | Type |
|---|---|
config | AgentConfig |
Returns
Agent
Accessors
sessionId
Get Signature
get sessionId(): string;
Defined in: agent.ts:1328
Get the session ID for this agent instance
Returns
string
Methods
addAnchor()
addAnchor(input): Anchor | undefined;
Defined in: agent.ts:1593
Parameters
| Parameter | Type |
|---|---|
input | AnchorInput |
Returns
Anchor | undefined
Deprecated
Use addPin() instead
addGuardrail()
addGuardrail(input): Guardrail | undefined;
Defined in: agent.ts:1648
Add a custom guardrail
Parameters
| Parameter | Type | Description |
|---|---|---|
input | GuardrailInput | Guardrail definition |
Returns
Guardrail | undefined
The created guardrail, or undefined if guardrails are not enabled
Example
agent.addGuardrail({
id: 'no-delete-important',
name: 'Important Files Protection',
description: 'Prevent deletion of important files',
patterns: [/rm.*important/i, /delete.*important/i],
action: 'block',
message: 'Cannot delete files marked as important',
scope: ['bash'],
});
addPermission()
addPermission(rule): this;
Defined in: agent.ts:1727
Add a permission rule for a tool
Parameters
| Parameter | Type | Description |
|---|---|---|
rule | ToolPermission | Permission rule to add |
Returns
this
this for chaining
Example
agent.addPermission({
toolName: 'bash',
level: 'once',
description: 'Execute shell commands',
});
addPin()
addPin(input): Anchor | undefined;
Defined in: agent.ts:1478
Add a pin (critical information that survives context compaction).
Pins are injected into every LLM call and never get compacted. Use them for information that must not be forgotten.
Parameters
| Parameter | Type | Description |
|---|---|---|
input | AnchorInput | Pin input (uses AnchorInput type) |
Returns
Anchor | undefined
The created pin, or undefined if pins are not enabled
Example
agent.addPin({
content: 'Team roster: $default, $arch',
priority: 'info',
scope: 'session',
});
checkpoint()
checkpoint(metadata?): Promise<string>;
Defined in: agent.ts:2279
Save the current state using the configured checkpointer. Throws if no checkpointer is configured.
Parameters
| Parameter | Type | Description |
|---|---|---|
metadata? | Partial<SessionMetadata> | Optional metadata overrides |
Returns
Promise<string>
The session ID
Example
const agent = new Agent({
provider,
checkpointer: new FileCheckpointer('~/.myapp/sessions/'),
});
await agent.run('Hello!');
const sessionId = await agent.checkpoint();
console.log(`Saved as: ${sessionId}`);
clearAnchors()
clearAnchors(options?): number;
Defined in: agent.ts:1613
Parameters
| Parameter | Type |
|---|---|
options? | AnchorClearOptions |
Returns
number
Deprecated
Use clearPins() instead
clearHistory()
clearHistory(): this;
Defined in: agent.ts:1875
Clear conversation history to start fresh
Returns
this
clearPins()
clearPins(options?): number;
Defined in: agent.ts:1528
Clear pins based on criteria
Parameters
| Parameter | Type | Description |
|---|---|---|
options? | AnchorClearOptions | Clear options for filtering which pins to remove |
Returns
number
Number of pins removed
clearSessionPermissions()
clearSessionPermissions(): this;
Defined in: agent.ts:1790
Clear all session-level permissions
Returns
this
compact()
compact(options?): Promise<{
categoryStats?: Record<ContextCategory, {
action: "preserved" | "compacted" | "summarized";
tokensAfter: number;
tokensBefore: number;
}>;
filesCreated?: string[];
messagesPreserved: number;
originalTokens: number;
restorationHintsInjected: boolean;
rounds: number;
success: boolean;
summary: string;
summaryTokens: number;
toolResultsRepaired: number;
}>;
Defined in: agent.ts:2049
Compact the conversation context to reduce token usage.
This is the recommended way to trigger context compaction externally. It handles:
- Summarizing older messages
- Repairing tool use/result pairing (prevents API errors)
- Injecting context restoration hints (if file tracking is enabled)
- Updating the conversation history
Parameters
| Parameter | Type | Description |
|---|---|---|
options? | { emergency?: boolean; injectRestorationHints?: boolean; targetUtilization?: number; useSmartCompaction?: boolean; } | Compaction options |
options.emergency? | boolean | Use emergency mode (more aggressive summarization). Default: auto-detect based on context utilization |
options.injectRestorationHints? | boolean | Inject file restoration hints after compaction. Only applies if file tracking is enabled. Default: true (if file tracking is enabled) |
options.targetUtilization? | number | Target utilization after compaction (0-1). Default: from context manager config (typically 0.5) |
options.useSmartCompaction? | boolean | Use smart category-aware compaction instead of simple summarization. Smart compaction: - Preserves system and recent messages completely - Saves large tool results to files - Summarizes history with LLM Default: true |
Returns
Promise<{ categoryStats?: Record<ContextCategory, { action: "preserved" | "compacted" | "summarized"; tokensAfter: number; tokensBefore: number; }>; filesCreated?: string[]; messagesPreserved: number; originalTokens: number; restorationHintsInjected: boolean; rounds: number; success: boolean; summary: string; summaryTokens: number; toolResultsRepaired: number; }>
Compaction result with statistics
Example
// Basic compaction
const result = await agent.compact();
console.log(`Reduced from ${result.originalTokens} to ${result.summaryTokens} tokens`);
// Compaction without restoration hints
await agent.compact({ injectRestorationHints: false });
// Emergency compaction (more aggressive)
await agent.compact({ emergency: true });
createSubAgent()
createSubAgent(config): this;
Defined in: agent.ts:2463
Create and register a sub-agent with isolated context.
Sub-agents are specialized agents that handle discrete tasks independently. They have their own context window and can have different tools/permissions.
Parameters
| Parameter | Type |
|---|---|
config | SubAgentConfig |
Returns
this
Example
agent.createSubAgent({
name: 'code-reviewer',
description: 'Reviews code for security and quality issues',
systemPrompt: 'You are a code review specialist...',
tools: [readFileTool], // Restricted tools
contextMode: 'isolated',
});
const result = await agent.runSubAgent('code-reviewer', 'Review src/auth.ts');
createWithMemory()
static createWithMemory(
config,
memoryOptions?,
memoryDir?): Promise<Agent>;
Defined in: agent.ts:1307
Create an agent with project memory loaded from files.
This factory method automatically discovers and loads project-specific instructions from files like CLAUDE.md, GEMINI.md, PROJECT.md, etc.
Parameters
| Parameter | Type | Description |
|---|---|---|
config | Omit<AgentConfig, "projectMemory"> | Agent configuration |
memoryOptions? | ProjectMemoryOptions | Project memory loading options |
memoryDir? | string | Directory to search for memory files (defaults to cwd) |
Returns
Promise<Agent>
Agent instance with loaded project memory
Example
// Load Claude-specific instructions
const agent = await Agent.createWithMemory(
{
provider,
systemPrompt: 'You are a helpful assistant.',
},
{ providers: 'claude' },
'/path/to/project'
);
// Load instructions for multiple providers
const agent = await Agent.createWithMemory(
{ provider },
{ providers: ['claude', 'gemini'], includeGeneric: true }
);
// Access loaded memory
const memory = agent.getProjectMemory();
console.log(`Loaded ${memory?.files.length} memory files`);
disableGuardrail()
disableGuardrail(id): boolean;
Defined in: agent.ts:1690
Disable a guardrail by ID
Parameters
| Parameter | Type |
|---|---|
id | string |
Returns
boolean
disposeAllSubAgents()
disposeAllSubAgents(): void;
Defined in: agent.ts:2739
Dispose all sub-agents and release their resources.
Useful for cleanup when the parent agent is done or to free memory during long-running sessions.
Returns
void
disposeSubAgent()
disposeSubAgent(name): boolean;
Defined in: agent.ts:2714
Dispose a sub-agent and release its resources.
This clears the sub-agent’s:
- Conversation history
- Context manager state
- Tool registry
After disposal, the sub-agent must be re-created to use again.
Parameters
| Parameter | Type |
|---|---|
name | string |
Returns
boolean
emitCustomEvent()
emitCustomEvent(config): void;
Defined in: agent.ts:1840
Emit a custom event that will be streamed to event handlers.
This allows tools, middleware, and user code to emit custom events that are streamed alongside built-in agent events.
Inspired by LangGraph’s get_stream_writer() pattern. Addresses issues like LangGraph #6330 (preserve event metadata).
Parameters
| Parameter | Type | Description |
|---|---|---|
config | CustomEventConfig | Custom event configuration |
Returns
void
Example
agent.emitCustomEvent({
name: 'progress',
data: { step: 1, total: 5, message: 'Processing...' },
metadata: { toolName: 'myTool' },
});
enableGuardrail()
enableGuardrail(id): boolean;
Defined in: agent.ts:1683
Enable a guardrail by ID
Parameters
| Parameter | Type |
|---|---|
id | string |
Returns
boolean
formatRestorationHints()
formatRestorationHints(): string;
Defined in: agent.ts:1978
Format context restoration hints based on tracked file accesses. Returns empty string if no files have been accessed or file tracking is disabled.
Returns
string
fromState()
static fromState(state, options): Agent;
Defined in: agent.ts:2387
Create an agent from a serialized AgentState object.
Parameters
| Parameter | Type | Description |
|---|---|---|
state | AgentState | The serialized agent state |
options | { checkpointer?: Checkpointer; onEvent?: AgentEventHandler; provider: LLMProvider; systemPrompt?: string; tools?: Tool<object>[]; } | Options for the new agent |
options.checkpointer? | Checkpointer | - |
options.onEvent? | AgentEventHandler | - |
options.provider | LLMProvider | - |
options.systemPrompt? | string | - |
options.tools? | Tool<object>[] | - |
Returns
Agent
Example
// Load state from somewhere
const json = await fs.readFile('session.json', 'utf-8');
const state = JSON.parse(json);
// Create agent from state
const agent = Agent.fromState(state, { provider });
await agent.run('Continue...');
getAnchor()
getAnchor(id): Anchor | undefined;
Defined in: agent.ts:1597
Parameters
| Parameter | Type |
|---|---|
id | string |
Returns
Anchor | undefined
Deprecated
Use getPin() instead
getAnchorManager()
getAnchorManager(): AnchorManager | undefined;
Defined in: agent.ts:1617
Returns
AnchorManager | undefined
Deprecated
Use getPinManager() instead
getAnchors()
getAnchors(options?): Anchor[];
Defined in: agent.ts:1601
Parameters
| Parameter | Type |
|---|---|
options? | AnchorQueryOptions |
Returns
Anchor[]
Deprecated
Use getPins() instead
getBudgetStatus()
getBudgetStatus(): BudgetStatus | undefined;
Defined in: agent.ts:1415
Get budget status.
Returns
BudgetStatus | undefined
getContextManager()
getContextManager(): ContextManager | undefined;
Defined in: agent.ts:1923
Get the context manager (if configured)
Returns
ContextManager | undefined
getContextStats()
getContextStats(): ContextStats | undefined;
Defined in: agent.ts:1938
Get context statistics
Returns
ContextStats | undefined
getDeadMessagePruneStats()
getDeadMessagePruneStats():
| {
errorsPruned: number;
permissionsPruned: number;
prunedCount: number;
tokensSaved: number;
}
| undefined;
Defined in: agent.ts:1954
Get dead message pruning statistics (errors pruned, permissions pruned, tokens saved).
Returns
| { errorsPruned: number; permissionsPruned: number; prunedCount: number; tokensSaved: number; } | undefined
getFileTracker()
getFileTracker(): FileAccessTracker | undefined;
Defined in: agent.ts:1970
Get the file access tracker (if file tracking is enabled)
Returns
FileAccessTracker | undefined
getGuardrail()
getGuardrail(id): Guardrail | undefined;
Defined in: agent.ts:1655
Get a guardrail by ID
Parameters
| Parameter | Type |
|---|---|
id | string |
Returns
Guardrail | undefined
getGuardrailManager()
getGuardrailManager(): GuardrailManager | undefined;
Defined in: agent.ts:1697
Get the guardrail manager (if configured)
Returns
GuardrailManager | undefined
getGuardrails()
getGuardrails(): Guardrail[];
Defined in: agent.ts:1662
Get all guardrails
Returns
getHistory()
getHistory(): Message[];
Defined in: agent.ts:1886
Get the current conversation history
Returns
Message[]
getModel()
getModel(): string;
Defined in: agent.ts:1553
Get the current model ID for this agent.
Returns
string
The model ID string (e.g., ‘claude-sonnet-4-20250514’)
getObservationMaskStats()
getObservationMaskStats():
| {
activeStamps: number;
inputsCompacted: number;
maskedCount: number;
tokensSaved: number;
}
| undefined;
Defined in: agent.ts:1945
Get observation masking statistics (tokens saved, observations masked, inputs compacted).
Returns
| { activeStamps: number; inputsCompacted: number; maskedCount: number; tokensSaved: number; } | undefined
getPermission()
getPermission(toolName): ToolPermission | undefined;
Defined in: agent.ts:1742
Get a permission rule by tool name
Parameters
| Parameter | Type |
|---|---|
toolName | string |
Returns
ToolPermission | undefined
getPermissionLevel()
getPermissionLevel(toolName): PermissionLevel;
Defined in: agent.ts:1768
Get the effective permission level for a tool
Parameters
| Parameter | Type |
|---|---|
toolName | string |
Returns
getPermissionManager()
getPermissionManager(): PermissionManager | undefined;
Defined in: agent.ts:1805
Get the permission manager (if configured)
Returns
PermissionManager | undefined
getPermissions()
getPermissions(): ToolPermission[];
Defined in: agent.ts:1749
Get all permission rules
Returns
getPin()
getPin(id): Anchor | undefined;
Defined in: agent.ts:1489
Get a pin by ID
Parameters
| Parameter | Type |
|---|---|
id | string |
Returns
Anchor | undefined
getPinManager()
getPinManager(): AnchorManager | undefined;
Defined in: agent.ts:1535
Get the pin manager (if configured)
Returns
AnchorManager | undefined
getPins()
getPins(options?): Anchor[];
Defined in: agent.ts:1496
Get all pins, optionally filtered
Parameters
| Parameter | Type |
|---|---|
options? | AnchorQueryOptions |
Returns
Anchor[]
getProjectMemory()
getProjectMemory(): ProjectMemory | undefined;
Defined in: agent.ts:1356
Get the loaded project memory (if any).
Project memory contains instructions loaded from files like CLAUDE.md, GEMINI.md, PROJECT.md, etc.
Returns
ProjectMemory | undefined
The loaded project memory, or undefined if none was loaded
Example
const memory = agent.getProjectMemory();
if (memory) {
console.log(`Loaded ${memory.files.length} instruction files`);
console.log(`Total tokens: ~${memory.estimatedTokens}`);
for (const file of memory.files) {
console.log(` - ${file.relativePath}`);
}
}
getSessionPermissions()
getSessionPermissions(): string[];
Defined in: agent.ts:1798
Get all tools with session-level permission
Returns
string[]
getStreamWriter()
getStreamWriter(eventName?): StreamWriter;
Defined in: agent.ts:1866
Get a stream writer function for emitting custom events.
This returns a simple function that can be passed to tools or middleware for streaming progress updates.
Parameters
| Parameter | Type | Default value | Description |
|---|---|---|---|
eventName | string | 'stream' | Name for all events emitted by this writer |
Returns
A stream writer function
Example
const writer = agent.getStreamWriter('myTool');
writer('Starting...', { phase: 'init' });
writer('Processing...', { phase: 'work', progress: 50 });
writer('Done!', { phase: 'complete' });
getSubAgent()
getSubAgent(name): Agent | undefined;
Defined in: agent.ts:2686
Get a registered sub-agent by name
Parameters
| Parameter | Type |
|---|---|
name | string |
Returns
Agent | undefined
getSubAgentNames()
getSubAgentNames(): string[];
Defined in: agent.ts:2693
Get all registered sub-agent names
Returns
string[]
getToolDefinitions()
getToolDefinitions(): ToolDefinition[];
Defined in: agent.ts:2829
Get all registered tool definitions
Returns
ToolDefinition[]
getToolRegistry()
getToolRegistry(): ToolRegistry;
Defined in: agent.ts:1931
Get the tool registry instance. Useful for setting up fallback handlers or inspecting registered tools.
Returns
getTotalInputTokens()
getTotalInputTokens(): number;
Defined in: agent.ts:1401
Get total input tokens used across all LLM calls.
Returns
number
getTotalOutputTokens()
getTotalOutputTokens(): number;
Defined in: agent.ts:1408
Get total output tokens used across all LLM calls.
Returns
number
getTotalTokens()
getTotalTokens(): number;
Defined in: agent.ts:1394
Get total tokens used across all LLM calls.
Returns
number
getUsageStats()
getUsageStats(): UsageStats | undefined;
Defined in: agent.ts:1387
Get usage tracking statistics.
Returns
UsageStats | undefined
Usage statistics or undefined if usage tracking is not enabled
Example
const stats = agent.getUsageStats();
if (stats) {
console.log(`Total calls: ${stats.totalCalls}`);
console.log(`Total tokens: ${stats.totalTokens}`);
console.log(`Input tokens: ${stats.totalInputTokens}`);
console.log(`Output tokens: ${stats.totalOutputTokens}`);
}
getUsageSummary()
getUsageSummary(): string | undefined;
Defined in: agent.ts:1429
Get a human-readable usage summary.
Returns
string | undefined
getVerbosityLevel()
getVerbosityLevel(): VerbosityLevel;
Defined in: agent.ts:1963
Get current verbosity level based on context pressure
Returns
grantSessionPermission()
grantSessionPermission(toolName): this;
Defined in: agent.ts:1775
Grant session-level permission for a tool
Parameters
| Parameter | Type |
|---|---|
toolName | string |
Returns
this
hasAnchor()
hasAnchor(id): boolean;
Defined in: agent.ts:1605
Parameters
| Parameter | Type |
|---|---|
id | string |
Returns
boolean
Deprecated
Use hasPin() instead
hasAnchors()
hasAnchors(): boolean;
Defined in: agent.ts:1621
Returns
boolean
Deprecated
Use hasPins() instead
hasCheckpointer()
hasCheckpointer(): boolean;
Defined in: agent.ts:2292
Check if a checkpointer is configured
Returns
boolean
hasGuardrail()
hasGuardrail(id): boolean;
Defined in: agent.ts:1669
Check if a guardrail exists
Parameters
| Parameter | Type |
|---|---|
id | string |
Returns
boolean
hasGuardrails()
hasGuardrails(): boolean;
Defined in: agent.ts:1704
Check if guardrails are enabled
Returns
boolean
hasPermissions()
hasPermissions(): boolean;
Defined in: agent.ts:1812
Check if permissions are enabled
Returns
boolean
hasPin()
hasPin(id): boolean;
Defined in: agent.ts:1503
Check if a pin exists
Parameters
| Parameter | Type |
|---|---|
id | string |
Returns
boolean
hasPins()
hasPins(): boolean;
Defined in: agent.ts:1542
Check if pins are enabled
Returns
boolean
hasProjectMemory()
hasProjectMemory(): boolean;
Defined in: agent.ts:1363
Check if project memory was loaded
Returns
boolean
hasUsageTracking()
hasUsageTracking(): boolean;
Defined in: agent.ts:1443
Check if usage tracking is enabled.
Returns
boolean
isBudgetExceeded()
isBudgetExceeded(): boolean;
Defined in: agent.ts:1422
Check if budget is exceeded.
Returns
boolean
isToolSilent()
isToolSilent(name): boolean;
Defined in: agent.ts:2836
Check if a tool is marked as silent (no spinner or result output)
Parameters
| Parameter | Type |
|---|---|
name | string |
Returns
boolean
registerTool()
registerTool(tool): this;
Defined in: agent.ts:2808
Register a tool that the agent can call during conversations.
Tools are functions the LLM can invoke to perform actions like reading files, running commands, or querying APIs. The LLM sees the tool’s name, description, and parameter schema, then decides when to call it.
Parameters
| Parameter | Type | Description |
|---|---|---|
tool | Tool | Tool definition created with defineTool() |
Returns
this
The agent instance (for chaining)
Example
agent.registerTool(defineTool({
name: 'get_weather',
description: 'Get current weather for a city',
parameters: {
type: 'object',
properties: { city: { type: 'string' } },
required: ['city'],
},
execute: async ({ city }) => {
const data = await fetchWeather(city);
return { content: JSON.stringify(data) };
},
}));
registerTools()
registerTools(tools): this;
Defined in: agent.ts:2819
Register multiple tools at once.
Parameters
| Parameter | Type | Description |
|---|---|---|
tools | Tool<object>[] | Array of tool definitions |
Returns
this
The agent instance (for chaining)
removeAnchor()
removeAnchor(id): boolean;
Defined in: agent.ts:1609
Parameters
| Parameter | Type |
|---|---|
id | string |
Returns
boolean
Deprecated
Use removePin() instead
removeGuardrail()
removeGuardrail(id): boolean;
Defined in: agent.ts:1676
Remove a guardrail by ID
Parameters
| Parameter | Type |
|---|---|
id | string |
Returns
boolean
removePermission()
removePermission(toolName): boolean;
Defined in: agent.ts:1735
Remove a permission rule by tool name
Parameters
| Parameter | Type |
|---|---|
toolName | string |
Returns
boolean
removePin()
removePin(id): boolean;
Defined in: agent.ts:1512
Remove a pin by ID
Parameters
| Parameter | Type |
|---|---|
id | string |
Returns
boolean
true if pin was removed, false if not found
removeSubAgent()
removeSubAgent(name): boolean;
Defined in: agent.ts:2700
Remove a registered sub-agent (alias for disposeSubAgent)
Parameters
| Parameter | Type |
|---|---|
name | string |
Returns
boolean
resetUsageTracking()
resetUsageTracking(): void;
Defined in: agent.ts:1436
Reset usage tracking data.
Returns
void
resume()
static resume(sessionId, options): Promise<Agent>;
Defined in: agent.ts:2345
Resume an agent from a saved session.
Parameters
| Parameter | Type | Description |
|---|---|---|
sessionId | string | Session ID to resume |
options | { checkpointer: Checkpointer; onEvent?: AgentEventHandler; provider: LLMProvider; systemPrompt?: string; tools?: Tool<object>[]; } | Resume options (provider and checkpointer required) |
options.checkpointer | Checkpointer | - |
options.onEvent? | AgentEventHandler | - |
options.provider | LLMProvider | - |
options.systemPrompt? | string | - |
options.tools? | Tool<object>[] | - |
Returns
Promise<Agent>
Example
const checkpointer = new FileCheckpointer('~/.myapp/sessions/');
// Resume a previous session
const agent = await Agent.resume('session_abc123', {
provider: new ClaudeProvider({ apiKey: '...' }),
checkpointer,
});
// Continue the conversation
await agent.run('Continue where we left off...');
revokeSessionPermission()
revokeSessionPermission(toolName): boolean;
Defined in: agent.ts:1783
Revoke session-level permission for a tool
Parameters
| Parameter | Type |
|---|---|
toolName | string |
Returns
boolean
run()
run(userMessage, options?): Promise<AgentRunResult>;
Defined in: agent.ts:2874
Run the agent with a user message and return the result.
This is the main entry point for agent interaction. The agent will:
- Add the user message to conversation history
- Send the conversation to the LLM
- Execute any tool calls the LLM requests
- Repeat steps 2-3 until the LLM responds with text (no tool calls)
- Return the final text response and metadata
Events are emitted throughout the process via the onEvent callback configured at construction time.
Parameters
| Parameter | Type | Description |
|---|---|---|
userMessage | string | ContentBlock[] | The user’s message (string or content blocks for images) |
options? | RunOptions | Optional run configuration (max iterations, abort signal, etc.) |
Returns
Promise<AgentRunResult>
The agent’s response, tool call history, and context stats
Examples
const result = await agent.run('What files are in this directory?');
console.log(result.response);
console.log(`Used ${result.toolCalls.length} tool calls`);
// With abort signal
const controller = new AbortController();
const result = await agent.run('Refactor this file', {
signal: controller.signal,
});
runParallelSubAgents()
runParallelSubAgents(tasks, options?): Promise<SubAgentResult[]>;
Defined in: agent.ts:2644
Run multiple sub-agents in parallel with proper state isolation.
This method ensures that parallel sub-agents don’t share mutable state, preventing race conditions and state leakage between concurrent runs.
Inspired by LangGraph issue #6446: Parallel subgraphs with shared state keys cause InvalidUpdateError.
Parameters
| Parameter | Type | Description |
|---|---|---|
tasks | { name: string; task: string; }[] | Array of {name, task} objects to run in parallel |
options? | RunOptions | Optional run options applied to all sub-agents |
Returns
Promise<SubAgentResult[]>
Array of results in the same order as tasks
Example
// Run code review and security scan in parallel
const results = await agent.runParallelSubAgents([
{ name: 'code-reviewer', task: 'Review src/auth.ts' },
{ name: 'security-scanner', task: 'Scan src/auth.ts for vulnerabilities' },
]);
runSubAgent()
runSubAgent(
name,
task,
options?): Promise<SubAgentResult>;
Defined in: agent.ts:2533
Run a sub-agent with a specific task.
The sub-agent executes independently with its own context and returns the result to the parent agent.
Parameters
| Parameter | Type | Description |
|---|---|---|
name | string | Name of the registered sub-agent |
task | string | Task description for the sub-agent |
options? | RunOptions | Optional run options |
Returns
Promise<SubAgentResult>
serialize()
serialize(): AgentState;
Defined in: agent.ts:2245
Serialize the current agent state to an AgentState object. This can be used for manual persistence or transferring state.
Returns
Example
const state = agent.serialize();
const json = JSON.stringify(state);
// Store json somewhere...
setHistory()
setHistory(messages, options?): Promise<Agent>;
Defined in: agent.ts:1898
Set the conversation history (for manual compaction/restoration) Also updates the context manager’s token count if configured.
Parameters
| Parameter | Type | Description |
|---|---|---|
messages | Message[] | The message history to restore |
options? | { turnCount?: number; } | Optional restore options |
options.turnCount? | number | The turn count to restore (important for compaction) |
Returns
Promise<Agent>
setModel()
setModel(modelId): void;
Defined in: agent.ts:1581
Change the model for subsequent LLM calls (same provider only).
Takes effect on the next run() or stream() call — never interrupts a running turn. Conversation history is preserved (it’s provider-agnostic). Emits a model_changed event.
Use this to switch between models within the same provider, e.g., Claude Sonnet → Claude Opus for a harder task, then back.
Parameters
| Parameter | Type | Description |
|---|---|---|
modelId | string | The new model ID (e.g., ‘claude-opus-4-20250514’) |
Returns
void
Throws
If modelId is empty or not a string
Example
console.log(agent.getModel()); // 'claude-sonnet-4-20250514'
agent.setModel('claude-opus-4-20250514');
// Next run() uses Opus
const result = await agent.run('Solve this complex problem');
agent.setModel('claude-sonnet-4-20250514'); // Switch back
Since
0.5.8
setPermissionLevel()
setPermissionLevel(
toolName,
level,
description?): this;
Defined in: agent.ts:1760
Set the permission level for a tool
Parameters
| Parameter | Type | Description |
|---|---|---|
toolName | string | Tool name or pattern |
level | PermissionLevel | Permission level |
description? | string | Optional description |
Returns
this
stream()
stream(userMessage, options?): AsyncIterable<AgentEvent>;
Defined in: agent.ts:3970
Stream the agent’s response as events.
Yields AgentEvent objects in real time as the agent thinks, calls tools, and generates text. Use this for building interactive UIs that show progress as it happens.
Parameters
| Parameter | Type | Description |
|---|---|---|
userMessage | string | The user’s message |
options? | RunOptions | Optional run configuration |
Returns
AsyncIterable<AgentEvent>
An async iterable of agent events
Example
for await (const event of agent.stream('Explain this code')) {
if (event.type === 'llm_chunk') {
process.stdout.write(event.chunk.text ?? '');
} else if (event.type === 'tool_start') {
console.log(`\nCalling tool: ${event.name}`);
} else if (event.type === 'done') {
console.log('\n\nDone!');
}
}