Skip to main content

Crate behest

Crate behest 

Source
Expand description

behest runtime kernel (facade re-exports). temporarily allow during migration Building blocks for Rust-native AI agent runtimes.

§Architecture

behest has two complementary surfaces:

The invocation surface — a Socket.IO-inspired emit / on model for interacting with an agent. Emit a user message, receive streaming events back through typed handlers. This is the caller-facing API, built on RuntimeInvocation.

The assembly surface — pluggable components (providers, tools, stores, transports) wired together via ComponentRegistry and driven by a coordinated lifecycle. This is the operator-facing API for composing a runtime from parts, built on ManagedRuntime.

                  emit("question")       on(TextDelta, handler)
  Caller ──────────►  RuntimeInvocation  ──────────►  Caller
                         │
                         ▼
                   AgentRuntime  ◄──  ComponentRegistry
                         │              │
                         ▼              ▼
                run_loop (FSM)      provider / tool / store / transport

The two surfaces are independent: you can use RuntimeInvocation with a hand-assembled AgentRuntime, or drive the ManagedRuntime lifecycle from your own invocation layer. They meet at AgentRuntime — the shared kernel that both paths produce.

§Quick start

use behest::prelude::*;
use behest::runtime::RuntimeInvocation;

// 1. Build config & runtime
let config = AgentConfigBuilder::default()
    .with_env("BEHEST")?
    .with_provider(ProviderId::new("openai"), ProviderConfig::new("https://api.openai.com/v1")
        .with_provider_type(ProviderType::OpenAi)
        .with_api_key("env:OPENAI_API_KEY")
        .with_model("gpt-4o"))
    .build()?;
let runtime = Arc::new(config.into_runtime().await?);

// 2. Wrap in the invocation facade
let inv = RuntimeInvocation::new(runtime);

// 3. Subscribe to text deltas
let handle = inv.on(EventKind::TextDelta, |envelope, _session, _control| async move {
    if let AgentEvent::TextDelta(td) = &envelope.event {
        print!("{}", td.delta);
    }
}).await?;

// 4. Emit a request
let output = inv.emit(|_session, _control| async move {
    EmitRequest::new(provider_id, model, "Hello, world!")
}).await?;

drop(handle);

§Modules

  • runtime: Runtime kernel, invocation facade, component system, policy
  • provider: Provider traits, request/response types, and registry
  • tool: Tool trait, registry, scoping
  • context: Multi-adapter context factory for composing chat requests
  • store: Persistence traits and backends for sessions, embeddings, artifacts
  • config: Centralized configuration with file, env, and builder support
  • adapt: Concrete provider adapters (OpenAI, Anthropic)
  • error: Error types and result aliases
  • rag: Retrieval-Augmented Generation context adapter (feature = rag)
  • queue: External event publishing to message brokers (feature = queue)

Re-exports§

pub use crate::runtime::CompactionResult;
pub use crate::runtime::CompactionService;

Modules§

adapt
Concrete provider adapters.
agent
Agent definition and registry.
config
Centralized agent configuration.
context
Re-export of the high-level context factory API, which now lives in behest_context. This module is preserved for facade compatibility; prefer use behest_context::* directly in new code.
error
Error types shared across the public API.
health
Health status primitives shared by every component.
prelude
Convenient imports for application and integration code.
provider
Provider-neutral contracts for chat, tools, streaming, and embeddings.
queue
External event publishing for agent observability.
rag
Retrieval-Augmented Generation (RAG) context adapter.
runtime
Runtime facade re-exports.
store
Persistence traits and storage backends.
token
Token estimation using character-based heuristics.
tool
Re-export of the tool system from behest_tool. This module is preserved for facade compatibility.
tool_output
Tool output configuration (re-exported from behest_runtime).
tool_scope
Tool scope helpers re-exported from behest_runtime.

Structs§

AgentRuntime
Streaming-first agent runtime kernel.
AnthropicChatComponent
Component wrapper for AnthropicChatAdapter.
CacheStats
Aggregated prompt-cache statistics over a window of events.
ComponentContext
Context handed to Component::init and propagated through dependent components.
ComponentDescriptor
Static descriptor of a component kind, used by the registry to plan initialization order without holding the actual factory.
ComponentRegistry
The central component registry.
ContextPipelineComponent
Component wrapper for ContextPipeline.
ContextPipelineConfig
JSON configuration for ContextPipelineComponent.
Control
Cooperative lifecycle handle shared across an invocation.
EmitRequest
Transport-neutral request for a single runtime invocation.
ExtensionPoint
Typed, name-indexed collection of Arc<T>.
Extensions
The composable, hot-pluggable facade over every pluggable runtime element.
FactoryRegistry
A registry that maps kind strings (e.g. "provider.openai") to FactoryInvoker instances.
FileSessionDataStore
File-system SessionDataStore backed by JSON files.
FileSnapshotStore
Filesystem-based SnapshotStore with atomic write semantics.
InvocationHandle
Handle to a background listener task started by RuntimeInvocation::on.
InvocationSession
Invocation-time session context with temporary KV storage.
ManagedRuntime
Unified container orchestrating AgentRuntime, ComponentRegistry, and a root ShutdownToken.
MemoryArtifactStoreComponent
Component wrapper for MemoryArtifactStore.
MemoryEmbeddingStoreComponent
Component wrapper for MemoryEmbeddingStore.
MemoryExecutionStoreComponent
Component wrapper for MemoryExecutionStore.
MemoryRunStoreComponent
Component wrapper for MemoryRunStore.
MemorySessionDataStore
In-memory SessionDataStore backed by a HashMap.
MemorySessionStoreComponent
Component wrapper for MemorySessionStore.
ModelRouter
Routes model requests (chat and embedding) across providers with capability checking, exponential-backoff retry, and fallback chains.
OpenAiChatComponent
Component wrapper for OpenAiChatAdapter.
OpenAiEmbeddingComponent
Component wrapper for OpenAiEmbeddingAdapter.
PromptCacheConfig
Prompt caching configuration.
ProviderHttpComponentConfig
JSON-deserializable configuration for HTTP-backed providers like OpenAI and Anthropic. Uses plain String for the API key (instead of SecretString) so that it can be deserialised from JSON/YAML/TOML.
RedisSessionDataStore
Redis-backed implementation of SessionDataStore.
RunId
Unique identifier for a single agent run invocation.
RunOutput
Output of a completed agent run.
RunRequest
Request to start a new agent run.
RuntimeEventBridge
Drains AgentRuntime::subscribe into the event store and stream adapter.
RuntimeEventBridgeHandle
Handle to a running RuntimeEventBridge task.
RuntimeEventEnvelope
Envelope wrapping an AgentEvent with cross-instance routing metadata.
RuntimeEventId
Globally unique identifier for a single runtime event.
RuntimeInvocation
Transport-neutral invocation facade over AgentRuntime.
RuntimePolicy
Runtime policy for agent execution.
RuntimeSubscription
Replay page plus a live stream for a single subscription.
RuntimeSubscriptionHub
Combines replay and live fanout for runtime event streams.
ShutdownToken
Hierarchical, cooperative shutdown token.
Snapshot
A serialized execution snapshot of an active agent run.
ToolOutputConfig
Configuration for tool output truncation.
TruncationResult
Result of tool output truncation.
TypedAnyComponent
Adapter from a typed Component to the type-erased AnyComponent trait. Created by TypedFactory::build.
TypedFactory
Convenience wrapper that adapts a concrete Component into a ComponentFactory.

Enums§

AgentEvent
Event emitted during agent runtime execution.
AnyComponentError
Type-erased error from a boxed AnyComponent. The original typed error is preserved as a string for log purposes; if callers need the typed error they should downcast via AnyComponent::as_any_arc.
ComponentError
Error type for components constructed from configuration.
ComponentState
Initialization state of a registered component.
ContextError
Errors produced during context construction.
Error
Top-level crate error.
EventKind
Kind of event a caller can subscribe to via RuntimeInvocation::on.
ExtensionError
Errors raised by ExtensionPoint operations.
FactoryError
Errors from factory creation or registry operations.
HealthStatus
Tri-state health classification of a component.
InvocationError
Errors raised by the invocation facade.
InvocationEvent
Unified event envelope wrapping runtime and chat-stream events.
ManagedError
Errors from ManagedRuntime operations.
ProviderError
Errors produced by provider implementations.
RegistryError
Errors raised by ComponentRegistry operations.
RunStatus
Status of an agent run.
RuntimeError
Errors that can occur during runtime execution.
RuntimeEventBridgeError
Errors surfaced by a RuntimeEventBridge handle.
RuntimeEventStoreError
Errors raised by a RuntimeEventStore.
RuntimeRoom
Fanout routing key, inspired by a Socket.IO room but transport-neutral.
RuntimeStreamError
Errors raised by a RuntimeStreamAdapter.
RuntimeSubscriptionError
Errors raised while assembling a RuntimeSubscription.
SessionDataError
Errors returned by SessionDataStore implementations.
StorageError
Errors produced by storage backends.
ToolError
Errors produced during tool execution.

Traits§

AnyComponent
Object-safe view of a Component instance, used by the registry to store and drive components of heterogeneous types uniformly.
Component
The core contract every pluggable runtime element implements.
ComponentFactory
Type-erased factory for a concrete Component type. The registry holds factories as Box<dyn ComponentFactory> so it can drive heterogeneous types uniformly.
RuntimeEventStore
Authoritative replay source for runtime events.
RuntimeStreamAdapter
Transport-neutral live fanout for runtime event envelopes.
SessionDataStore
Pluggable backend for per-session temporary key-value data.
SnapshotStore
Trait for snapshot persistence backends.

Functions§

default_factory_registry
Returns a FactoryRegistry pre-populated with all built-in component factory invokers:
register_context_pipeline
Registers the context-pipeline factory invoker into a FactoryRegistry.
register_memory_stores
Registers all memory-store factory invokers into a FactoryRegistry.
register_providers
Registers all provider factory invokers into a FactoryRegistry.

Type Aliases§

FactoryFn
Thread-safe factory function pointer — an Arc around a boxed closure.
Result
Crate-wide result type.