Skip to main content

Agent

Struct Agent 

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

Subscriber info for fan-out event delivery

Thread-safe, Clone-able agent handle for tokio async usage. All internal state is held behind a single Arc<Mutex<>> — cloning Agent just increments the reference count. All public methods take &self.

§Sharing across tasks

let agent = Agent::new("claude-sonnet-4-6");

// Clone into another task
let agent2 = agent.clone();
let handle = tokio::spawn(async move {
    agent2.query("do work").await
});

// Subscribe from the original
let (mut sub, _guard) = agent.subscribe();

Implementations§

Source§

impl Agent

Source

pub fn new(model: &str) -> Self

Create a new agent with the given model name.

The model defaults to the AI_MODEL environment variable, then "claude-sonnet-4-6". All other config (API key, base URL, max turns, thinking) also defaults from environment.

Chain builder methods to customize:

let agent = Agent::new("claude-sonnet-4-6")
    .max_turns(20)
    .system_prompt("You are a code reviewer.")
    .thinking(ThinkingConfig::Enabled { budget_tokens: 4096 });

Returns a Cloneable handle — all internal state uses interior mutability, so Agent::query takes &self and the agent can be shared across async tasks via Arc<Agent>.

Source

pub fn model(self, model: &str) -> Self

Configure the model name.

Triggers engine recreation if the engine is already initialized.

Source

pub fn api_key(self, api_key: &str) -> Self

Set the API key.

Triggers engine recreation if the engine is already initialized.

Source

pub fn base_url(self, base_url: &str) -> Self

Set a custom base URL for the API.

Triggers engine recreation if the engine is already initialized.

Source

pub fn cwd(self, cwd: &str) -> Self

Set the working directory.

Triggers engine recreation if the engine is already initialized.

Source

pub fn system_prompt(self, prompt: &str) -> Self

Set a custom system prompt.

Source

pub fn max_turns(self, max_turns: u32) -> Self

Set the maximum number of turns.

Triggers engine recreation if the engine is already initialized.

Source

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

Set the maximum budget in USD.

Source

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

Set the maximum tokens for a single response.

Source

pub fn fallback_model(self, model: &str) -> Self

Set the fallback model.

Source

pub fn thinking(self, thinking: ThinkingConfig) -> Self

Set thinking configuration for extended thinking.

Source

pub fn tools(self, tools: Vec<ToolDefinition>) -> Self

Set tool definitions.

Source

pub fn allowed_tools(self, tools: Vec<String>) -> Self

Only allow specific tools by name.

Source

pub fn disallowed_tools(self, tools: Vec<String>) -> Self

Explicitly disallow specific tools by name.

Source

pub fn mcp_servers(self, servers: HashMap<String, McpServerConfig>) -> Self

Set MCP server configurations.

Source

pub fn on_event<F>(self, callback: F) -> Self
where F: Fn(AgentEvent) + Send + Sync + 'static,

Set an event callback for streaming agent events.

Can be called at any time (before or after query()). Takes self so it can be updated between queries for dynamic event handling.

For fully async event handling, prefer Agent::subscribe() with the EventSubscriber stream instead.

Source

pub async fn prompt(model: &str, prompt: &str) -> Result<String, AgentError>

One-shot query — creates an agent, sends the prompt, and returns the text.

Use this for single-turn interactions where you don’t need conversation history or multi-turn reuse. For persistent agents, use Agent::new() + .query().

§Example
let answer = Agent::prompt("claude-sonnet-4-6", "Explain quantum computing")
    .await?;
println!("{answer}");
Source

pub fn get_model(&self) -> String

Get the configured model name.

Source

pub fn get_session_id(&self) -> String

Get the session ID.

Source

pub fn get_messages(&self) -> Vec<Message>

Get all messages in the conversation history. Delegates to the persisted QueryEngine which owns the message state (matches TypeScript: engine.mutableMessages).

Source

pub fn get_tools(&self) -> Vec<ToolDefinition>

Get all tools available to the agent

Source

pub fn set_system_prompt(&self, prompt: &str)

Set system prompt for the agent (interior mutability).

Source

pub fn set_cwd(&self, cwd: &str)

Set the working directory for the agent (interior mutability).

Source

pub fn set_thinking(&self, thinking: Option<ThinkingConfig>)

Set thinking configuration for the agent (interior mutability).

Source

pub fn set_model(&self, model: &str)

Set the model name at runtime (interior mutability).

Changes the model for subsequent query() calls, matching TypeScript’s QueryEngine.setModel().

Source

pub async fn query(&self, prompt: &str) -> Result<QueryResult, AgentError>

Main query method - handles the full agent loop including tool use, streaming responses, and multi-turn interaction with the LLM.

Reuses a persisted QueryEngine across calls so that conversation history, usage tracking, and tool state accumulate naturally (matches TypeScript pattern).

Takes &self (interior mutability) — the agent can be shared across tasks.

Source

pub fn reset(&self)

Reset the agent’s conversation history, keeping configuration intact.

Clears all messages, usage tracking, and turn count. This starts a fresh conversation while preserving model, API key, tools, and other settings.

Source

pub fn subscribe(&self) -> (EventSubscriber, CancelGuard)

Subscribe to agent events for the current and subsequent queries.

Returns an EventSubscriber (implements futures_util::Stream) and a CancelGuard. Events flow to the subscriber until the guard is dropped.

Takes &self (not &mut self) — you can subscribe from a shared reference, enabling decoupled TUI architectures where the subscriber is owned by a separate task from the agent.

§Example
let (mut sub, _guard) = agent.subscribe();
tokio::pin!(sub);

// Run query asynchronously
tokio::spawn(async move {
    agent.query("hello").await;
});

// Consume events
while let Some(ev) = sub.next().await {
    // render in TUI
}
Source

pub fn interrupt(&self)

Interrupt the agent loop. This aborts the current query() call, cancelling any in-flight API requests and tool execution.

§Example
let agent = Agent::new("claude-sonnet-4-6");

tokio::spawn(async move {
    agent.query("Do a lot of work").await.unwrap();
});

tokio::time::sleep(Duration::from_secs(5)).await;
agent.interrupt(); // Cancel the running prompt
Source

pub async fn recap(&self) -> AwaySummaryResult

Generate a short session recap summarizing the conversation so far.

Produces a 1-3 sentence summary suitable for a “while you were away” card or CLI status display. Uses the small/fast model (Haiku) with the last 30 messages and optional session memory context.

Returns AwaySummaryResult which indicates whether the LLM produced a summary, was aborted, or returned empty (no conversation history).

§Example
let agent = Agent::new("claude-sonnet-4-6")
    .api_key("sk-ant-...");
agent.query("build a REST API").await.ok();
// ... user steps away ...
let recap = agent.recap().await;
if let Some(summary) = recap.summary {
    println!("※ {}", summary);
}

Trait Implementations§

Source§

impl Clone for Agent

Source§

fn clone(&self) -> Agent

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

§

impl Freeze for Agent

§

impl !RefUnwindSafe for Agent

§

impl Send for Agent

§

impl Sync for Agent

§

impl Unpin for Agent

§

impl UnsafeUnpin for Agent

§

impl !UnwindSafe for Agent

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
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> 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> TaskStateTrait for T
where T: Clone + 'static,

Source§

fn as_any(&self) -> &(dyn Any + 'static)

Source§

fn clone_box(&self) -> Box<dyn TaskStateTrait>

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
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