Agent
Defined in: src/agent/agent.ts:372
Orchestrates the interaction between a model, a set of tools, and MCP clients. The Agent is responsible for managing the lifecycle of tools and clients and invoking the core decision-making loop.
Implements
Section titled “Implements”InvokableAgent
Constructors
Section titled “Constructors”Constructor
Section titled “Constructor”new Agent(config?): Agent;Defined in: src/agent/agent.ts:466
Creates an instance of the Agent.
Parameters
Section titled “Parameters”| Parameter | Type | Description |
|---|---|---|
config? | AgentConfig | The configuration for the agent. |
Returns
Section titled “Returns”Agent
Properties
Section titled “Properties”messages
Section titled “messages”messages: Message[];Defined in: src/agent/agent.ts:379
The conversation history of messages between user and assistant.
Implementation of
Section titled “Implementation of”LocalAgent.messagesappState
Section titled “appState”readonly appState: StateStore;Defined in: src/agent/agent.ts:384
App state storage accessible to tools and application logic. State is not passed to the model during inference.
Implementation of
Section titled “Implementation of”LocalAgent.appStatemodelState
Section titled “modelState”readonly modelState: StateStore;Defined in: src/agent/agent.ts:390
Runtime state for the model provider. Used by stateful models to persist provider-specific data (e.g., response IDs for conversation chaining) across invocations.
Implementation of
Section titled “Implementation of”LocalAgent.modelStatemodel: Model;Defined in: src/agent/agent.ts:396
The model provider used by the agent for inference.
Implementation of
Section titled “Implementation of”LocalAgent.modelsystemPrompt?
Section titled “systemPrompt?”optional systemPrompt?: SystemPrompt;Defined in: src/agent/agent.ts:401
The system prompt to pass to the model provider.
Implementation of
Section titled “Implementation of”LocalAgent.systemPromptreadonly name: string;Defined in: src/agent/agent.ts:406
The name of the agent.
Implementation of
Section titled “Implementation of”InvokableAgent.namereadonly id: string;Defined in: src/agent/agent.ts:411
The unique identifier of the agent instance.
Implementation of
Section titled “Implementation of”LocalAgent.iddescription?
Section titled “description?”readonly optional description?: string;Defined in: src/agent/agent.ts:416
Optional description of what the agent does.
Implementation of
Section titled “Implementation of”InvokableAgent.descriptionsessionManager?
Section titled “sessionManager?”readonly optional sessionManager?: SessionManager;Defined in: src/agent/agent.ts:421
The session manager for saving and restoring agent sessions, if configured.
memoryManager?
Section titled “memoryManager?”readonly optional memoryManager?: MemoryManager;Defined in: src/agent/agent.ts:425
The memory manager for cross-session memory retrieval and storage, if configured.
_interruptState
Section titled “_interruptState”_interruptState: InterruptState;Defined in: src/agent/agent.ts:456
Interrupt state for human-in-the-loop workflows.
Accessors
Section titled “Accessors”sandbox
Section titled “sandbox”Get Signature
Section titled “Get Signature”get sandbox(): Sandbox;Defined in: src/agent/agent.ts:435
Execution environment for running commands, code, and file operations.
Throws
Section titled “Throws”DefaultNotConfiguredError if no sandbox is configured for this environment (e.g. browsers, where no host default is registered).
Returns
Section titled “Returns”Implementation of
Section titled “Implementation of”LocalAgent.sandboxGet Signature
Section titled “Get Signature”get tools(): Tool[];Defined in: src/agent/agent.ts:858
The tools this agent can use.
Returns
Section titled “Returns”Tool[]
toolRegistry
Section titled “toolRegistry”Get Signature
Section titled “Get Signature”get toolRegistry(): ToolRegistry;Defined in: src/agent/agent.ts:865
The tool registry for managing the agent’s tools.
Returns
Section titled “Returns”ToolRegistry
Implementation of
Section titled “Implementation of”LocalAgent.toolRegistryisInvoking
Section titled “isInvoking”Get Signature
Section titled “Get Signature”get isInvoking(): boolean;Defined in: src/agent/agent.ts:872
Whether the agent is currently processing an invocation.
Returns
Section titled “Returns”boolean
Get Signature
Section titled “Get Signature”get tool(): ToolCallerProxy;Defined in: src/agent/agent.ts:893
Direct tool calling accessor.
Returns a proxy where each property is a ToolHandle with
.invoke() and .stream() methods:
const result = await agent.tool.calculator!.invoke({ a: 5, b: 3 })
for await (const event of agent.tool.calculator!.stream({ a: 5, b: 3 })) { console.log('progress:', event)}Supports underscore-to-hyphen and case-insensitive name resolution.
Results are recorded in message history by default (pass
{ recordDirectToolCall: false } to skip).
Returns
Section titled “Returns”cancelSignal
Section titled “cancelSignal”Get Signature
Section titled “Get Signature”get cancelSignal(): AbortSignal;Defined in: src/agent/agent.ts:903
The cancellation signal for the current invocation.
Tools can pass this to cancellable operations (e.g., fetch(url, { signal: agent.cancelSignal })).
Hooks can check event.agent.cancelSignal.aborted to detect cancellation.
Returns
Section titled “Returns”AbortSignal
Implementation of
Section titled “Implementation of”LocalAgent.cancelSignalMethods
Section titled “Methods”addHook()
Section titled “addHook()”addHook<T>( eventType, callback, options?): HookCleanup;Defined in: src/agent/agent.ts:604
Register a hook callback for a specific event type.
Type Parameters
Section titled “Type Parameters”| Type Parameter |
|---|
T extends HookableEvent |
Parameters
Section titled “Parameters”| Parameter | Type | Description |
|---|---|---|
eventType | HookableEventConstructor<T> | The event class constructor to register the callback for |
callback | HookCallback<T> | The callback function to invoke when the event occurs |
options? | HookCallbackOptions | Optional configuration including execution order |
Returns
Section titled “Returns”HookCleanup
Cleanup function that removes the callback when invoked
Example
Section titled “Example”const agent = new Agent({ model })
const cleanup = agent.addHook(BeforeInvocationEvent, (event) => { console.log('Invocation started')})
// Later, to remove the hook:cleanup()Implementation of
Section titled “Implementation of”LocalAgent.addHookaddMiddleware()
Section titled “addMiddleware()”Call Signature
Section titled “Call Signature”addMiddleware<TContext, TResult, TEvent>(phase, handler): () => void;Defined in: src/agent/agent.ts:624
Register an Input phase handler that transforms context before execution. Input handlers run before Wrap and Output handlers.
Type Parameters
Section titled “Type Parameters”| Type Parameter |
|---|
TContext |
TResult |
TEvent |
Parameters
Section titled “Parameters”| Parameter | Type |
|---|---|
phase | MiddlewareInputPhase<TContext, TResult, TEvent> |
handler | MiddlewareInputHandler<TContext> |
Returns
Section titled “Returns”() => void
Example
Section titled “Example”agent.addMiddleware(InvokeModelStage.Input, async (context) => ({ ...context, systemPrompt: injectToSystemPrompt(context),}))Implementation of
Section titled “Implementation of”LocalAgent.addMiddlewareCall Signature
Section titled “Call Signature”addMiddleware<TContext, TResult, TEvent>(phase, handler): () => void;Defined in: src/agent/agent.ts:632
Register a Wrap phase handler via the explicit .Wrap sub-token.
Equivalent to passing the stage token directly.
Type Parameters
Section titled “Type Parameters”| Type Parameter |
|---|
TContext |
TResult |
TEvent |
Parameters
Section titled “Parameters”| Parameter | Type |
|---|---|
phase | MiddlewareWrapPhase<TContext, TResult, TEvent> |
handler | MiddlewareHandler<TContext, TResult, TEvent> |
Returns
Section titled “Returns”() => void
Implementation of
Section titled “Implementation of”LocalAgent.addMiddlewareCall Signature
Section titled “Call Signature”addMiddleware<TContext, TResult, TEvent>(phase, handler): () => void;Defined in: src/agent/agent.ts:649
Register an Output phase handler that transforms the result after execution. Output handlers see the result after Wrap handlers complete. Execution order: Input → Wrap → Output.
Type Parameters
Section titled “Type Parameters”| Type Parameter |
|---|
TContext |
TResult |
TEvent |
Parameters
Section titled “Parameters”| Parameter | Type |
|---|---|
phase | MiddlewareOutputPhase<TContext, TResult, TEvent> |
handler | MiddlewareOutputHandler<TResult> |
Returns
Section titled “Returns”() => void
Example
Section titled “Example”agent.addMiddleware(InvokeModelStage.Output, async (result) => { log(`Model returned stopReason=${result.result.stopReason}`) return result})Implementation of
Section titled “Implementation of”LocalAgent.addMiddlewareCall Signature
Section titled “Call Signature”addMiddleware<TContext, TResult, TEvent>(stage, handler): () => void;Defined in: src/agent/agent.ts:674
Register a middleware handler for a given stage (Wrap phase). Middleware wraps stage execution and can intercept, transform, or short-circuit operations.
Type Parameters
Section titled “Type Parameters”| Type Parameter |
|---|
TContext |
TResult |
TEvent |
Parameters
Section titled “Parameters”| Parameter | Type | Description |
|---|---|---|
stage | MiddlewareStage<TContext, TResult, TEvent> | The stage token identifying the interception point |
handler | MiddlewareHandler<TContext, TResult, TEvent> | The middleware handler function (async generator) |
Returns
Section titled “Returns”A cleanup function that removes the middleware when called
() => void
Example
Section titled “Example”const cleanup = agent.addMiddleware(InvokeModelStage, async function* (context, next) { const start = Date.now() const result = yield* next(context) console.log(`Model call took ${Date.now() - start}ms`) return result})
// Later, remove the middleware:cleanup()Implementation of
Section titled “Implementation of”LocalAgent.addMiddlewareinitialize()
Section titled “initialize()”initialize(): Promise<void>;Defined in: src/agent/agent.ts:722
Returns
Section titled “Returns”Promise<void>
cancel()
Section titled “cancel()”cancel(): void;Defined in: src/agent/agent.ts:935
Cancels the current agent invocation cooperatively.
The agent will stop at the next cancellation checkpoint:
- During model response streaming
- Before tool execution
- Between sequential tool executions
- At the top of each agent loop cycle
If a tool is already executing, it will run to completion unless the tool checks LocalAgent.cancelSignal | cancelSignal internally.
Hook callbacks can check event.agent.cancelSignal.aborted to detect
cancellation and adjust their behavior accordingly.
The stream/invoke call will return an AgentResult with stopReason: 'cancelled'.
If the agent is not currently invoking, this is a no-op.
Returns
Section titled “Returns”void
Example
Section titled “Example”const agent = new Agent({ model, tools })
// Cancel after 5 secondssetTimeout(() => agent.cancel(), 5000)const result = await agent.invoke('Do something')console.log(result.stopReason) // 'cancelled'invoke()
Section titled “invoke()”invoke(args, options?): Promise<AgentResult>;Defined in: src/agent/agent.ts:967
Invokes the agent and returns the final result.
This is a convenience method that consumes the stream() method and returns only the final AgentResult. Use stream() if you need access to intermediate streaming events.
Parameters
Section titled “Parameters”| Parameter | Type | Description |
|---|---|---|
args | InvokeArgs | Arguments for invoking the agent |
options? | InvokeOptions | Optional per-invocation options |
Returns
Section titled “Returns”Promise<AgentResult>
Promise that resolves to the final AgentResult
Example
Section titled “Example”const agent = new Agent({ model, tools })const result = await agent.invoke('What is 2 + 2?')console.log(result.lastMessage) // Agent's responseImplementation of
Section titled “Implementation of”InvokableAgent.invokestream()
Section titled “stream()”stream(args, options?): AsyncGenerator<AgentStreamEvent, AgentResult, undefined>;Defined in: src/agent/agent.ts:1006
Streams the agent execution, yielding events and returning the final result.
The agent loop manages the conversation flow by:
- Streaming model responses and yielding all events
- Executing tools when the model requests them
- Continuing the loop until the model completes without tool use
Use this method when you need access to intermediate streaming events. For simple request/response without streaming, use invoke() instead.
An explicit goal of this method is to always leave the message array in a way that the agent can be reinvoked with a user prompt after this method completes. To that end assistant messages containing tool uses are only added after tool execution succeeds with valid toolResponses
Parameters
Section titled “Parameters”| Parameter | Type | Description |
|---|---|---|
args | InvokeArgs | Arguments for invoking the agent |
options? | InvokeOptions | Optional per-invocation options |
Returns
Section titled “Returns”AsyncGenerator<AgentStreamEvent, AgentResult, undefined>
Async generator that yields AgentStreamEvent objects and returns AgentResult
Example
Section titled “Example”const agent = new Agent({ model, tools })
for await (const event of agent.stream('Hello')) { console.log('Event:', event.type)}// Messages array is mutated in place and contains the full conversationImplementation of
Section titled “Implementation of”InvokableAgent.streamasTool()
Section titled “asTool()”asTool(options?): Tool;Defined in: src/agent/agent.ts:1241
Returns a Tool that wraps this agent, allowing it to be used as a tool by another agent.
The returned tool accepts a single input string parameter, invokes
this agent, and returns the text response as a tool result.
Note: You can also pass an Agent directly in another agent’s tools array — it will be wrapped automatically via this method.
Parameters
Section titled “Parameters”| Parameter | Type | Description |
|---|---|---|
options? | AgentAsToolOptions | Optional configuration for the tool name, description, and context preservation |
Returns
Section titled “Returns”A Tool wrapping this agent
Example
Section titled “Example”const researcher = new Agent({ name: 'researcher', description: 'Finds info', printer: false })
// Explicit wrappingconst writer = new Agent({ tools: [researcher.asTool()] })
// Automatic wrapping (equivalent)const writer = new Agent({ tools: [researcher] })takeSnapshot()
Section titled “takeSnapshot()”takeSnapshot(options): Snapshot;Defined in: src/agent/agent.ts:1275
Captures a point-in-time snapshot of the agent’s current state.
Use snapshots to checkpoint agent state for later restoration, enabling use cases like undo/redo, branching conversations, and session persistence.
Fields are selected via a preset/include/exclude model:
- Start with preset fields (e.g.
'session'captures all fields) - Add any
includefields - Remove any
excludefields
Parameters
Section titled “Parameters”| Parameter | Type | Description |
|---|---|---|
options | TakeSnapshotOptions | Controls which fields to capture and optional app data to store |
Returns
Section titled “Returns”A Snapshot containing the captured agent state
Throws
Section titled “Throws”Error if no fields would be included after applying options
Example
Section titled “Example”// Capture all session-relevant stateconst snapshot = agent.takeSnapshot({ preset: 'session' })
// Capture only messages and stateconst partial = agent.takeSnapshot({ include: ['messages', 'state'] })
// Capture session state but exclude interruptsconst noInterrupts = agent.takeSnapshot({ preset: 'session', exclude: ['interrupts'] })
// Attach application-owned metadataconst withMeta = agent.takeSnapshot({ preset: 'session', appData: { userId: 'u-123' } })Implementation of
Section titled “Implementation of”LocalAgent.takeSnapshotloadSnapshot()
Section titled “loadSnapshot()”loadSnapshot(snapshot): void;Defined in: src/agent/agent.ts:1304
Restores agent state from a previously captured snapshot.
Only fields present in snapshot.data are restored; absent fields are left
unchanged. This allows partial snapshots to update specific aspects of state
without affecting others.
Parameters
Section titled “Parameters”| Parameter | Type | Description |
|---|---|---|
snapshot | Snapshot | The snapshot to restore from |
Returns
Section titled “Returns”void
Throws
Section titled “Throws”Error if snapshot.schemaVersion is incompatible or scope is wrong
Example
Section titled “Example”// Save and restore a conversation checkpointconst checkpoint = agent.takeSnapshot({ preset: 'session' })
// ... agent continues processing ...
// Restore to the checkpointagent.loadSnapshot(checkpoint)
// Restore from a JSON-serialized snapshot (e.g. from storage)const stored = JSON.parse(savedSnapshotJson)agent.loadSnapshot(stored)Implementation of
Section titled “Implementation of”LocalAgent.loadSnapshot