Agent
Defined in: src/agent/agent.ts:178
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:242
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:185
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:190
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.appStatemodel: Model;Defined in: src/agent/agent.ts:196
The model provider used by the agent for inference.
systemPrompt?
Section titled “systemPrompt?”optional systemPrompt?: SystemPrompt;Defined in: src/agent/agent.ts:201
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:206
The name of the agent.
Implementation of
Section titled “Implementation of”InvokableAgent.namereadonly id: string;Defined in: src/agent/agent.ts:211
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:216
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:221
The session manager for saving and restoring agent sessions, if configured.
Accessors
Section titled “Accessors”Get Signature
Section titled “Get Signature”get tools(): Tool[];Defined in: src/agent/agent.ts:369
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:376
The tool registry for managing the agent’s tools.
Returns
Section titled “Returns”ToolRegistry
Implementation of
Section titled “Implementation of”LocalAgent.toolRegistrycancelSignal
Section titled “cancelSignal”Get Signature
Section titled “Get Signature”get cancelSignal(): AbortSignal;Defined in: src/agent/agent.ts:386
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): HookCleanup;Defined in: src/agent/agent.ts:313
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 |
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.addHookinitialize()
Section titled “initialize()”initialize(): Promise<void>;Defined in: src/agent/agent.ts:317
Returns
Section titled “Returns”Promise<void>
cancel()
Section titled “cancel()”cancel(): void;Defined in: src/agent/agent.ts:418
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:450
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:489
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:569
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] })