Skip to main content

AgentBuilder

Struct AgentBuilder 

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

Builder for configuring and running agent sessions.

Use the builder pattern to set options, then call a terminal method (exec, run, resume, continue_last) to execute.

Implementations§

Source§

impl AgentBuilder

Source

pub fn new() -> Self

Create a new builder with default settings.

Source

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

Set the provider (e.g., “claude”, “codex”, “gemini”, “copilot”, “ollama”).

Calling this method pins the provider — it will NOT be downgraded to another provider in the tier list if its binary is missing or the startup probe fails. Omit this call (or set provider via the config file) to allow automatic downgrading.

Source

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

Set the model (e.g., “sonnet”, “opus”, “small”, “large”).

Source

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

Set a system prompt to configure agent behavior.

Source

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

Set the root directory for the agent to operate in.

Source

pub fn auto_approve(self, approve: bool) -> Self

Enable auto-approve mode (skip permission prompts).

Source

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

Add an additional directory for the agent to include.

Source

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

Attach a file to the prompt (text files ≤50 KB inlined, others referenced).

Source

pub fn env(self, key: &str, value: &str) -> Self

Add an environment variable for the agent subprocess.

Source

pub fn worktree(self, name: Option<&str>) -> Self

Enable worktree mode with an optional name.

Source

pub fn sandbox(self, name: Option<&str>) -> Self

Enable sandbox mode with an optional name.

Source

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

Set the Ollama parameter size (e.g., “2b”, “9b”, “35b”).

Source

pub fn json(self) -> Self

Request JSON output from the agent.

Source

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

Set a JSON schema for structured output validation. Implies json().

Source

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

Set a specific session ID (UUID).

Source

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

Set the output format (e.g., “text”, “json”, “json-pretty”, “stream-json”).

Source

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

Set the input format (Claude only, e.g., “text”, “stream-json”).

No-op for Codex, Gemini, Copilot, and Ollama. See docs/providers.md for the full per-provider support matrix.

Source

pub fn replay_user_messages(self, replay: bool) -> Self

Re-emit user messages from stdin on stdout (Claude only).

Only works with --input-format stream-json and --output-format stream-json. exec_streaming auto-enables this flag, so most callers never need to set it manually. No-op for non-Claude providers.

Source

pub fn include_partial_messages(self, include: bool) -> Self

Include partial message chunks in streaming output (Claude only).

Only works with --output-format stream-json. Defaults to false.

When false (the default), streaming surfaces one assistant_message event per complete assistant turn. When true, the agent instead emits a stream of token-level partial assistant_message chunks as the model generates them — use this for responsive, token-by-token UIs over exec_streaming. No-op for non-Claude providers.

Source

pub fn verbose(self, v: bool) -> Self

Enable verbose output.

Source

pub fn quiet(self, q: bool) -> Self

Enable quiet mode (suppress all non-essential output).

Source

pub fn show_usage(self, show: bool) -> Self

Show token usage statistics.

Source

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

Set the maximum number of agentic turns.

Source

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

Set a timeout for exec. If the agent doesn’t complete within this duration, it will be killed and an error returned.

Source

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

Set MCP server config for this invocation (Claude only).

Accepts either a JSON string ({"mcpServers": {...}}) or a path to a JSON file. No-op for Codex, Gemini, Copilot, and Ollama — those providers manage MCP configuration through their own CLIs or do not support it. See docs/providers.md for the full per-provider support matrix.

Source

pub fn on_progress(self, handler: Box<dyn ProgressHandler>) -> Self

Set a custom progress handler for status reporting.

Source

pub async fn exec(self, prompt: &str) -> Result<AgentOutput>

Run the agent non-interactively and return structured output.

This is the primary entry point for programmatic use.

Source

pub async fn exec_streaming(self, prompt: &str) -> Result<StreamingSession>

Run the agent with streaming input and output (Claude only).

Returns a StreamingSession that allows sending NDJSON messages to the agent’s stdin and reading events from stdout. Automatically configures --input-format stream-json, --output-format stream-json, and --replay-user-messages.

§Default emission granularity

By default assistant_message events are emitted once per complete assistant turn — you get one event when the model finishes speaking, not a stream of token chunks. For responsive, token-level UIs call include_partial_messages(true) on the builder before exec_streaming; the session will then emit partial assistant_message chunks as the model generates them.

The default is kept false so existing callers that render whole-turn bubbles are not broken. See docs/providers.md for the full per-provider flag support matrix.

§Event lifecycle

The session emits a unified Event::Result at the end of every agent turn — not only at final session end. Use that event as the authoritative turn-boundary signal. After a Result, the session remains open and accepts another send_user_message for the next turn. Call close_input followed by wait to terminate the session cleanly.

Do not depend on replayed user_message events to detect turn boundaries; those only appear while --replay-user-messages is set.

§Examples
use zag_agent::builder::AgentBuilder;
use zag_agent::output::Event;

let mut session = AgentBuilder::new()
    .provider("claude")
    .exec_streaming("initial prompt")
    .await?;

// Drain the first turn until Result.
while let Some(event) = session.next_event().await? {
    println!("{:?}", event);
    if matches!(event, Event::Result { .. }) {
        break;
    }
}

// Follow-up turn.
session.send_user_message("do something else").await?;
while let Some(event) = session.next_event().await? {
    if matches!(event, Event::Result { .. }) {
        break;
    }
}

session.close_input();
session.wait().await?;
Source

pub async fn run(self, prompt: Option<&str>) -> Result<()>

Start an interactive agent session.

This takes over stdin/stdout for the duration of the session.

Source

pub async fn resume(self, session_id: &str) -> Result<()>

Resume a previous session by ID.

Source

pub async fn continue_last(self) -> Result<()>

Resume the most recent session.

Trait Implementations§

Source§

impl Default for AgentBuilder

Source§

fn default() -> Self

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> 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, 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