Skip to content

Agent

Defined in: src/agent/agent.ts:413

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.

  • InvokableAgent
new Agent(config?): Agent;

Defined in: src/agent/agent.ts:560

Creates an instance of the Agent.

ParameterTypeDescription
config?AgentConfigThe configuration for the agent.

Agent

messages: Message[];

Defined in: src/agent/agent.ts:420

The conversation history of messages between user and assistant.

LocalAgent.messages


readonly appState: StateStore;

Defined in: src/agent/agent.ts:425

App state storage accessible to tools and application logic. State is not passed to the model during inference.

LocalAgent.appState


readonly modelState: StateStore;

Defined in: src/agent/agent.ts:431

Runtime state for the model provider. Used by stateful models to persist provider-specific data (e.g., response IDs for conversation chaining) across invocations.

LocalAgent.modelState


model: Model;

Defined in: src/agent/agent.ts:437

The model provider used by the agent for inference.

LocalAgent.model


systemPrompt?: SystemPrompt;

Defined in: src/agent/agent.ts:444

The system prompt to pass to the model provider.

LocalAgent.systemPrompt


readonly name: string;

Defined in: src/agent/agent.ts:449

The name of the agent.

InvokableAgent.name


readonly id: string;

Defined in: src/agent/agent.ts:454

The unique identifier of the agent instance.

LocalAgent.id


readonly description?: string;

Defined in: src/agent/agent.ts:459

Optional description of what the agent does.

InvokableAgent.description


readonly contextManager?: ContextManager;

Defined in: src/agent/agent.ts:464

The context manager for strategy-driven offloading, if configured.

LocalAgent.contextManager


readonly sessionManager?: SessionManager;

Defined in: src/agent/agent.ts:468

The session manager for saving and restoring agent sessions, if configured.


readonly memoryManager?: MemoryManager;

Defined in: src/agent/agent.ts:474

The memory manager for cross-session memory retrieval and storage, if configured.


readonly storage?: Storage<string, string>;

Defined in: src/agent/agent.ts:479

Default storage backend for agent subsystems.

LocalAgent.storage


readonly baggageAttributes: Readonly<Record<string, string>>;

Defined in: src/agent/agent.ts:484

OpenTelemetry baggage entries attached to the context for every invocation.


_interruptState: InterruptState;

Defined in: src/agent/agent.ts:547

Interrupt state for human-in-the-loop workflows.

get sandbox(): Sandbox;

Defined in: src/agent/agent.ts:494

Execution environment for running commands, code, and file operations.

DefaultNotConfiguredError if no sandbox is configured for this environment (e.g. browsers, where no host default is registered).

Sandbox

LocalAgent.sandbox


get auxModel(): Model;

Defined in: src/agent/agent.ts:508

Model for auxiliary side calls (summarization, memory extraction, classification, steering, web fetch). Resolution order: configured auxModel > model.

Reading always yields a resolved Model. Assigning accepts a Model, a Bedrock model ID string, or undefined to revert to following model. Memory extraction resolves its model when attached to the agent and keeps it; every other side call resolves it at call time.

Error if assigned a ModelRouter.

Model

set auxModel(auxModel): void;

Defined in: src/agent/agent.ts:512

Model used for auxiliary side calls; defaults to model. See Agent.auxModel.

ParameterType
auxModel| string | Model<BaseModelConfig>

void

LocalAgent.auxModel


get sessionId(): string;

Defined in: src/agent/agent.ts:522

A stable, unique identifier for the current conversation session.

If a SessionManager is attached, delegates to its sessionId. Otherwise, lazily generates and caches a random 8-character hex string.

string

LocalAgent.sessionId


get tools(): Tool[];

Defined in: src/agent/agent.ts:976

The tools this agent can use.

Tool[]


get toolRegistry(): ToolRegistry;

Defined in: src/agent/agent.ts:983

The tool registry for managing the agent’s tools.

ToolRegistry

LocalAgent.toolRegistry


get toolExecutor():
| ConcurrentToolExecutor
| SequentialToolExecutor;

Defined in: src/agent/agent.ts:996

Executor for tool calls from a single assistant turn.

Reading always yields the resolved executor instance. Assigning accepts an executor instance or a ToolExecutorStrategy string shorthand, which is resolved to the matching instance on write.

Error if assigned an unrecognized string shorthand.

| ConcurrentToolExecutor | SequentialToolExecutor

set toolExecutor(toolExecutor): void;

Defined in: src/agent/agent.ts:1000

ParameterType
toolExecutor| ConcurrentToolExecutor | SequentialToolExecutor | ToolExecutorStrategy

void


get metrics(): AgentMetrics;

Defined in: src/agent/agent.ts:1007

Read-only snapshot of accumulated agent metrics (cycles, token usage, tool stats).

AgentMetrics

LocalAgent.metrics


get isInvoking(): boolean;

Defined in: src/agent/agent.ts:1014

Whether the agent is currently processing an invocation.

boolean


get tool(): ToolCallerProxy;

Defined in: src/agent/agent.ts:1035

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).

ToolCallerProxy


get cancelSignal(): AbortSignal;

Defined in: src/agent/agent.ts:1045

The cancellation signal for the current invocation.

SDK-managed tool contexts receive this as context.cancelSignal for cancellable operations. Hooks can check event.agent.cancelSignal.aborted to detect cancellation.

AbortSignal

LocalAgent.cancelSignal

addHook<T>(
eventType,
callback,
options?
): HookCleanup;

Defined in: src/agent/agent.ts:743

Register a hook callback for a specific event type.

Type Parameter
T extends HookableEvent
ParameterTypeDescription
eventTypeHookableEventConstructor<T>The event class constructor to register the callback for
callbackHookCallback<T>The callback function to invoke when the event occurs
options?HookCallbackOptionsOptional configuration including execution order

HookCleanup

Cleanup function that removes the callback when invoked

const agent = new Agent({ model })
const cleanup = agent.addHook(BeforeInvocationEvent, (event) => {
console.log('Invocation started')
})
// Later, to remove the hook:
cleanup()

LocalAgent.addHook


addMiddleware<TContext, TResult, TEvent>(phase, handler): () => void;

Defined in: src/agent/agent.ts:763

Register an Input phase handler that transforms context before execution. Input handlers run before Wrap and Output handlers.

Type Parameter
TContext
TResult
TEvent
ParameterType
phaseMiddlewareInputPhase<TContext, TResult, TEvent>
handlerMiddlewareInputHandler<TContext>

() => void

agent.addMiddleware(InvokeModelStage.Input, async (context) => ({
...context,
systemPrompt: injectToSystemPrompt(context),
}))

LocalAgent.addMiddleware

addMiddleware<TContext, TResult, TEvent>(phase, handler): () => void;

Defined in: src/agent/agent.ts:771

Register a Wrap phase handler via the explicit .Wrap sub-token. Equivalent to passing the stage token directly.

Type Parameter
TContext
TResult
TEvent
ParameterType
phaseMiddlewareWrapPhase<TContext, TResult, TEvent>
handlerMiddlewareHandler<TContext, TResult, TEvent>

() => void

LocalAgent.addMiddleware

addMiddleware<TContext, TResult, TEvent>(phase, handler): () => void;

Defined in: src/agent/agent.ts:788

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 Parameter
TContext
TResult
TEvent
ParameterType
phaseMiddlewareOutputPhase<TContext, TResult, TEvent>
handlerMiddlewareOutputHandler<TResult>

() => void

agent.addMiddleware(InvokeModelStage.Output, async (result) => {
log(`Model returned stopReason=${result.result.stopReason}`)
return result
})

LocalAgent.addMiddleware

addMiddleware<TContext, TResult, TEvent>(stage, handler): () => void;

Defined in: src/agent/agent.ts:813

Register a middleware handler for a given stage (Wrap phase). Middleware wraps stage execution and can intercept, transform, or short-circuit operations.

Type Parameter
TContext
TResult
TEvent
ParameterTypeDescription
stageMiddlewareStage<TContext, TResult, TEvent>The stage token identifying the interception point
handlerMiddlewareHandler<TContext, TResult, TEvent>The middleware handler function (async generator)

A cleanup function that removes the middleware when called

() => void

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()

LocalAgent.addMiddleware


initialize(): Promise<void>;

Defined in: src/agent/agent.ts:859

Promise<void>


cancel(): void;

Defined in: src/agent/agent.ts:1077

Cancels the current agent invocation cooperatively.

The agent will stop at the next cancellation-safe point:

  • 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 context.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.

void

const agent = new Agent({ model, tools })
// Cancel after 5 seconds
setTimeout(() => agent.cancel(), 5000)
const result = await agent.invoke('Do something')
console.log(result.stopReason) // 'cancelled'

invoke(args, options?): Promise<AgentResult>;

Defined in: src/agent/agent.ts:1109

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.

ParameterTypeDescription
argsInvokeArgsArguments for invoking the agent
options?InvokeOptionsOptional per-invocation options

Promise<AgentResult>

Promise that resolves to the final AgentResult

const agent = new Agent({ model, tools })
const result = await agent.invoke('What is 2 + 2?')
console.log(result.lastMessage) // Agent's response

InvokableAgent.invoke


shutdown(): Promise<void>;

Defined in: src/agent/agent.ts:1132

Runs the agent’s shutdown procedures at end of life. Safe to call more than once, and a no-op when there is nothing to release.

Call it directly when you own the agent’s lifecycle (e.g. draining on a shutdown signal), or bind the agent with await using to run it automatically on scope exit.

Promise<void>

await using agent = await createHarness()
await agent.invoke('summarize the repo')
// agent.shutdown() runs here as the scope exits

[asyncDispose](): Promise<void>;

Defined in: src/agent/agent.ts:1140

Runs Agent.shutdown when the agent leaves an await using scope, on normal exit and on throw, so its shutdown procedures run without a manual finally.

Promise<void>


stream(args, options?): AsyncGenerator<AgentStreamEvent, AgentResult, undefined>;

Defined in: src/agent/agent.ts:1174

Streams the agent execution, yielding events and returning the final result.

The agent loop manages the conversation flow by:

  1. Streaming model responses and yielding all events
  2. Executing tools when the model requests them
  3. 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

ParameterTypeDescription
argsInvokeArgsArguments for invoking the agent
options?InvokeOptionsOptional per-invocation options

AsyncGenerator<AgentStreamEvent, AgentResult, undefined>

Async generator that yields AgentStreamEvent objects and returns AgentResult

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 conversation

InvokableAgent.stream


asTool(options?): Tool;

Defined in: src/agent/agent.ts:1499

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.

ParameterTypeDescription
options?AgentAsToolOptionsOptional configuration for the tool name, description, and context preservation

Tool

A Tool wrapping this agent

const researcher = new Agent({ name: 'researcher', description: 'Finds info', printer: false })
// Explicit wrapping
const writer = new Agent({ tools: [researcher.asTool()] })
// Automatic wrapping (equivalent)
const writer = new Agent({ tools: [researcher] })

takeSnapshot(options): Snapshot;

Defined in: src/agent/agent.ts:1533

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:

  1. Start with preset fields (e.g. 'session' captures all fields)
  2. Add any include fields
  3. Remove any exclude fields
ParameterTypeDescription
optionsTakeSnapshotOptionsControls which fields to capture and optional app data to store

Snapshot

A Snapshot containing the captured agent state

Error if no fields would be included after applying options

// Capture all session-relevant state
const snapshot = agent.takeSnapshot({ preset: 'session' })
// Capture only messages and state
const partial = agent.takeSnapshot({ include: ['messages', 'state'] })
// Capture session state but exclude interrupts
const noInterrupts = agent.takeSnapshot({ preset: 'session', exclude: ['interrupts'] })
// Attach application-owned metadata
const withMeta = agent.takeSnapshot({ preset: 'session', appData: { userId: 'u-123' } })

LocalAgent.takeSnapshot


loadSnapshot(snapshot): void;

Defined in: src/agent/agent.ts:1562

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.

ParameterTypeDescription
snapshotSnapshotThe snapshot to restore from

void

Error if snapshot.schemaVersion is incompatible or scope is wrong

// Save and restore a conversation checkpoint
const checkpoint = agent.takeSnapshot({ preset: 'session' })
// ... agent continues processing ...
// Restore to the checkpoint
agent.loadSnapshot(checkpoint)
// Restore from a JSON-serialized snapshot (e.g. from storage)
const stored = JSON.parse(savedSnapshotJson)
agent.loadSnapshot(stored)

LocalAgent.loadSnapshot