Skip to content

Agent

The core entry point of Agent Express.

An Agent wraps a language model with middleware-based lifecycle hooks. Create an agent, add middleware with .use(), and run it with .run().

const agent = new Agent({
name: "assistant",
model: "anthropic/claude-sonnet-4-6",
instructions: "You are a helpful assistant.",
})
// Multi-turn
await agent.init()
const session = agent.session()
const r = await session.run("Hello!").result
await session.close()
await agent.dispose()
// Convenience one-liner
const { text } = await agent.run("Hello!").result

new Agent(def): Agent

AgentDef

Agent

readonly name: string

Agent name used for debugging and tracing.

[asyncDispose](): Promise<void>

Alias for dispose() — enables await using agent = new Agent(...).

Promise<void>


dispose(): Promise<void>

Dispose the agent: auto-closes open sessions, then unwinds the agent onion triggering cleanup in all middleware (reverse registration order). Idempotent — safe to call on an uninitialized agent.

Promise<void>


init(): Promise<void>

Explicitly initialize the agent: resolve model, run agent middleware (connect MCP servers, register tools, etc.). Idempotent.

Promise<void>

await agent.init() // MCP servers connect, tools register

run(input, opts?): AgentRun

Convenience: auto-init + create session + single turn + close session.

string

User message text

RunOptions

Optional run options (output schema)

AgentRun

AgentRun (dual interface: streaming + result promise)

const { text } = await agent.run("Hello!").result

session(opts?): Session

Create a new session for multi-turn conversation. Auto-initializes the agent if not already initialized.

SessionOptions

Optional session configuration (custom ID for persistence)

Session

A Session object for executing turns


use(middleware): this

Register middleware on this agent. Chainable.

Accepts a Middleware object, an array of middleware, a plain function (treated as a turn hook), or a scope + function pair.

Middleware

this

this agent (for chaining)

use(middlewares): this

Register middleware on this agent. Chainable.

Accepts a Middleware object, an array of middleware, a plain function (treated as a turn hook), or a scope + function pair.

Middleware[]

this

this agent (for chaining)

use(fn): this

Register middleware on this agent. Chainable.

Accepts a Middleware object, an array of middleware, a plain function (treated as a turn hook), or a scope + function pair.

TurnHookFn

this

this agent (for chaining)

use<S>(scope, fn): this

Register middleware on this agent. Chainable.

Accepts a Middleware object, an array of middleware, a plain function (treated as a turn hook), or a scope + function pair.

S extends HookScope

S

ScopeHookFn[S]

this

this agent (for chaining)