Skip to main content

BasicAgent

Struct BasicAgent 

Source
pub struct BasicAgent {
Show 13 fields pub system_prompt: String, pub model_config: ModelConfig, pub provider_override: Option<Arc<dyn StreamProvider>>, pub thinking_level: ThinkingLevel, pub max_tokens: Option<u32>, pub temperature: Option<f32>, pub context_config: Option<ContextConfig>, pub execution_limits: Option<ExecutionLimits>, pub cache_config: CacheConfig, pub tool_execution: ToolExecutionStrategy, pub tool_timeout: Option<Duration>, pub response_format: ResponseFormat, pub retry_config: RetryConfig, /* private fields */
}
Expand description

Reference implementation of the Agent trait.

Custom agents should implement the Agent trait directly. New generic agent methods should be defined on the Agent trait first, then implemented here — never add public methods to BasicAgent without the corresponding trait method.

Configuration is done via the builder pattern before any prompting. The runtime interface (prompting, state access, control) is provided via the Agent trait.

Fields§

§system_prompt: String§model_config: ModelConfig§provider_override: Option<Arc<dyn StreamProvider>>

Optional provider override. When set, bypasses ProviderRegistry dispatch. Used primarily in tests to inject a MockProvider.

§thinking_level: ThinkingLevel§max_tokens: Option<u32>§temperature: Option<f32>§context_config: Option<ContextConfig>§execution_limits: Option<ExecutionLimits>§cache_config: CacheConfig§tool_execution: ToolExecutionStrategy§tool_timeout: Option<Duration>§response_format: ResponseFormat§retry_config: RetryConfig

Implementations§

Source§

impl BasicAgent

Source

pub fn new(model_config: ModelConfig) -> Self

Source

pub fn with_session(self, session: Session) -> Self

Set a session for block-based compaction.

Source

pub fn take_session(&mut self) -> Option<Session>

Take the session out of the agent, returning ownership.

Source

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

Source

pub fn with_thinking(self, level: ThinkingLevel) -> Self

Source

pub fn with_tools(self, tools: Vec<Arc<dyn AgentTool>>) -> Self

Source

pub fn tools(&self) -> &[Arc<dyn AgentTool>]

Read-only view of the currently registered tools. Useful for tests that assert the LLM-facing tool registry (e.g. the Composition I opt-in guarantee — revert_to_state must NOT appear without an explicit with_revert_tool() call).

Source

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

Source

pub fn with_provider_override(self, provider: Arc<dyn StreamProvider>) -> Self

Override the provider used by the agent loop, bypassing ProviderRegistry dispatch. Primarily used in tests to inject a MockProvider.

Source

pub fn with_max_tokens(self, max: u32) -> Self

Source

pub fn with_context_config(self, config: ContextConfig) -> Self

Source

pub fn with_cache_config(self, config: CacheConfig) -> Self

Source

pub fn with_tool_execution(self, strategy: ToolExecutionStrategy) -> Self

Source

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

Set the per-tool execution timeout. See AgentLoopConfig::tool_timeout.

Source

pub fn with_response_format(self, format: ResponseFormat) -> Self

Set the desired LLM output shape. See crate::provider::ResponseFormat.

Source

pub fn with_retry_config(self, config: RetryConfig) -> Self

Source

pub fn with_skills(self, skills: SkillSet) -> Self

Load skills and append their index to the system prompt.

The skills index is appended as XML per the AgentSkills standard. The agent can then read individual SKILL.md files using the read_file tool when it decides a skill is relevant.

Source

pub fn with_execution_limits(self, limits: ExecutionLimits) -> Self

Source

pub fn with_messages(self, msgs: Vec<AgentMessage>) -> Self

Source

pub fn on_before_turn( self, f: impl Fn(&[AgentMessage], usize) -> bool + Send + Sync + 'static, ) -> Self

Source

pub fn on_after_turn( self, f: impl Fn(&[AgentMessage], &Usage) + Send + Sync + 'static, ) -> Self

Source

pub fn on_error(self, f: impl Fn(&str) + Send + Sync + 'static) -> Self

Source

pub fn with_input_filter(self, filter: impl InputFilter + 'static) -> Self

Add an input filter. Filters run in order on user messages before the LLM call.

Source

pub fn with_compaction_strategy( self, strategy: impl CompactionStrategy + 'static, ) -> Self

Set a custom in-memory compaction strategy on the context config. When set, replaces DefaultCompaction during context compaction for sessionless runs. (G5: stored on CompactionConfig, not BasicAgent.)

Source

pub fn with_profile(self, profile: AgentProfile) -> Self

Set the agent profile blueprint. Also copies profile fields into this agent’s public fields for backward compatibility (profile values act as defaults; existing field values take precedence if already set).

Source

pub fn with_temperature(self, temp: f32) -> Self

Set the temperature for LLM calls.

Source

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

Set the config identity, used as the middle segment of loop_id.

Source

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

Set the agent workspace directory. File paths in system prompt blocks resolve relative to this directory.

Source

pub fn on_before_loop( self, f: impl Fn(&[AgentMessage], usize) -> bool + Send + Sync + 'static, ) -> Self

Set the before-loop hook. Return false to abort the loop.

Source

pub fn on_after_loop( self, f: impl Fn(&[AgentMessage], &Usage) + Send + Sync + 'static, ) -> Self

Set the after-loop hook.

Source

pub fn on_before_tool_execution( self, f: impl Fn(&str, &str, &Value) -> bool + Send + Sync + 'static, ) -> Self

Set the before-tool-execution hook. Return false to skip the tool call.

Source

pub fn on_after_tool_execution( self, f: impl Fn(&str, &str, bool) + Send + Sync + 'static, ) -> Self

Set the after-tool-execution hook.

Source

pub fn on_before_tool_execution_update( self, f: impl Fn(&str, &str, &str) -> bool + Send + Sync + 'static, ) -> Self

Set the before-tool-execution-update hook. Return false to suppress the event.

Source

pub fn on_after_tool_execution_update( self, f: impl Fn(&str, &str, &str) + Send + Sync + 'static, ) -> Self

Set the after-tool-execution-update hook.

Source

pub fn with_prun_tool(self) -> Self

Enable the prun tool (both prun and prun_with_memo variants). Adds both tool variants to the tool set and wires up the shared pending queue.

Source

pub fn with_revert_tool(self) -> Self

Enable the revert_to_state tool (Composition I braking layer).

Registers a RevertTool on the agent and wires the shared revert_pending queue into the loop config so apply_revert runs between turns. The opt-in guarantee — there is no other registration path — is the load-bearing safety invariant for downstream consumers that have not yet adopted Composition I.

Source

pub fn with_convert_to_llm( self, f: impl Fn(&[AgentMessage]) -> Vec<Message> + Send + Sync + 'static, ) -> Self

Set a custom convert-to-LLM function.

Source

pub fn with_transform_context( self, f: impl Fn(Vec<AgentMessage>) -> Vec<AgentMessage> + Send + Sync + 'static, ) -> Self

Set a custom transform-context function.

Source

pub fn with_block_compaction_strategy( self, strategy: impl BlockCompactionStrategy + 'static, ) -> Self

Set a custom block compaction strategy for Session-aware compaction. (G5: stored on CompactionConfig, not BasicAgent.)

Source

pub fn on_before_compaction_start( self, f: impl Fn(usize, usize) -> bool + Send + Sync + 'static, ) -> Self

Set the before-compaction-start hook (G1). Return false to skip compaction.

Source

pub fn on_after_compaction_end( self, f: impl Fn(usize, usize, usize, usize) + Send + Sync + 'static, ) -> Self

Set the after-compaction-end hook (G1).

Source

pub fn with_context_translation( self, strategy: Arc<dyn ContextTranslationStrategy>, ) -> Self

Set the context translation strategy (G8) for cross-provider compatibility.

Source

pub fn with_sub_agent(self, sub: SubAgentTool) -> Self

Add a sub-agent tool. The sub-agent runs its own agent_loop() when invoked.

Source

pub fn without_context_management(self) -> Self

Disable automatic context compaction

Source

pub async fn with_mcp_server_stdio( self, command: &str, args: &[&str], env: Option<HashMap<String, String>>, ) -> Result<Self, McpError>

Connect to an MCP server via stdio and add its tools to the agent.

Source

pub async fn with_mcp_server_http(self, url: &str) -> Result<Self, McpError>

Connect to an MCP server via HTTP and add its tools to the agent.

Source

pub async fn prompt( &mut self, text: impl Into<String>, ) -> UnboundedReceiver<AgentEvent>

Send a text prompt. Returns a stream of AgentEvents.

Accepts impl Into<String> (e.g. &str). The trait’s Agent::prompt default requires an owned String; use this inherent method to pass &str without .to_string().

Source

pub async fn prompt_with_sender( &mut self, text: impl Into<String>, tx: UnboundedSender<AgentEvent>, )

Send a text prompt, streaming events to a caller-provided sender.

Accepts impl Into<String> (e.g. &str).

Source

pub fn compact_context_with_sender(&mut self, tx: &UnboundedSender<AgentEvent>)

Run block-based compaction on the agent’s session and emit the full event lifecycle.

Emits: AgentStart(Compaction)CompactionStartedCompactionEndedAgentEnd.

Requires self.session to be Some and self.context_config to be Some. Panics if either is missing. No-op if self.session or self.context_config is None.

Source

pub fn compact_context(&mut self) -> usize

Fire-and-forget compaction. Returns the number of loops that received new CompactionBlocks.

Requires self.session to be Some and self.context_config to be Some. Returns 0 if self.session or self.context_config is None.

Source

pub fn build_config(&self) -> Result<AgentLoopConfig, AgentBuildError>

Source

pub fn new_session(&mut self) -> String

Immediately rotate to a new session_id.

All subsequent loops will belong to the new session. Loop counters are reset so the new session’s loop ids start from .1.

Returns the newly assigned session_id.

Source

pub fn check_and_rotate(&mut self, threshold: Duration) -> Option<String>

Rotate to a new session if the agent has been idle for longer than threshold.

Idleness is measured from the last prompt_messages_with_sender call. If no prompt has ever been issued, returns None (no rotation needed — the session has never been used).

Returns Some(new_session_id) if rotation happened, None otherwise.

Trait Implementations§

Source§

impl Agent for BasicAgent

Source§

fn prompt_messages_with_sender<'life0, 'async_trait>( &'life0 mut self, messages: Vec<AgentMessage>, tx: UnboundedSender<AgentEvent>, ) -> Pin<Box<dyn Future<Output = ()> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Send messages as a prompt, streaming events to a caller-provided sender.

Source§

fn continue_loop_with_sender<'life0, 'async_trait>( &'life0 mut self, tx: UnboundedSender<AgentEvent>, kind: ContinuationKind, ) -> Pin<Box<dyn Future<Output = ()> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Continue from current context, streaming events to a caller-provided sender.

kind describes how this continuation relates to prior loops:

  • Default — unspecified continuation (preserves current semantics; use when the Rerun/Branch distinction is not relevant to the caller)
  • Rerun { tag } — retry from the same context state (auto-generates a UTC timestamp tag)
  • Branch { tag } — explore a different path from the same starting point (same tag)
Source§

fn messages(&self) -> &[AgentMessage]

Full message history.
Source§

fn is_streaming(&self) -> bool

Whether the agent is currently running a loop.
Source§

fn agent_id(&self) -> &str

Stable UUID assigned at construction; included in every AgentStart event.
Source§

fn session_id(&self) -> &str

Stable UUID assigned at construction; groups all loops from this instance.
Source§

fn last_loop_id(&self) -> Option<&str>

The loop_id of the most recently started loop; None before first run. Read more
Source§

fn clear_messages(&mut self)

Clear all messages from history.
Source§

fn append_message(&mut self, msg: AgentMessage)

Append a single message to history.
Source§

fn replace_messages(&mut self, msgs: Vec<AgentMessage>)

Replace the entire message history.
Source§

fn save_messages(&self) -> Result<String, Error>

Serialize message history to JSON.
Source§

fn restore_messages(&mut self, json: &str) -> Result<(), Error>

Restore message history from JSON.
Source§

fn set_tools(&mut self, tools: Vec<Arc<dyn AgentTool>>)

Replace the tool set.
Source§

fn abort(&self)

Cancel the current run via CancellationToken.
Source§

fn reset(&mut self)

Clear all state (messages, queues, streaming flag).
Source§

fn steer(&self, msg: AgentMessage)

Queue a steering message — interrupts the agent mid-tool-execution. Read more
Source§

fn follow_up(&self, msg: AgentMessage)

Queue a follow-up message — processed after the current agent turn completes. Read more
Source§

fn clear_steering_queue(&self)

Clear all pending steering messages. Default: no-op.
Source§

fn clear_follow_up_queue(&self)

Clear all pending follow-up messages. Default: no-op.
Source§

fn set_steering_mode(&mut self, mode: QueueMode)

Set how steering messages are delivered. Default: no-op.
Source§

fn set_follow_up_mode(&mut self, mode: QueueMode)

Set how follow-up messages are delivered. Default: no-op.
Source§

fn profile(&self) -> Option<&AgentProfile>

The agent’s profile blueprint. Default: None.
Source§

fn system_prompt(&self) -> &str

The agent’s system prompt. Default: empty string.
Source§

fn model_config(&self) -> Option<&ModelConfig>

The agent’s model configuration. Default: None.
Source§

fn thinking_level(&self) -> ThinkingLevel

The agent’s thinking level. Default: ThinkingLevel::Off.
Source§

fn temperature(&self) -> Option<f32>

The agent’s temperature setting. Default: None.
Source§

fn max_tokens(&self) -> Option<u32>

The agent’s max tokens setting. Default: None.
Source§

fn context_config(&self) -> Option<&ContextConfig>

The agent’s context config. Default: None.
Source§

fn execution_limits(&self) -> Option<&ExecutionLimits>

The agent’s execution limits. Default: None.
Source§

fn cache_config(&self) -> CacheConfig

The agent’s cache config. Default: CacheConfig::default().
Source§

fn tool_execution(&self) -> ToolExecutionStrategy

The agent’s tool execution strategy. Default: ToolExecutionStrategy::default().
Source§

fn tool_timeout(&self) -> Option<Duration>

The agent’s per-tool execution timeout. Default: None (no per-tool timeout). Read more
Source§

fn response_format(&self) -> ResponseFormat

The agent’s desired output shape. Default: ResponseFormat::Text (free-form text). Read more
Source§

fn retry_config(&self) -> RetryConfig

The agent’s retry config. Default: RetryConfig::default().
Source§

fn session(&self) -> Option<&Session>

The agent’s current session. Default: None.
Source§

fn workspace(&self) -> Option<&Path>

The agent’s workspace directory. File paths in system prompt blocks resolve relative to this. Default: None (uses current directory).
Source§

fn set_before_turn(&mut self, f: Option<BeforeTurnFn>)

Set the before-turn hook. Default: no-op.
Source§

fn set_after_turn(&mut self, f: Option<AfterTurnFn>)

Set the after-turn hook. Default: no-op.
Source§

fn set_before_loop(&mut self, f: Option<BeforeLoopFn>)

Set the before-loop hook. Default: no-op.
Source§

fn set_after_loop(&mut self, f: Option<AfterLoopFn>)

Set the after-loop hook. Default: no-op.
Source§

fn set_before_tool_execution(&mut self, f: Option<BeforeToolExecutionFn>)

Set the before-tool-execution hook. Default: no-op.
Source§

fn set_after_tool_execution(&mut self, f: Option<AfterToolExecutionFn>)

Set the after-tool-execution hook. Default: no-op.
Source§

fn set_before_tool_execution_update( &mut self, f: Option<BeforeToolExecutionUpdateFn>, )

Set the before-tool-execution-update hook. Default: no-op.
Source§

fn set_after_tool_execution_update( &mut self, f: Option<AfterToolExecutionUpdateFn>, )

Set the after-tool-execution-update hook. Default: no-op.
Source§

fn set_convert_to_llm(&mut self, f: Option<ConvertToLlmFn>)

Set the convert-to-LLM function. Default: no-op.
Source§

fn set_transform_context(&mut self, f: Option<TransformContextFn>)

Set the transform-context function. Default: no-op.
Source§

fn set_block_compaction_strategy( &mut self, s: Option<Arc<dyn BlockCompactionStrategy>>, )

Set the block compaction strategy. Default: no-op.
Source§

fn set_before_compaction_start(&mut self, f: Option<BeforeCompactionStartFn>)

Set the before-compaction-start hook (G1). Default: no-op.
Source§

fn set_after_compaction_end(&mut self, f: Option<AfterCompactionEndFn>)

Set the after-compaction-end hook (G1). Default: no-op.
Source§

fn set_context_translation( &mut self, s: Option<Arc<dyn ContextTranslationStrategy>>, )

Set the context translation strategy (G8). Default: no-op.
Source§

fn context_translation(&self) -> Option<Arc<dyn ContextTranslationStrategy>>

Get the context translation strategy (G8). Default: None.
Source§

fn prompt_with_sender<'life0, 'async_trait>( &'life0 mut self, text: String, tx: UnboundedSender<AgentEvent>, ) -> Pin<Box<dyn Future<Output = ()> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Send a text prompt, streaming events to a caller-provided sender. Read more
Source§

fn prompt<'life0, 'async_trait>( &'life0 mut self, text: String, ) -> Pin<Box<dyn Future<Output = UnboundedReceiver<AgentEvent>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Send a text prompt. Returns a stream of AgentEvents. Read more
Source§

fn prompt_messages<'life0, 'async_trait>( &'life0 mut self, messages: Vec<AgentMessage>, ) -> Pin<Box<dyn Future<Output = UnboundedReceiver<AgentEvent>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Send messages as a prompt. Returns a stream of AgentEvents. Read more
Source§

fn continue_loop<'life0, 'async_trait>( &'life0 mut self, ) -> Pin<Box<dyn Future<Output = UnboundedReceiver<AgentEvent>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Continue from current context. Returns a stream of AgentEvents. Read more
Source§

fn clear_all_queues(&self)

Clear both steering and follow-up queues.
Source§

fn set_prun_enabled(&mut self, _enabled: bool)

Enable or disable the prun tool. Default: no-op.
Source§

fn build_config(&self) -> Result<AgentLoopConfig, AgentBuildError>

Assemble an AgentLoopConfig from this agent’s current settings. 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> 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, 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<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