| title | Agent (bricks-agent) |
|---|---|
| description | Agent builder, agentic loop, streaming events, auto-compact, reasoning profiles, system prompt caching. |
import { Callout } from 'fumadocs-ui/components/callout'; import { Tabs, Tab } from 'fumadocs-ui/components/tabs'; import { TypeTable } from 'fumadocs-ui/components/type-table';
The high-level Agent API. Builder pattern for configuration, an agentic loop that handles tool dispatch and multi-turn conversations, a set of 39 event variants for observation, and automatic context management.
Most users interact with Bricks through this crate. The `bricks` facade re-exports `Agent`, `AgentBuilder`, `AgentOutput`, `AgentEvent`, and `AgentStream` directly.Every agent starts with a builder. The only required field is .provider(): everything else has sensible defaults. The provider is one model configured in ~/.bricks/providers.toml, selected as provider_id/model_id.
let agent = Agent::builder()
.provider(bricks::provider_from_config(None, "my-provider/my-model")?)
.tools(bricks::tools::coding())
.system_prompt("You are a coding assistant.")
.max_tokens(16384)
.permission_policy(AllowAll)
.build()?;<TypeTable type={{ '.provider(p)': { type: 'impl Provider', description: 'The LLM backend: a ConfiguredProvider from bricks::provider_from_config, or a custom implementation.', required: true, }, '.tool(t)': { type: 'impl Tool', description: 'Add a single tool. Can be called multiple times.', }, '.tools(vec)': { type: 'Vec<Box>', description: 'Add multiple tools at once. Use bricks::tools::coding() for the standard set.', }, '.system_prompt(s)': { type: 'impl Into', description: 'Static system prompt, placed before the dynamic boundary. Cached by providers that support prompt caching.', }, '.system_prompt_options(opts)': { type: 'SystemPromptOptions', description: 'The Bricks prompt, assembled for each request from the tools that request announces; its request context (environment, model, git, plan) follows the cache boundary. Wins over .system_prompt(s).', }, '.append_system_prompt(s)': { type: 'impl Into', description: 'Dynamic section appended after the cache boundary. Rebuilt each turn.', }, '.model(s)': { type: 'impl Into', description: 'A label for the model in use. The model is the one configured on the provider; this does not select it.', }, '.max_tokens(n)': { type: 'u32', description: 'Max output tokens per model call. Capped at the model's max_output_tokens.', default: '16384', }, '.temperature(t)': { type: 'f32', description: 'Sampling temperature. Not sent unless set.', default: 'not sent', }, '.reasoning_profile(id)': { type: 'impl Into', description: 'Reasoning profile of the model, as declared in providers.toml. An unknown id is an error; nothing is replaced silently.', default: "the model's default", }, '.working_dir(p)': { type: 'impl Into', description: 'Working directory for file tools and shell commands.', default: 'current dir', }, '.permission_policy(p)': { type: 'impl PermissionPolicy', description: 'The approver: answers the calls the session policy asks about (a callback, a stream, or a fixed answer). Alone, it gives the ASK profile.', default: 'none (EXECUTE)', }, '.permission_profile(p)': { type: 'SessionPolicy', description: 'The session policy: ASK, EXECUTE or CUSTOM, with its rules. See the Permissions section of the tools page.', default: 'EXECUTE, or ASK with an approver', }, '.memory(m)': { type: 'impl Memory', description: 'Session persistence backend. JsonlMemory, InMemory, or custom.', }, '.long_term_memory(m)': { type: 'Arc', description: 'Long-term memory. The notes index is added to the system prompt of each run (within the recall budget). The note store records no exchanges.', }, '.session_id(s)': { type: 'impl Into', description: 'Session identifier for memory load/save.', }, '.hook(h)': { type: 'impl Hook', description: 'Add lifecycle middleware. Can be called multiple times.', }, '.on_event(f)': { type: 'Fn(&AgentEvent)', description: 'Synchronous callback for every event. Simplest observation method.', }, '.enable_broadcast(cap)': { type: 'usize', description: 'Enable broadcast channel with given capacity. Call .subscribe() after build.', default: 'disabled', }, '.auto_compact(b)': { type: 'bool', description: 'Summarize old messages when the context reaches the threshold.', default: 'true', }, '.compact_threshold(f)': { type: 'f64', description: 'Trigger compaction at this fraction of the prompt budget (crates/bricks-agent/src/lib.rs:883). Overrides the context policy.', default: '0.85 (context policy)', }, '.tool_result_budget(n)': { type: 'usize', description: 'Tool results beyond this many characters are replaced by a placeholder, oldest first; it names the saved original when the original could be saved. Unset, the budget follows the model (crates/bricks-agent/src/runner.rs:170, applied at :1141).', default: 'the model's declared input limit, read as characters (about a quarter of its window); at least 50000', }, '.cancel_token(t)': { type: 'CancellationToken', description: 'External cancellation signal. Call .cancel() to abort the loop.', default: 'new token', }, '.mcp_server(cfg)': { type: 'McpServerConfig', description: 'Connect to an MCP server at the first run. Tools are offered as mcp____.', }, }} />
`.build()` returns `Result` and fails when the configuration is invalid.The simplest way to run an agent: it builds, executes, and returns in one call:
let output = Agent::builder()
.provider(bricks::provider_from_config(None, "my-provider/my-model")?)
.tools(bricks::tools::coding())
.run_with("Fix the failing tests")
.await?;
println!("{}", output.text());
println!("Turns: {}, Tool calls: {}", output.turns, output.tool_calls.len());run is async. Build once, run multiple times. The agent maintains conversation history across calls:
let agent = Agent::builder()
.provider(bricks::provider_from_config(None, "my-provider/my-model")?)
.tools(bricks::tools::coding())
.build()?;
// First turn
let output1 = agent.run("What files are in src/?").await?;
// Second turn: the agent remembers the first
let output2 = agent.run("Now fix the bug in main.rs").await?;run_stream takes the agent behind an Arc, so the run can outlive the caller's stack frame. It returns an AgentStream that yields events as they happen. AgentStream::cancel() is applied to the run. respond_permission() and inject_message() are accepted by AgentStream, but run_stream_input ignores their control messages (crates/bricks-agent/src/lib.rs:286-287), so they have no effect in this version.
use std::sync::Arc;
let agent = Arc::new(agent);
let mut stream = agent.run_stream("Deploy the application");
while let Some(event) = stream.next().await {
match event {
AgentEvent::TextDelta(t) => print!("{t}"),
AgentEvent::ThinkingDelta(t) => { /* thinking content */ }
AgentEvent::ToolStart { name, input, .. } => {
eprintln!("\n[Tool: {name}]");
}
AgentEvent::ToolEnd { name, duration, is_error, .. } => {
let status = if is_error { "FAIL" } else { "OK" };
eprintln!("[{name}: {status} in {} ms]", duration.as_millis());
}
AgentEvent::PermissionRequired(req) => {
// respond_permission() has no effect in this version (see note above)
eprintln!("Permission requested for {}", req.tool_name);
}
AgentEvent::Complete(output) => {
eprintln!("\nDone: {} turns", output.turns);
break;
}
AgentEvent::Error(msg) => {
eprintln!("Error: {msg}");
break;
}
_ => {}
}
}Returned by run(), run_with(), and AgentStream::collect().
use bricks_agent::{Termination, ToolCallRecord};
pub struct AgentOutput {
pub message: Message,
pub usage: Usage,
pub stop_reason: StopReason,
pub turns: u32,
pub tool_calls: Vec<ToolCallRecord>,
pub termination: Termination,
}<TypeTable
type={{
message: {
type: 'Message',
description: 'The final assistant message with all content blocks.',
required: true,
},
usage: {
type: 'Usage',
description: 'Cumulative usage of this agent, all runs so far, including a seed from with_cumulative_usage (crates/bricks-agent/src/runner.rs:1769).',
required: true,
},
stop_reason: {
type: 'StopReason',
description: "The provider's reason for its last response: EndTurn, MaxTokens, ToolUse, StopSequence, ContentFilter.",
required: true,
},
turns: {
type: 'u32',
description: 'Generation turns actually run (each tool-use cycle is one turn).',
required: true,
},
tool_calls: {
type: 'Vec',
description: 'Every tool call made, with name, id, input, result, duration, and error status.',
required: true,
},
termination: {
type: 'Termination',
description: 'How the run ended: Completed, OutputTruncated, NoProgress, ContentFiltered, EmptyResponse. A stored end of another kind (for example max_turns, written before 0.4.8) is read as Historical { kind }: an incomplete end, never a success. No run produces it. Use is_complete() for a final answer.',
required: true,
},
}}
/>
// Access the text response
let text = output.text(); // -> &str
// Inspect tool calls
for call in &output.tool_calls {
println!("{}: {} ms (error: {})", call.name, call.duration.as_millis(), call.is_error);
}39 variants covering every observable moment in the agentic loop. The most useful are listed below; the enum in bricks_agent::events is the reference.
| Variant | Fields | Emitted When |
|---|---|---|
TextDelta(String) |
text chunk | Model streams a text token |
ThinkingDelta(String) |
thinking chunk | Model streams a reasoning token |
| Variant | Fields | Emitted When |
|---|---|---|
ToolStart { name, id, input } |
tool name, call ID, JSON input | Tool dispatch begins |
ToolProgress { name, message } |
tool name, progress message | A running tool reports progress |
ToolEnd { name, id, result, is_error, duration, compression } |
tool name, call ID, result text, error flag, wall-clock time, compression stats | Tool execution completes |
ToolPermissionCheck { name, id, level } |
tool name, call ID, permission level | A tool call is checked against the policy |
| Variant | Fields | Emitted When |
|---|---|---|
TurnStart { turn } |
turn number | A model call begins |
TurnComplete { turn, stop_reason, usage } |
turn number, stop reason, token usage | One model call + tool cycle finishes |
ModelRequestStart { turn, message_count, token_estimate } |
turn, messages sent, estimated tokens | A request is about to be sent |
TokenWarning { pct_used, state } |
context % used, Normal/Warning/Critical |
Context window approaching limit |
CompactStart { reason, messages_before } |
compaction reason, message count | Context compaction begins |
CompactEnd { messages_after, tokens_freed } |
remaining messages, tokens reclaimed | Compaction finishes |
CompactionResult { reason, outcome } |
reason, CompactionOutcome |
The outcome is explicit: Compacted, InsufficientGain, Failed, Skipped |
SessionLoaded { session_id, message_count } |
session ID, number of messages | Session resumed from memory |
SessionSaved { session_id } |
session ID | Session stored |
| Variant | Fields | Emitted When |
|---|---|---|
PermissionRequired(PermissionRequest) |
tool name, input, description, level, category, id, policy_revision | The policy asked, and the stream approver answers (InteractivePolicy::via_stream) |
ApprovalRequested / ApprovalResolved |
approval and decision details | An approval is asked and answered (control contract) |
EditApplied { tool_call_id, tool, files } |
call ID, tool, changed files | A file change was written |
CostUpdate { turn_cost, cumulative_cost, input_tokens, output_tokens } |
costs and token counts | After each model call |
SubAgentSpawned { agent_id, prompt } |
sub-agent ID, task description | Sub-agent created |
SubAgentComplete { agent_id, result } |
sub-agent ID, AgentOutput |
Sub-agent finished |
SkillActivated / SkillNotActivated |
skill name, source, revision or reason | An Agent Skill was activated, refused, or withdrawn because it was removed, reinstalled or changed |
MemoryRecalled { items, tokens, omitted, budget } |
counts and token budget | The memory index was added to the run's prompt |
MemoryMaintenanceStarted / MemoryMaintenanceFinished(result) |
maintenance report | Deferred memory work started, or ended with its report |
SubAgent(SubAgentEvent) / Job(JobEvent) |
sub-agent or background job event | A sub-agent or background command changed state |
| Variant | Fields | Emitted When |
|---|---|---|
Status(String) |
status message | Informational update |
Error(String) |
error message | Unrecoverable error |
Complete(AgentOutput) |
final output | Agent loop finished |
Bidirectional control channel. Receive events and send commands back.
<TypeTable type={{ 'next()': { type: 'async fn -> Option', description: 'Receive the next event. Returns None when the stream ends.', }, 'respond_permission()': { type: 'fn(request_id: String, decision: PermissionDecision)', description: 'Answers a PermissionRequired event. PermissionDecision: Allow, Deny(reason), AllowOnce (this call only; no allow for the session).', }, 'cancel()': { type: 'fn()', description: 'Cancels the current run: the in-flight provider request and the wait for tool results are interrupted (crates/bricks-agent/src/runner.rs:968-970, 1469-1471).', }, 'inject_message()': { type: 'fn(message: String)', description: 'Sends an InjectMessage, but run_stream_input ignores it (crates/bricks-agent/src/lib.rs:286-287): no effect in this version.', }, 'collect()': { type: 'async fn -> Result', description: 'Consume all events and return the final output.', }, 'collect_text()': { type: 'async fn -> Result', description: 'Consume all events and return the final text.', }, }} />
Reasoning depth is not a fixed SDK enum. A model declares its own profiles in providers.toml, and an agent selects one by id. Bricks has no list of levels, and the id sent to the server is the profile's parameters, not its local name:
[[providers.models.reasoning.profiles]]
id = "approfondi"
label = "Approfondi"
parameters = { reasoning_effort = "high" }let agent = Agent::builder()
.provider(bricks::provider_from_config(None, "my-provider/my-model")?)
.reasoning_profile("approfondi") // must be a profile of this model
.build()?;
println!("{:?}", agent.reasoning_profile()); // the effective profile id, if any
agent.set_reasoning(None); // back to the model's declared defaultPassing an id the model does not declare is an error that lists the available ones. See bricks-provider for the protocol side.
When the conversation approaches the context window limit, the agent summarizes older messages to free space. This happens automatically, so the model continues working without interruption. Auto-compact is on by default.
Agent::builder()
.auto_compact(true) // default
.compact_threshold(0.85) // trigger at 85% of the context window
.tool_result_budget(50_000) // fixed: tool results beyond 50K chars are replaced by a placeholder (unset: follows the model)The compaction pipeline:
- Measure the active context, with its provenance (
measured,counted,mixedorestimated) - Above the threshold, ask the model for a budgeted summary with fixed headings: objective, constraints, decisions, files, actions, open problems, key facts
- Keep the user's messages verbatim
- Replace the old messages only if the summary gains enough space; otherwise the outcome is
InsufficientGain, and nothing is replaced - Keep the original history in memory (
raw_history(),compaction_snapshots()). When a session memory is configured, the raw history and each snapshot are also stored (<id>.raw,<id>.compaction-<n>), seecrates/bricks-agent/src/runner.rs:1958-1975
Events emitted: CompactStart, CompactEnd (with messages_after and tokens_freed), and CompactionResult with the explicit outcome.
The system prompt is split into two sections separated by SYSTEM_PROMPT_DYNAMIC_BOUNDARY (__SYSTEM_PROMPT_DYNAMIC_BOUNDARY__):
[Static section: cached by the provider]
__SYSTEM_PROMPT_DYNAMIC_BOUNDARY__
[Dynamic section: rebuilt each turn]
Agent::builder()
.system_prompt("You are a coding assistant. Always use Rust.") // static, cached
.append_system_prompt("Current time: 2024-01-01") // dynamic, per-turnWith the Bricks prompt (system_prompt_options), the part after the boundary holds the request's date, environment, model, git state and plan; it is built again for each request. See System Prompts.
Providers that support prompt caching cache everything before the boundary. Whether caching applies depends on the model's protocol and its compat settings (prompt_cache_markers for anthropic_messages). See docs/providers.md in the repository.