Skip to main content

Crate haest

Crate haest 

Source
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::TurnEnd

Agent::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, …).

TraitWhat it ishaest’s own
ModelResolver, Providerturns a model spec (openrouter:z-ai/glm-5.3) into a model APIproviders::ProviderRegistry
http::HttpClienthow every model call and web request travelshttp::ReqwestClient
ToolSource, Toolthe tools the model may callTools, tools::builtin_tools, mcp, mods, code
Workspace, Fsthe files and the shell every tool goes throughworkspace::RealWorkspace, workspace::SandboxWorkspace, ShutWorkspace
SystemPromptthe system prompt, rebuilt for each model callString, &'static str, closures
AgentHooksthe host’s say in the loop: each message to save, compaction before a model call, mediaNoHooks, runtime
ToolServiceswhat tools hand the host while they run: inner-call rows, debug linesNoServices, runtime
ModelFactswhat the host knows of each model: the inputs it takes, its effortsNoFacts, runtime
TurnCapsSourcethe caps on each turn, per modelTurnCaps (the same for every model), runtime
Clockthe time a turn’s time cap readsWallClock
EventSinkwhere the turn’s events goclosures, Vec<LoopEvent>, a tokio channel
KeySourceAPI keys and endpoints, asked for by nameclosures, 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.

FeatureBringsDefault
httphttp: the HTTP seam the model calls and GenerateImage send through (WebFetch and MCP servers keep clients of their own); on with providers and toolsyes
reqwesthttp::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
providersproviders: Anthropic Messages, OpenAI Chat Completions and Responses, OpenRouter, any OpenAI-compatible serveryes
workspaceworkspace: the real disk and bash, or a sandbox over a copy-on-write overlayyes
toolstools: Read, Write, Edit, Glob, Grep, Bash, WebFetch, tasks, subagents and moreyes
mcpmcp: MCP servers (stdio, streamable HTTP) and their toolsyes
rmcpmcp::rmcp and mcp::McpHub::connect_transport: an MCP server over a transport the host opened (rmcp’s types in haest’s API); turns on mcpno
codecode: the Code tool and the sandbox js command, in embedded QuickJSyes
modsmods: change how haest behaves without forking it; approvals, plan modeyes
settingssettings: every setting as a plain value a host writes out in Rustyes
configconfig: the loader for haest’s TOML files, HAEST_* variables and flags; with mcp too, it reads a trusted project’s .mcp.jsonno
runtimeruntime: a whole conversation built from settings, behind a host’s UIno
wirewire: the envelope around a conversation’s events, the requests a peer sends, a replay ring with gaps, an NDJSON codecno
sessionsession: a conversation another program watches and drives while it runs (input mid-turn, catch-up, approvals over it); with runtime, the whole conversation is oneno
transporttransport: the session served to another program, one connection’s rules over any line source and sinkno
transport-stdiotransport::Stdio: a parent process drives the conversation over this one’s stdin and stdoutno
transport-brokertransport::Broker: the conversation dials out to a broker over a WebSocket (pulls a WebSocket client on rustls)no
transport-unixtransport::UnixSocket: programs on this machine watch (or drive) the conversation over a Unix socket; transport::running_sessions and transport::connect_session find and reach oneno
promptprompt: 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 callno
testingcore::testing: a scripted model and other fakes for testsno
# 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

  • runtime builds what the haest CLI runs: settings in, a conversation with sessions, subagents, MCP, mods and compaction out. Start there for a full agent behind your own UI.
  • settings lists 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 notebook runs 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 threshold runs two.
  • cargo install haest-cli gets the haest command line agent.

Re-exports§

pub use serde_json;

Modules§

codecode
haest’s JavaScript: an embedded QuickJS engine and the two things built on it.
configconfig
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.
httphttp
haest’s HTTP seam: the HttpClient trait haest’s parts send through, and its default.
mcpmcp
haest’s MCP client: it connects MCP servers and offers their tools to the agent as haest Tools.
modsmods
Mods: code that changes how a haest agent behaves, without a change to haest itself.
prelude
The key types, async_trait, CancellationToken and serde_json’s Value and json!, for a glob import: use haest::prelude::*; is all an impl Tool, impl Provider or impl AgentHooks needs.
promptprompt
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.
providersproviders
Model API adapters for haest: the providers that turn one model call into an HTTP request and stream the answer back.
runtimeruntime
haest assembled into one conversation: providers, workspace, tools, MCP servers, mods, subagents, the inbox and the session file, behind a host’s Ui.
sessionsession
A haest conversation another program can watch and drive while it runs.
settingssettings
haest’s settings as plain typed values: everything a conversation is built from, with no files, no environment and no flags.
toolstools
haest’s built-in tools: the Tools an agent reads, writes, searches, runs commands, fetches pages, keeps a task list and starts subagents with.
transporttransport
A haest session served to other programs: the same wire frames over a pipe pair, a Unix control socket or a broker link.
wirewire
haest’s wire format: how a running conversation talks to another program.
workspaceworkspace
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::run runs one human turn.
AgentControl
Steer or stop a running turn from another task. Cheap to clone.
AgentDeps
Everything the loop needs: what Agent::new takes. An agent’s own tools and system prompt, and what it runs on besides (SharedDeps), which the agents of one conversation share.
AgentHooksRef
An AgentHooks, shared: what SharedDeps::hooks holds.
AgentOptions
How a new Agent starts: its model, its effort, and any history to resume.
AssistantMessage
One model call’s complete answer, as the Provider folded its stream into it.
CancellationToken
The turn’s cancel token, as AgentHooks::before_model_call, ToolContext::cancel and ProviderRequest::cancel hand 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.
ChangeSetRef
A ChangeSet, shared: what Workspace::changes hands out.
ChildEnv
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.
ClockRef
A Clock, shared: what SharedDeps::clock holds.
DirEntry
One entry of a directory listing (Fs::read_dir), built with DirEntry::new.
ExecOptions
How to run one command: where, until when, and the interrupt.
ExecResult
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_lock hands back.
FsRef
An Fs, shared: what Workspace::fs hands 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 an Arc of one.
FsStat
What Fs::stat knows about a path.
KeySourceRef
A KeySource, shared: what haest-providers’ registry asks. Built from the source itself (a closure, a map), or from an Arc of one.
MediaPart
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.
ModelFactsRef
A ModelFacts, shared: what SharedDeps::facts holds.
ModelResolverRef
A ModelResolver, shared: what SharedDeps::models holds. Built from the resolver itself (a closure, haest-providers’ registry), or from an Arc of 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.
OutputChunks
Where a streamed command’s output goes, chunk by chunk as it arrives: stdout and stderr interleaved, whole UTF-8 characters only.
ProviderRef
A Provider, shared: what a ResolvedModel holds. Built from the provider itself, or from an Arc of one a resolver keeps.
ProviderRequest
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.
ResolvedModel
A spec resolved to the provider that serves it and the provider’s model id.
SharedDeps
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.
ShutWorkspace
No files, no shell: every file call fails (ShutFs) and every command ends with EXIT_NOT_FOUND. The prompt note tells the model to work with the tools it was given.
SystemPromptRef
A SystemPrompt, shared: what AgentDeps holds. Built from the prompt itself ("You are terse.", a String, a closure, a host’s own type), or from an Arc of one.
ToolCall
A tool call the model asked for.
ToolContext
What one tool call may use: where it runs, how it learns it was cancelled, the workspace and the host’s services.
ToolOutput
What a tool’s run produced.
ToolOverride
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 a Tools list and the loop hold one. Built from the tool itself, or from an Arc of one.
ToolResultMessage
The answer to one ToolCall, as history keeps it and the model reads it.
ToolServicesRef
A ToolServices, shared: what SharedDeps::services and every ToolContext hold.
ToolSourceRef
A ToolSource, shared: what AgentDeps::tools holds.
Tools
A list of tools, in order, one per name: what a ToolSource hands the loop, and the simplest source there is (every tool advertised, every call).
TurnCaps
The hard caps on one turn. 0 (or a zero duration) turns a cap off; Default is every cap off.
TurnCapsSourceRef
A TurnCapsSource, shared: what SharedDeps::turn_caps holds.
TurnOutcome
How a turn ended: the LoopEvent::TurnEnd event without its tallies. Agent::run returns it.
Usage
Token counts and cost of one model call, or a sum of several.
UserMessage
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).
WallClock
The wall clock (now_ms): AgentDeps::new’s default.
WorkspaceRef
A Workspace, shared: what SharedDeps::workspace and every ToolContext hold.

Enums§

AssistantPart
One block of an AssistantMessage, in the order the model produced it.
Effort
haest’s reasoning levels, cheapest first. Off turns reasoning off where the model allows it.
FileKind
What a path is.
InnerCallEvent
A tool call made by another tool (call parent_id): a transcript row of its own, not a model turn.
InputModality
A kind of input a model accepts, in OpenRouter’s names (file is a PDF).
LoopEvent
One thing that happened in a turn. Serialized with a snake_case type tag and camelCase fields ({"type":"turn_end","stopReason":"end_turn",...}).
Message
One entry of a conversation’s history.
ModelError
Why a model spec cannot be served: what ModelResolver::resolve and parse_model_spec refuse. 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]).
ProviderEvent
One event of a model call’s stream. The deltas are for showing progress; only ProviderEvent::Done’s message goes into history.
StopReason
Why a model call ended (AssistantMessage::stop_reason), or a whole turn (TurnOutcome::stop_reason).
ToolError
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.
WorkspaceMode
What kind of world a Workspace is (the workspace setting’s words).

Traits§

AgentHooks
A host’s say in the loop.
ChangeSet
What a sandbox changed, and putting it on the real disk. Workspace::changes hands 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 closure Fn() -> u64 is a clock.
EventSink
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’s apiKeyEnv). The host answers from its environment, a keychain, a vault, or not at all. An empty value counts as none.
ModelFacts
PLUG POINT: what the host knows about a model spec (Agent::model_spec), set on SharedDeps::facts. Asked again before every model call, so the answers may follow the model. Every method defaults to “unknown”; NoFacts knows nothing.
ModelResolver
Turns a provider:model spec 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 ProviderRequest into a stream of ProviderEvents.
SystemPrompt
The system prompt, built again before every model call (instruction files and skills can change mid-conversation).
Tool
A tool the model can call.
ToolServices
What the host offers every tool. All optional: the defaults do nothing.
ToolSource
Where the loop gets its tools, asked again before every model call (deferred tools and MCP servers change the list mid-conversation).
TurnCapsSource
PLUG POINT: the TurnCaps for 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. A TurnCaps is one (the same caps for every model), and so is a closure Fn(&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: produce gets the Deltas to send as the answer arrives and returns the whole answer, which the stream ends with as its one ProviderEvent::Done.
now_ms
Milliseconds since the Unix epoch, by the wall clock; 0 if the clock is set before 1970. What WallClock reads.
opt_bool
A flag: true and false, also as strings in any case ("True"). Missing, null and "" are false.
opt_count
An optional count (a limit, an offset, a timeout in ms): a number as opt_num reads it, rounded down to a whole one, and a huge one held at u64::MAX. Missing, null and "" 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, null and "" are all None.
req_num
A required number, also as a numeric string (opt_num).
req_str
A required, non-empty string argument.
runtime_inputsconfig and runtime
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.json servers 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. max counts 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 with report (report(&*e)).
JsonMap
A tool call’s arguments: a JSON object.
ProviderStream
What Provider::stream returns: a boxed, 'static, Send stream of ProviderEvents.

Attribute Macros§

async_trait
Marks an impl Tool (or any other async trait impl in haest) so its async fns compile; the same macro haest’s traits are declared with.