Skip to main content

Agent

Struct Agent 

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

The agent orchestrates a conversation turn: takes a user message, calls the LLM provider, streams events, executes tool calls when requested, and feeds results back until a final text response is produced.

§Security Pipeline

When a permission engine is configured, every tool call is evaluated before execution. Denied calls return an error result without invoking the tool. The Ask decision defaults to Deny at the agent level.

When a sandbox is configured, bash tool calls are executed within the sandbox environment. If the sandbox is unavailable, the configured SandboxFallbackPolicy decides whether the invocation is denied or may continue through an explicitly approved unsandboxed path.

§Example

use talos_agent::Agent;
use talos_core::tool::ToolRegistry;
use std::sync::Arc;
let provider: Arc<dyn LanguageModel> = Arc::new(MyModel);
let tools = ToolRegistry::new();
let agent = Agent::new(provider, tools);
let response = agent.run("Hello!".into()).await.unwrap();

Implementations§

Source§

impl Agent

Source

pub fn new(provider: Arc<dyn LanguageModel>, tools: ToolRegistry) -> Self

👎Deprecated:

Agent::new() has NO permission engine and NO sandbox; use Agent::with_security(). See docs/decisions/007-process-hardening-unsafe.md and ARCH review.

Creates a new agent with the given language model provider and tool registry.

§Security

This constructor is unsafe-by-policy: no permission engine and no sandbox are configured. Every tool call is executed directly without any security gating. It exists for unit tests only; production run paths must use Agent::with_security to attach a permission engine and a sandbox provider.

See docs/decisions/007-process-hardening-unsafe.md and the ARCH remediation review (R0 #ARCH-S2) for context.

Source

pub fn with_security( provider: Arc<dyn LanguageModel>, tools: ToolRegistry, permission_engine: Option<Arc<PermissionEngine>>, sandbox: Option<Box<dyn SandboxProvider>>, workspace_root: PathBuf, ) -> Self

Creates a new agent with security controls enabled.

§Arguments
  • provider — The language model provider.
  • tools — Registry of tools available to the agent.
  • permission_engine — Optional permission engine for gating tool calls. When Some, every tool call is evaluated before execution.
  • sandbox — Optional sandbox provider for bash tool execution. When Some, bash commands run within the sandbox environment.
  • workspace_root — The workspace root directory, used for sandbox configuration and path resolution.
Source

pub fn with_security_and_sandbox_fallback( provider: Arc<dyn LanguageModel>, tools: ToolRegistry, permission_engine: Option<Arc<PermissionEngine>>, sandbox: Option<Box<dyn SandboxProvider>>, workspace_root: PathBuf, sandbox_fallback_policy: SandboxFallbackPolicy, sandbox_fallback_handler: Option<Arc<dyn SandboxFallbackHandler>>, ) -> Self

Creates an agent with an explicit sandbox fallback policy.

Source

pub fn with_security_and_hooks( provider: Arc<dyn LanguageModel>, tools: ToolRegistry, permission_engine: Option<Arc<PermissionEngine>>, sandbox: Option<Box<dyn SandboxProvider>>, workspace_root: PathBuf, hook_registry: Arc<HookRegistry>, ) -> Self

Creates a new agent with security controls and a shared hook registry.

Source

pub fn with_security_and_hooks_and_sandbox_fallback( provider: Arc<dyn LanguageModel>, tools: ToolRegistry, permission_engine: Option<Arc<PermissionEngine>>, sandbox: Option<Box<dyn SandboxProvider>>, workspace_root: PathBuf, hook_registry: Arc<HookRegistry>, sandbox_fallback_policy: SandboxFallbackPolicy, sandbox_fallback_handler: Option<Arc<dyn SandboxFallbackHandler>>, ) -> Self

Creates an agent with security controls, hooks, and sandbox fallback.

Source

pub fn with_reasoning_identity( self, provider_key: Option<String>, model_id: Option<String>, replay: bool, ) -> Self

Configures reasoning origin identity and replay behavior (ADR-034).

Source

pub fn set_request_budget_spec(&mut self, spec: RequestBudgetSpec)

Applies the exact Provider output reserve and conservative input policy.

Source

pub fn request_budget_spec(&self) -> RequestBudgetSpec

Source

pub fn set_memory_provider( &mut self, provider: Arc<dyn Fn(&str) -> Option<String> + Send + Sync>, )

Sets a memory provider callback for injecting memory into the system prompt.

The callback receives the user’s query and returns an optional formatted memory section string. When None is returned, no memory is injected.

Source

pub fn set_todo_section_provider( &mut self, provider: Arc<dyn Fn() -> Option<String> + Send + Sync>, )

Sets a callback for injecting bounded active session todos into the dynamic prompt suffix.

The callback returns already-formatted advisory text. It is evaluated once per provider request and does not invalidate the stable prompt prefix cache.

Source

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

Enables or disables bash output compression for model context.

When enabled, bash tool output exceeding 30 lines is compressed to the last 30 lines plus a truncation marker before entering model context. The raw output is preserved on the UI event/export surface.

Default: disabled (false).

Source

pub fn with_image_input_supported(self, supported: bool) -> Self

Enables or disables the read_image tool presentation based on the active model’s image input capability (ADR-051 / I154).

When true, read_image is included in the tool definitions sent to the provider. When false (default), the tool is registered but not presented — model calls to it are rejected by the presentation policy.

Source

pub fn set_image_input_supported(&mut self, supported: bool)

Sets image input capability on an existing agent (ADR-051 / I154). Rebuilds presented_tool_names and tool_definitions to reflect the new capability state.

Source

pub fn set_tools(&mut self, tools: Vec<ToolDescription>)

Sets the tool descriptions for the system prompt builder.

Tools are sorted alphabetically by name in the assembled prompt to ensure stable ordering across turns.

Source

pub fn set_tool_presentation_policy(&mut self, policy: ToolPresentationPolicy)

Sets which registered tool families are presented to the model.

The executable ToolRegistry is unchanged. Calls to registered tools that were not presented return a recoverable tool error instead of executing silently.

Source

pub fn set_tool_protocol(&mut self, protocol: ToolProtocol)

Sets the provider tool-call protocol.

Source

pub fn set_skill_index(&mut self, skills: Vec<SkillIndex>)

Sets the skill index for the system prompt builder.

Only Level 0 metadata (name, description, triggers) is included.

Source

pub fn set_activated_skill_context( &mut self, context: Option<ActivatedSkillContext>, )

Sets explicitly activated Level 1/2 Skill content for the system prompt.

The caller must load, bound, and validate this content before passing it here. Changing activated Skill content invalidates the stable prefix.

Source

pub fn set_context_files(&mut self, files: Vec<ContextFile>)

Sets the context files for the system prompt builder.

Typically loaded from AGENTS.md files via crate::context::ContextLoader.

Source

pub fn set_user_preferences(&mut self, prefs: String)

Sets user-specific instructions for the system prompt builder.

Source

pub fn set_custom_prompt(&mut self, prompt: String)

Sets a custom prompt that replaces the default identity.

Source

pub fn set_append_prompt(&mut self, prompt: String)

Sets an append prompt that is added at the end of the system prompt.

Source

pub fn clear_append_prompt(&mut self)

Clears the append prompt, removing any previously set value.

Source

pub fn set_append_prompt_opt(&mut self, prompt: Option<String>)

Sets the append prompt to an optional value.

Use None to clear the append prompt, or Some(prompt) to set it.

Source

pub fn build_system_prompt(&self) -> String

Assembles and returns the full system prompt from all configured components.

Components are assembled in the optimal order for caching: identity, tools, skill index, context files, user preferences, and append prompt (if provided).

Source

pub fn cancellation_token(&self) -> CancellationToken

Returns a CancellationToken that can be used to cancel the current turn. The caller is responsible for storing and triggering this token.

Note: The token itself does not interrupt the provider stream; it is provided for the caller to coordinate cancellation at a higher level.

Source§

impl Agent

Source

pub fn provider(&self) -> &dyn LanguageModel

Source

pub async fn run(&self, user_message: String) -> AgentResult<String>

Runs a single turn with the given user message and returns the complete assistant response.

If the model emits tool calls during the turn, they are executed and results are fed back until the model produces a final text response. AgentError::TurnBudgetExceeded if the tool call budget is exceeded, or AgentError::DoomLoopDetected if a doom loop is detected.

Source

pub async fn run_streaming( &self, user_message: String, history: Vec<Message>, event_tx: UnboundedSender<AgentEvent>, ) -> AgentResult<(String, Vec<Message>)>

Runs a single turn with streaming events forwarded to the given unbounded mpsc channel.

This method behaves like Agent::run but also sends every AgentEvent to event_tx, allowing external consumers to receive real-time updates (e.g., for UI streaming).

§Arguments
  • user_message — The current user message for this turn.
  • history — Prior conversation messages to include before the user message.
  • event_tx — Channel for streaming agent events.
§Errors

Returns the same errors as Agent::run.

Source

pub async fn preview_request( &self, user_message: String, history: Vec<Message>, ) -> AgentResult<Option<String>>

Builds a provider request preview without calling the provider.

This is the explicit diagnostic API used by product layers that expose request-inspection commands. The normal turn loop treats all user messages literally and does not parse diagnostic magic strings.

Auto Trait Implementations§

§

impl !Freeze for Agent

§

impl !RefUnwindSafe for Agent

§

impl !UnwindSafe for Agent

§

impl Send for Agent

§

impl Sync for Agent

§

impl Unpin for Agent

§

impl UnsafeUnpin 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> 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> 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<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