AgentBuilder

Struct AgentBuilder 

Source
pub struct AgentBuilder { /* private fields */ }
Expand description

Fluent builder for constructing crate::Agent instances with custom configuration.

Use crate::Agent::builder() to create a new builder instance.

Implementations§

Source§

impl AgentBuilder

Source

pub async fn build(self) -> Result<Agent>

Source§

impl AgentBuilder

Source

pub fn new() -> Self

Creates a new builder with default configuration.

Source

pub fn agent_config(self, config: AgentConfig) -> Self

Sets the complete agent configuration, replacing all defaults.

Source

pub fn provider_config(self, config: ProviderConfig) -> Self

Sets the API provider configuration (timeouts, beta features, etc.).

Source

pub async fn auth(self, auth: impl Into<Auth>) -> Result<Self>

Configures authentication for the API.

§Supported Methods
  • Auth::from_env() - Uses ANTHROPIC_API_KEY environment variable
  • Auth::api_key("sk-...") - Explicit API key
  • Auth::claude_cli() - Uses Claude CLI OAuth (requires cli-integration feature)
  • Auth::bedrock("region") - AWS Bedrock (requires aws feature)
  • Auth::vertex("project", "region") - GCP Vertex AI (requires gcp feature)
§Example
let agent = Agent::builder()
    .auth(Auth::from_env()).await?
    .build().await?;
Source

pub fn oauth_config(self, config: OAuthConfig) -> Self

Sets OAuth configuration for token refresh.

Source

pub fn supports_server_tools(&self) -> bool

Returns whether the current auth method supports server-side tools.

Source

pub fn models(self, config: ModelConfig) -> Self

Sets both primary and small model configurations.

Source

pub fn model(self, model: impl Into<String>) -> Self

Sets the primary model for main operations.

Default: claude-sonnet-4-5-20250514

Source

pub fn small_model(self, model: impl Into<String>) -> Self

Sets the smaller model for quick operations (e.g., subagents).

Default: claude-haiku-4-5-20251001

Source

pub fn max_tokens(self, tokens: u32) -> Self

Sets the maximum tokens per response.

Default: 8192. Values exceeding this require the 128k beta feature, which is automatically enabled when using ProviderConfig::with_max_tokens.

Source

pub fn extended_context(self, enabled: bool) -> Self

Enables extended context window (1M tokens for supported models).

Requires the context-1m-2025-08-07 beta feature. Currently supported: claude-sonnet-4-5-20250929

Source

pub fn tools(self, access: ToolAccess) -> Self

Sets tool access policy.

§Options
  • ToolAccess::all() - Enable all built-in tools
  • ToolAccess::none() - Disable all tools
  • ToolAccess::only(["Read", "Write"]) - Enable specific tools
  • ToolAccess::except(["Bash"]) - Enable all except specific tools
Source

pub fn tool<T: Tool + 'static>(self, tool: T) -> Self

Registers a custom tool implementation.

Source

pub fn working_dir(self, path: impl Into<PathBuf>) -> Self

Sets the working directory for file operations.

Source

pub fn max_iterations(self, max: usize) -> Self

Sets the maximum number of agentic loop iterations.

Default: 100

Source

pub fn timeout(self, timeout: Duration) -> Self

Sets the overall execution timeout.

Default: 300 seconds

Source

pub fn chunk_timeout(self, timeout: Duration) -> Self

Sets the timeout between streaming chunks.

This timeout detects stalled connections when no data is received for the specified duration during streaming responses.

Default: 60 seconds

For large projects or slow network conditions, consider increasing this value (e.g., 180 seconds).

Source

pub fn auto_compact(self, enabled: bool) -> Self

Enables or disables automatic context compaction.

Default: true

Source

pub fn compact_keep_messages(self, count: usize) -> Self

Sets the number of messages to preserve during compaction.

Default: 4

Source

pub fn system_prompt(self, prompt: impl Into<String>) -> Self

Sets a custom system prompt, replacing the default.

Source

pub fn system_prompt_mode(self, mode: SystemPromptMode) -> Self

Sets how the system prompt is applied.

Source

pub fn append_system_prompt(self, prompt: impl Into<String>) -> Self

Appends to the default system prompt instead of replacing it.

Source

pub fn output_style(self, style: OutputStyle) -> Self

Sets the output style for response formatting.

Source

pub fn output_style_name(self, name: impl Into<String>) -> Self

Sets the output style by name (loaded from configuration).

Source

pub fn output_schema(self, schema: Value) -> Self

Sets a JSON schema for structured output.

Source

pub fn structured_output<T: JsonSchema>(self) -> Self

Enables structured output with automatic schema generation.

Source

pub fn permission_policy(self, policy: PermissionPolicy) -> Self

Sets the complete permission policy.

Source

pub fn permission_mode(self, mode: PermissionMode) -> Self

Sets the permission mode (permissive, default, or strict).

Source

pub fn allow_tool(self, pattern: impl Into<String>) -> Self

Adds a rule to allow a tool or pattern.

Source

pub fn deny_tool(self, pattern: impl Into<String>) -> Self

Adds a rule to deny a tool or pattern.

Source

pub fn env(self, key: impl Into<String>, value: impl Into<String>) -> Self

Sets an environment variable for tool execution.

Source

pub fn envs( self, vars: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>, ) -> Self

Sets multiple environment variables for tool execution.

Source

pub fn allow_domain(self, domain: impl Into<String>) -> Self

Adds a domain to the network allowlist.

Source

pub fn deny_domain(self, domain: impl Into<String>) -> Self

Adds a domain to the network blocklist.

Source

pub fn sandbox_enabled(self, enabled: bool) -> Self

Enables or disables sandbox isolation.

Source

pub fn exclude_command(self, command: impl Into<String>) -> Self

Excludes a command from sandbox restrictions.

Source

pub fn max_budget_usd(self, amount: f64) -> Self

Sets the maximum budget in USD.

Source

pub fn tenant_id(self, id: impl Into<String>) -> Self

Sets the tenant ID for multi-tenant budget tracking.

Source

pub fn tenant_budget_manager(self, manager: TenantBudgetManager) -> Self

Sets a shared tenant budget manager.

Source

pub fn fallback_model(self, model: impl Into<String>) -> Self

Sets the model to fall back to when budget is exceeded.

Source

pub fn fallback(self, config: FallbackConfig) -> Self

Sets the complete fallback configuration.

Source

pub fn session_manager(self, manager: SessionManager) -> Self

Sets a custom session manager for persistence.

Source

pub async fn fork_session(self, session_id: impl Into<String>) -> Result<Self>

Forks an existing session, creating a new branch.

Source

pub async fn resume_session(self, session_id: impl Into<String>) -> Result<Self>

Resumes an existing session by ID.

Source

pub fn messages(self, messages: Vec<Message>) -> Self

Sets initial messages for the conversation.

Source

pub fn mcp_server( self, name: impl Into<String>, config: McpServerConfig, ) -> Self

Adds an MCP server configuration.

Source

pub fn mcp_stdio( self, name: impl Into<String>, command: impl Into<String>, args: Vec<String>, ) -> Self

Adds an MCP server using stdio transport.

Source

pub fn mcp_manager(self, manager: McpManager) -> Self

Sets an owned MCP manager.

Source

pub fn shared_mcp_manager(self, manager: Arc<McpManager>) -> Self

Sets a shared MCP manager (for multi-agent scenarios).

Source

pub fn mcp_toolset(self, toolset: McpToolset) -> Self

Registers an MCP toolset configuration for deferred loading.

Enables tool search with default configuration.

Source

pub fn tool_search_config(self, config: ToolSearchConfig) -> Self

Sets the tool search configuration.

Source

pub fn tool_search_threshold(self, threshold: f64) -> Self

Sets the tool search threshold as a fraction of context window (0.0 - 1.0).

Source

pub fn tool_search_mode(self, mode: SearchMode) -> Self

Sets the search mode for tool search.

Source

pub fn always_load_tools( self, tools: impl IntoIterator<Item = impl Into<String>>, ) -> Self

Sets tools that should always be loaded immediately (never deferred).

Source

pub fn shared_tool_search_manager(self, manager: Arc<ToolSearchManager>) -> Self

Sets a shared tool search manager.

Source

pub fn skill_registry(self, registry: IndexRegistry<SkillIndex>) -> Self

Sets a complete skill registry.

Source

pub fn skill(self, skill: SkillIndex) -> Self

Registers a single skill index.

Source

pub fn rule_index(self, index: RuleIndex) -> Self

Adds a rule index for rule discovery.

Source

pub fn memory_content(self, content: impl Into<String>) -> Self

Adds memory content (CLAUDE.md style).

Source

pub fn local_memory_content(self, content: impl Into<String>) -> Self

Adds local memory content (CLAUDE.local.md style).

Source

pub fn subagent_registry(self, registry: IndexRegistry<SubagentIndex>) -> Self

Sets a complete subagent registry.

Source

pub fn subagent(self, subagent: SubagentIndex) -> Self

Registers a single subagent.

Source

pub fn hook<H: Hook + 'static>(self, hook: H) -> Self

Registers an event hook.

Source§

impl AgentBuilder

Source

pub async fn from_claude_code(self, path: impl AsRef<Path>) -> Result<Self>

Available on crate feature cli-integration only.

Initializes Claude Code CLI authentication and working directory.

This is the minimal setup. Use with_*_resources() methods to enable loading from specific levels. Resources are loaded during build() in a fixed order: Enterprise → User → Project → Local.

§Example
let agent = Agent::builder()
    .from_claude_code("./project").await?
    .with_user_resources()
    .with_project_resources()
    .build()
    .await?;
Source

pub fn with_enterprise_resources(self) -> Self

Available on crate feature cli-integration only.

Enables loading of enterprise-level resources during build.

Resources are loaded from system configuration paths:

  • macOS: /Library/Application Support/ClaudeCode/
  • Linux: /etc/claude-code/

This method only sets a flag; actual loading happens during build() in the fixed order: Enterprise → User → Project → Local.

Source

pub fn with_user_resources(self) -> Self

Available on crate feature cli-integration only.

Enables loading of user-level resources during build.

Resources are loaded from ~/.claude/.

This method only sets a flag; actual loading happens during build() in the fixed order: Enterprise → User → Project → Local.

Source

pub fn with_project_resources(self) -> Self

Available on crate feature cli-integration only.

Enables loading of project-level resources during build.

Resources are loaded from {working_dir}/.claude/. Requires from_claude_code() to be called first to set the working directory.

This method only sets a flag; actual loading happens during build() in the fixed order: Enterprise → User → Project → Local.

Source

pub fn with_local_resources(self) -> Self

Available on crate feature cli-integration only.

Enables loading of local-level resources during build.

Loads CLAUDE.local.md and settings.local.json from the project directory. These are typically gitignored and contain personal/machine-specific settings. Requires from_claude_code() to be called first to set the working directory.

This method only sets a flag; actual loading happens during build() in the fixed order: Enterprise → User → Project → Local.

Trait Implementations§

Source§

impl Default for AgentBuilder

Source§

fn default() -> AgentBuilder

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FutureExt for T

Source§

fn with_context(self, otel_cx: Context) -> WithContext<Self>

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
Source§

fn with_current_context(self) -> WithContext<Self>

Attaches the current Context to this type, returning a WithContext wrapper. Read more
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<Unshared, Shared> IntoShared<Shared> for Unshared
where Shared: FromUnshared<Unshared>,

Source§

fn into_shared(self) -> Shared

Creates a shared type from an unshared type.
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more