Expand description
An agent loop and tool harness you embed in a Rust program.
haest runs the loop every coding agent runs: send the conversation to a model, run the tools it asks for, send the results back, until the model answers without tools. Around that loop it brings the parts a real agent needs: providers for Anthropic, OpenAI and OpenRouter, the file, shell, search and web tools, a copy-on-write sandbox, MCP servers, subagents, mods, sessions, compaction and spending caps. Every part is a trait, so a host swaps any of them for its own.
haest reads nothing it wasn’t handed. No file, environment variable or flag
reaches a run unless the host passes it in: keys come from a KeySource,
the environment of a process the agent starts is a ChildEnv, and the
files the tools touch go through the Workspace you give it.
§Quickstart
[dependencies]
haest = "0.3"
tokio = { version = "1", features = ["rt-multi-thread", "macros"] }One turn with a real model and haest’s built-in tools, in the current directory:
use haest::providers::ProviderRegistry;
use haest::tools::{BuiltinOptions, builtin_tools};
use haest::workspace::RealWorkspace;
use haest::{Agent, AgentDeps, AgentOptions, BoxError, ChildEnv, LoopEvent, SharedDeps};
#[tokio::main]
async fn main() -> Result<(), BoxError> {
// The host decides where keys come from; here, this process's environment.
let keys = |name: &str| std::env::var(name).ok();
// The built-in providers; `.with_custom(..)` adds providers.json's.
let models = ProviderRegistry::new(keys);
// Bash runs with only the variables you pass on.
let pass = |k: &'static str| (k, std::env::var(k).unwrap_or_default());
let env = ChildEnv::new([pass("PATH"), pass("HOME")]);
// What the conversation runs on: models, a working directory, files and shell.
let shared = SharedDeps::new(models, std::env::current_dir()?, RealWorkspace::new(env));
// The agent's own: its tools and its system prompt.
let tools = builtin_tools(BuiltinOptions::default());
let deps = AgentDeps::new(shared, tools, "You are a careful engineer.");
let model = AgentOptions::new("openrouter:anthropic/claude-sonnet-5.5");
let mut agent = Agent::new(deps, model);
// Every event of the turn goes to the sink, in order.
// This one prints the answer as it streams.
let mut sink = |ev: LoopEvent| match ev {
LoopEvent::TextDelta { text } => print!("{text}"),
LoopEvent::ToolCallStart { name, .. } => println!("\n[{name}]"),
_ => {}
};
let end = agent.run("What does this project do?", &mut sink).await;
println!("\n{:?}", end.stop_reason);
Ok(())
}Run it with OPENROUTER_API_KEY set. anthropic: and openai: models take
ANTHROPIC_API_KEY and OPENAI_API_KEY; a providers.json adds any
OpenAI-compatible server (see providers).
§How a turn runs
agent.run(input, &mut sink)
1. the input joins the history LoopEvent::User
2. the model is called through the ModelResolver LoopEvent::ModelStart, TextDelta ...
3. its answer joins the history LoopEvent::Assistant
4. each tool it called runs, inside the Workspace LoopEvent::ToolResult
5. back to 2 with the results, until it answers without tools,
a cap stops it, or the host aborts LoopEvent::TurnEndAgent::run returns how the turn ended (TurnOutcome); Agent::history
is the history, ready for the next turn. Input that arrives during a turn
goes through AgentControl::steer, and AgentControl::abort stops it
cleanly.
§The plug points
AgentDeps and the SharedDeps inside it are everything the loop is
handed. Each part is a trait with haest’s own implementations beside it; a
host keeps those or brings its own. SharedDeps::new, AgentDeps::new
and every with_* setter take the part itself (a closure, a String, a host’s own type), or
an Arc of one the host already shares, so one object can fill several
slots. Each slot holds it in a cheap handle named after its trait
(ToolSourceRef, AgentHooksRef, …).
| Trait | What it is | haest’s own |
|---|---|---|
ModelResolver, Provider | turns a model spec (openrouter:z-ai/glm-5.3) into a model API | providers::ProviderRegistry |
http::HttpClient | how every model call and web request travels | http::ReqwestClient |
ToolSource, Tool | the tools the model may call | Tools, tools::builtin_tools, mcp, mods, code |
Workspace, Fs | the files and the shell every tool goes through | workspace::RealWorkspace, workspace::SandboxWorkspace, ShutWorkspace |
SystemPrompt | the system prompt, rebuilt for each model call | String, &'static str, closures |
AgentHooks | the host’s say in the loop: each message to save, compaction before a model call, media | NoHooks, runtime |
ToolServices | what tools hand the host while they run: inner-call rows, debug lines | NoServices, runtime |
ModelFacts | what the host knows of each model: the inputs it takes, its efforts | NoFacts, runtime |
TurnCapsSource | the caps on each turn, per model | TurnCaps (the same for every model), runtime |
Clock | the time a turn’s time cap reads | WallClock |
EventSink | where the turn’s events go | closures, Vec<LoopEvent>, a tokio channel |
KeySource | API keys and endpoints, asked for by name | closures, HashMap<String, String> |
Approvals are a mod’s (mods), not the loop’s.
§Write a tool
A tool is a name, a description and a JSON Schema the model sees, and an
async execute. Return ToolError::Input for a mistake the model can
correct; it goes back to the model as is.
use haest::prelude::*;
struct Shout;
#[async_trait]
impl Tool for Shout {
fn name(&self) -> &str {
"Shout"
}
fn description(&self) -> String {
"Returns the text in capitals.".into()
}
fn parameters(&self) -> Value {
json!({
"type": "object",
"properties": { "text": { "type": "string" } },
"required": ["text"]
})
}
fn kind(&self) -> &str {
"shout"
}
fn read_only(&self) -> bool {
true
}
async fn execute(
&self,
input: JsonMap,
_ctx: &ToolContext,
) -> Result<ToolOutput, ToolError> {
let text = req_str(&input, "text")?;
Ok(ToolOutput::text(text.to_uppercase()))
}
}Hand it to the agent with the others:
let tools = builtin_tools(opts).with(Shout);.
§Test your host
The testing feature brings core::testing: a model that answers from
a script and records every request, so a test drives whole turns with no
network and no keys. Its docs run a turn with a tool call.
[dev-dependencies]
haest = { version = "0.3", features = ["testing"] }§Features
core (the loop and the contracts) is always there: its key types at
the root (haest::Agent, haest::Tool) and in prelude, its modules
under core (haest::core::fs, haest::core::session). Every other
part is a feature, so a host links only what it uses, and each one has a
module of its name at the root: haest::workspace is always the workspace
crate.
| Feature | Brings | Default |
|---|---|---|
http | http: the HTTP seam the model calls and GenerateImage send through (WebFetch and MCP servers keep clients of their own); on with providers and tools | yes |
reqwest | http::ReqwestClient, the default client over reqwest and rustls; off with providers alone, the model calls send only through the client a host hands in (tools and mcp turn it on: WebFetch and rmcp run on reqwest) | yes |
providers | providers: Anthropic Messages, OpenAI Chat Completions and Responses, OpenRouter, any OpenAI-compatible server | yes |
workspace | workspace: the real disk and bash, or a sandbox over a copy-on-write overlay | yes |
tools | tools: Read, Write, Edit, Glob, Grep, Bash, WebFetch, tasks, subagents and more | yes |
mcp | mcp: MCP servers (stdio, streamable HTTP) and their tools | yes |
rmcp | mcp::rmcp and mcp::McpHub::connect_transport: an MCP server over a transport the host opened (rmcp’s types in haest’s API); turns on mcp | no |
code | code: the Code tool and the sandbox js command, in embedded QuickJS | yes |
mods | mods: change how haest behaves without forking it; approvals, plan mode | yes |
settings | settings: every setting as a plain value a host writes out in Rust | yes |
config | config: the loader for haest’s TOML files, HAEST_* variables and flags; with mcp too, it reads a trusted project’s .mcp.json | no |
runtime | runtime: a whole conversation built from settings, behind a host’s UI | no |
wire | wire: the envelope around a conversation’s events, the requests a peer sends, a replay ring with gaps, an NDJSON codec | no |
session | session: a conversation another program watches and drives while it runs (input mid-turn, catch-up, approvals over it); with runtime, the whole conversation is one | no |
transport | transport: the session served to another program, one connection’s rules over any line source and sink | no |
transport-stdio | transport::Stdio: a parent process drives the conversation over this one’s stdin and stdout | no |
transport-broker | transport::Broker: the conversation dials out to a broker over a WebSocket (pulls a WebSocket client on rustls) | no |
transport-unix | transport::UnixSocket: programs on this machine watch (or drive) the conversation over a Unix socket; transport::running_sessions and transport::connect_session find and reach one | no |
prompt | prompt: the system prompt as the host’s Jinja template, set up like Hugging Face chat templates; with runtime, runtime::RuntimeInputs::with_prompt_template renders it before every model call | no |
testing | core::testing: a scripted model and other fakes for tests | no |
# a host with its own HTTP client, files and tools:
haest = { version = "0.3", default-features = false, features = [
"providers", "workspace", "tools", "settings",
] }
# the whole conversation from haest's own files, variables and flags (the CLI):
haest = { version = "0.3", features = ["runtime", "config"] }§Going further
runtimebuilds what thehaestCLI runs: settings in, a conversation with sessions, subagents, MCP, mods and compaction out. Start there for a full agent behind your own UI.settingslists every setting; the settings reference explains each one.- The notebook example
wires every plug point the way a real host does, against fakes;
cargo run -p haest --example notebookruns it. core::threshold: a meter crossing a mark fires an action (remind the model, warn the human, wind down, stop). A host adds its own beside haest’s;cargo run -p haest --example thresholdruns two.cargo install haest-cligets thehaestcommand line agent.
Re-exports§
pub use serde_json;
Modules§
- code
code - haest’s JavaScript: an embedded QuickJS engine and the two things built on it.
- config
config - haest’s settings loader: it reads haest’s TOML config files, its
HAEST_*variables and its flags, laid one over the other in the order a host adds them, into the values haest-runtime is handed. - core
- haest-core: the agent loop and the contracts every plug-in implements.
- http
http - haest’s HTTP seam: the
HttpClienttrait haest’s parts send through, and its default. - mcp
mcp - haest’s MCP client: it connects MCP
servers and offers their tools to the agent as haest
Tools. - mods
mods - Mods: code that changes how a haest agent behaves, without a change to haest itself.
- prelude
- The key types,
async_trait,CancellationTokenand serde_json’sValueandjson!, for a glob import:use haest::prelude::*;is all animpl Tool,impl Providerorimpl AgentHooksneeds. - prompt
prompt - haest’s system prompt as a Jinja template, for a host that wants to
write its own. Opt-in: without it haest builds its prompt in code
(
haest_core::context::build_system_prompt), and nothing here is compiled. - providers
providers - Model API adapters for haest: the providers that turn one model call into an HTTP request and stream the answer back.
- runtime
runtime - haest assembled into one conversation: providers, workspace, tools, MCP
servers, mods, subagents, the inbox and the session file, behind a host’s
Ui. - session
session - A haest conversation another program can watch and drive while it runs.
- settings
settings - haest’s settings as plain typed values: everything a conversation is built from, with no files, no environment and no flags.
- tools
tools - haest’s built-in tools: the
Tools an agent reads, writes, searches, runs commands, fetches pages, keeps a task list and starts subagents with. - transport
transport - A haest session served to other programs: the same wire frames over a pipe pair, a Unix control socket or a broker link.
- wire
wire - haest’s wire format: how a running conversation talks to another program.
- workspace
workspace - Workspaces: the worlds haest’s tools and shell run in.
Structs§
- Agent
- One conversation with a model: its history, the model it talks to, and
what it runs on.
Agent::runruns one human turn. - Agent
Control - Steer or stop a running turn from another task. Cheap to clone.
- Agent
Deps - Everything the loop needs: what
Agent::newtakes. An agent’s own tools and system prompt, and what it runs on besides (SharedDeps), which the agents of one conversation share. - Agent
Hooks Ref - An
AgentHooks, shared: whatSharedDeps::hooksholds. - Agent
Options - How a new
Agentstarts: its model, its effort, and any history to resume. - Assistant
Message - One model call’s complete answer, as the
Providerfolded its stream into it. - Cancellation
Token - The turn’s cancel token, as
AgentHooks::before_model_call,ToolContext::cancelandProviderRequest::cancelhand it out: tokio-util’s, re-exported so a host names the same version. A token which can be used to signal a cancellation request to one or more tasks. - Change
SetRef - A
ChangeSet, shared: whatWorkspace::changeshands out. - Child
Env - The environment of every process the agent starts: a real shell, its background jobs, an MCP server. A child gets these variables and nothing else – not the host’s own environment, not its keys – unless the host put them here. Debug output shows the names only.
- Clock
Ref - A
Clock, shared: whatSharedDeps::clockholds. - DirEntry
- One entry of a directory listing (
Fs::read_dir), built withDirEntry::new. - Exec
Options - How to run one command: where, until when, and the interrupt.
- Exec
Result - How a command ended: what it printed, its exit code, and whether it ran out of time.
- FsLock
- A lock on a file, held until this value is dropped: what
Fs::try_lockhands back. - FsRef
- An
Fs, shared: whatWorkspace::fshands out, and what a session file or a skill set reads through. Built from the file system itself (MemFs::new(), a host’s own), or from anArcof one. - FsStat
- What
Fs::statknows about a path. - KeySource
Ref - A
KeySource, shared: whathaest-providers’ registry asks. Built from the source itself (a closure, a map), or from anArcof one. - Media
Part - Non-text input riding a user turn or a tool result. Bytes travel inline as base64: every request re-sends history, and the session log must replay without the original file.
- MemFs
- An in-memory
Fs: tests, scratch space, a sandbox with no disk behind it. - Model
Facts Ref - A
ModelFacts, shared: whatSharedDeps::factsholds. - Model
Resolver Ref - A
ModelResolver, shared: whatSharedDeps::modelsholds. Built from the resolver itself (a closure,haest-providers’ registry), or from anArcof one. - NoFacts
- Facts about no model: every answer “unknown”.
AgentDeps::new’s default. - NoHooks
- Hooks that change nothing:
AgentDeps::new’s default. - NoServices
- Services that offer nothing: publish returns no URL, the rest is dropped.
- Output
Chunks - Where a streamed command’s output goes, chunk by chunk as it arrives: stdout and stderr interleaved, whole UTF-8 characters only.
- Provider
Ref - A
Provider, shared: what aResolvedModelholds. Built from the provider itself, or from anArcof one a resolver keeps. - Provider
Request - One model call, provider-neutral: everything an adapter turns into its wire request.
- Reasoning
- How a model reasons: whether it can stop, and the levels it accepts.
- Resolved
Model - A spec resolved to the provider that serves it and the provider’s model id.
- Shared
Deps - What an agent runs on besides its tools and system prompt. Main and its subagents share one (a subagent hub gets it from its parent), so the whole tree runs on the same models, files, hooks and ledger.
- Shut
Workspace - No files, no shell: every file call fails (
ShutFs) and every command ends withEXIT_NOT_FOUND. The prompt note tells the model to work with the tools it was given. - System
Prompt Ref - A
SystemPrompt, shared: whatAgentDepsholds. Built from the prompt itself ("You are terse.", aString, a closure, a host’s own type), or from anArcof one. - Tool
Call - A tool call the model asked for.
- Tool
Context - What one tool call may use: where it runs, how it learns it was cancelled, the workspace and the host’s services.
- Tool
Output - What a tool’s run produced.
- Tool
Override - A tool with what the model reads changed: its name, its description, its
line in the prompt’s tool guide or its parameter schema. Everything else
(kind,
read_only,on_resume, what a call does) is the wrapped tool’s. - ToolRef
- A
Tool, shared: how aToolslist and the loop hold one. Built from the tool itself, or from anArcof one. - Tool
Result Message - The answer to one
ToolCall, as history keeps it and the model reads it. - Tool
Services Ref - A
ToolServices, shared: whatSharedDeps::servicesand everyToolContexthold. - Tool
Source Ref - A
ToolSource, shared: whatAgentDeps::toolsholds. - Tools
- A list of tools, in order, one per name: what a
ToolSourcehands the loop, and the simplest source there is (every tool advertised, every call). - Turn
Caps - The hard caps on one turn. 0 (or a zero duration) turns a cap off;
Defaultis every cap off. - Turn
Caps Source Ref - A
TurnCapsSource, shared: whatSharedDeps::turn_capsholds. - Turn
Outcome - How a turn ended: the
LoopEvent::TurnEndevent without its tallies.Agent::runreturns it. - Usage
- Token counts and cost of one model call, or a sum of several.
- User
Message - Input to the model in the user’s seat: what the human typed, and also what the loop sends on their behalf (steering, the turn guard’s nudge, a compaction summary).
- Wall
Clock - The wall clock (
now_ms):AgentDeps::new’s default. - Workspace
Ref - A
Workspace, shared: whatSharedDeps::workspaceand everyToolContexthold.
Enums§
- Assistant
Part - One block of an
AssistantMessage, in the order the model produced it. - Effort
- haest’s reasoning levels, cheapest first.
Offturns reasoning off where the model allows it. - File
Kind - What a path is.
- Inner
Call Event - A tool call made by another tool (call
parent_id): a transcript row of its own, not a model turn. - Input
Modality - A kind of input a model accepts, in OpenRouter’s names (
fileis a PDF). - Loop
Event - One thing that happened in a turn. Serialized with a snake_case
typetag and camelCase fields ({"type":"turn_end","stopReason":"end_turn",...}). - Message
- One entry of a conversation’s history.
- Model
Error - Why a model spec cannot be served: what
ModelResolver::resolveandparse_model_specrefuse. The loop shows it to the human with its causes (report). - OnResume
- What a resumed durable run (
crate::run) does with a call that may have run before the stop ([Tool::on_resume]). - Provider
Event - One event of a model call’s stream. The deltas are for showing progress;
only
ProviderEvent::Done’s message goes into history. - Stop
Reason - Why a model call ended (
AssistantMessage::stop_reason), or a whole turn (TurnOutcome::stop_reason). - Tool
Error - Why a tool call failed. [
Tool::execute] returns it; the loop turns it into an error result the model reads, and the turn goes on. - Workspace
Mode - What kind of world a
Workspaceis (theworkspacesetting’s words).
Traits§
- Agent
Hooks - A host’s say in the loop.
- Change
Set - What a sandbox changed, and putting it on the real disk.
Workspace::changeshands it out; only a sandbox has one. - Clock
- PLUG POINT: the clock the turn guard’s time cap reads, in milliseconds
since the epoch (
SharedDeps::with_clock). A host that pauses runs gives one that stands still while paused. A closureFn() -> u64is a clock. - Event
Sink - Where a turn’s events go.
- Fs
- A file system: the one way haest reads and writes files.
- KeySource
- Named values a provider asks the host for: its key and endpoint overrides
(
OPENROUTER_API_KEY,ANTHROPIC_BASE_URL, a providers.json entry’sapiKeyEnv). The host answers from its environment, a keychain, a vault, or not at all. An empty value counts as none. - Model
Facts - PLUG POINT: what the host knows about a model spec
(
Agent::model_spec), set onSharedDeps::facts. Asked again before every model call, so the answers may follow the model. Every method defaults to “unknown”;NoFactsknows nothing. - Model
Resolver - Turns a
provider:modelspec into a live provider. The loop asks it before every model call, so a model switch mid-conversation takes effect at once. - Provider
- A model API: turns a
ProviderRequestinto a stream ofProviderEvents. - System
Prompt - The system prompt, built again before every model call (instruction files and skills can change mid-conversation).
- Tool
- A tool the model can call.
- Tool
Services - What the host offers every tool. All optional: the defaults do nothing.
- Tool
Source - Where the loop gets its tools, asked again before every model call (deferred tools and MCP servers change the list mid-conversation).
- Turn
Caps Source - PLUG POINT: the
TurnCapsfor a model spec, asked before every model call (SharedDeps::turn_caps). The host’s policy, apart from what it knows about a model (ModelFacts): token caps may follow a model’s window. ATurnCapsis one (the same caps for every model), and so is a closureFn(&str) -> Option<TurnCaps>. - Workspace
- The world the agent works in: a file system and a shell, one door for both.
Functions§
- answer_
stream - The stream of one model call, written as an async block:
producegets theDeltasto send as the answer arrives and returns the whole answer, which the stream ends with as its oneProviderEvent::Done. - now_ms
- Milliseconds since the Unix epoch, by the wall clock; 0 if the clock is
set before 1970. What
WallClockreads. - opt_
bool - A flag:
trueandfalse, also as strings in any case ("True"). Missing,nulland""are false. - opt_
count - An optional count (a limit, an offset, a timeout in ms): a number as
opt_numreads it, rounded down to a whole one, and a huge one held atu64::MAX. Missing,nulland""are None. - opt_num
- A number, also as a numeric string (models send both).
Missing,
null,""and whitespace are None. - opt_str
- An optional string argument; missing,
nulland""are all None. - req_num
- A required number, also as a numeric string (
opt_num). - req_str
- A required, non-empty string argument.
- runtime_
inputs configandruntime - What the loader read, as the runtime’s inputs on the real disk: the
settings, the child environment and the variables passed on purpose, the
provider keys (the loader’s environment), providers.json, the trusted
.mcp.jsonservers and the OpenRouter routing, sent over the default reqwest client. - truncate_
middle - Keep the head and tail of long output; the middle is where nothing useful
lives.
maxcounts characters, never splitting one.
Type Aliases§
- BoxError
- The error a trait a host implements returns where haest only shows it (a
mod’s events): any error (
e.into(),?) or a line of text ("why".into()). Show it withreport(report(&*e)). - JsonMap
- A tool call’s arguments: a JSON object.
- Provider
Stream - What
Provider::streamreturns: a boxed,'static,Sendstream ofProviderEvents.
Attribute Macros§
- async_
trait - Marks an
impl Tool(or any other async trait impl in haest) so itsasync fns compile; the same macro haest’s traits are declared with.