Expand description
§agentyk
Compose agents from values and run them.
An Agent is built entirely by value — a system prompt, a model
(ModelSpec), capabilities (Capability), tools (Tool) — with no
entity creation, no registration, and no ids to thread. Ids exist only as
internal correlation handles on sessions and events.
This is the facade crate: builders, the canonical engine and its
in-process host, bundled drivers (sim; OpenAI/Anthropic behind http), the
JSONL event store, filesystem support, and MCP support. The portable
contract — traits, the event protocol, and the turn state machine — lives in
agentyk-core and is fully
re-exported here; depend on core directly only when implementing a seam
(a custom driver, capability, or event store).
The domain language (events protocol, capabilities, drivers, the
input → reason → act turn) is inherited from
everruns; agentyk is the
value-first core that everruns-core and everruns-runtime are intended to
be rebuilt on top of.
use agentyk::{Agent, ModelSpec, SimDriver, SimTurn};
let agent = Agent::builder()
.name("greeter")
.system_prompt("You are terse.")
.model(ModelSpec::llmsim())
.driver(SimDriver::new([SimTurn::text("hi!")]))
.build()?;
let mut session = agent.session();
let turn = session.run("hello").await?;
assert_eq!(turn.response, "hi!");
assert!(!session.events().await?.is_empty());With a real provider (feature http):
let agent = Agent::builder()
.system_prompt("You are a coding agent.")
.model(ModelSpec::anthropic("claude-sonnet-4-5").api_key(key))
.capability(my_capability)
.build()?;
let result = agent.run("list the files").await?;Re-exports§
pub use drivers::sim::SimDriver;pub use drivers::sim::SimToolCall;pub use drivers::sim::SimTurn;pub use filesystem::FileEntry;fspub use filesystem::FileStat;fspub use filesystem::FileSystem;fspub use filesystem::FileSystemCapability;fspub use filesystem::InMemoryFileSystem;fspub use filesystem::RealDiskFileSystem;fspub use filesystem::WriteBlocklistFileSystem;fspub use hooks::ShellHook;hookspub use jsonl_log::JsonlEventLog;pub use mcp::oauth::McpOAuthLoginOptions;mcp-oauthpub use mcp::oauth::McpOAuthTokenProvider;mcp-oauthpub use mcp::oauth::McpOAuthTokenSet;mcp-oauthpub use mcp::oauth::PreparedMcpOAuthLogin;mcp-oauthpub use mcp::oauth::prepare_mcp_oauth_login;mcp-oauthpub use mcp::oauth::refresh_mcp_oauth_tokens;mcp-oauthpub use mcp::McpAuthProvider;mcppub use mcp::McpCapability;mcppub use mcp::McpClient;mcppub use mcp::McpProtocolMode;mcppub use mcp::McpServer;mcppub use mcp::McpServerDiscovery;mcppub use mcp::McpTransport;mcppub use mcp::StaticBearer;mcppub use drivers::anthropic::AnthropicDriver;httppub use drivers::openai::OpenAiDriver;http
Modules§
- agent
- Agent — a composed value, not a record.
- atoms
- Atoms — the stateless, effectful operations a host runs between
crate::turn::TurnStatetransitions. - budget
- The budget seam — deliberately stopping a turn that would otherwise keep burning resources without producing useful work.
- cancellation
- Cooperative turn cancellation.
- capability
- Capabilities — composable extensions that give an agent behavior.
- concurrency
- Running several futures at once, without a runtime.
- context
- The context-assembly seam — what actually gets sent to the model, as opposed to what’s in the log.
- controls
- Per-turn overrides — mirrors everruns’
Controls. - driver
- LLM drivers — the multi-provider seam.
- drivers
- Bundled
crate::driver::ChatDriverimplementations. - engine
- Canonical one-step turn semantics shared by every execution host.
- error
- Crate error type.
- event
- The event protocol.
- event_
log - Event log — the append-only record of everything a session did, and the persistence seam of the library.
- event_
types - The dot-notation type string of every event this crate emits, as it
appears in
Event::event_typeand on disk. - extensions
- A typed extension bag — axum’s
Extensionspattern, socrate::tool::ToolContextcan carry arbitrary host-injected services (a credential store, a workspace handle, anything) without core knowing what they are. A tool that needs one downcasts by type; core stays free of any concrete host concern (noSessionFileSystem, no credential store type, nothing DB- or server-shaped in this crate). - filesystem
fs - File system access as a bundled capability.
- hook
- User hooks at stable agent lifecycle boundaries.
- hooks
hooks - Trusted local shell-backed user hooks.
- host
- Per-run host context and the single event recording path.
- id
- Typed identifiers.
- in_
process - The in-process host for the canonical turn engine.
- input
- Steering — input that arrives while a turn is already running.
- jsonl_
log - File-backed event log: one JSON-serialized
Eventper line — the batteries-included durability option (the yolop pattern). - mcp
mcp - MCP — Model Context Protocol support.
- message
- Chat messages exchanged with LLM drivers and reconstructed from the event
log. Mirrors the everruns message vocabulary (
Message,Role,ToolCall,ContentPart). - middleware
- Middleware — interception points inside the turn loop.
- prelude
- The names most applications want in scope at once.
- profile
- What a model can actually do — and catching a request it can’t, early.
- replay
- Replay — fold an event log back into message history.
- session
- Session — a conversation with an agent.
- tool
- Tools — functions the model can call during a turn.
- turn
- Turn state machine — the deterministic turn reducer.
Structs§
- Agent
- A runnable agent, composed by value. Cheap to clone (shared internals).
- Agent
Builder - Fluent, by-value agent composition.
- Agent
Definition - Agent behavior, separate from the resources that run it.
- Agent
Environment - Host resources used to execute an
AgentDefinition. - Cancellation
Token - A cancellation signal shared between a caller and a running turn.
- Chat
Request - One LLM completion request: everything a driver needs to produce the next assistant message.
- Chat
Response - What one completion produced.
- Command
Context - Context available while executing a command. Commands are host-invoked
directly (e.g. a user typing
/goal set X) and bypass the turn loop entirely, so there’s noturn_id— only a session. - Command
Descriptor - One slash-command a capability exposes — everruns’
CommandDescriptor, pared down to what a host needs to list and invoke it. - Composite
Event Listener - Listener that forwards each event to an ordered collection of listeners.
- Context
Assembly - Model messages plus the accounting and provenance behind them.
- Context
Event - Durable observational event produced while assembling context.
- Context
Request - Everything a context policy needs to shape one model request.
- Context
Source - Provenance for one contribution to assembled model context.
- Driver
Id - Names a provider protocol implementation, e.g.
"openai","anthropic","llmsim". An open string (not a closed enum) so embedders can register their own drivers. - Driver
Registry - Routes a
ModelSpecto theChatDriverthat speaks its protocol. - Event
- A fully-recorded event.
idandtsare always assigned on emission;sequenceisSome(contiguous per session, starting at 1) for durable events andNonefor ephemeral ones — seeEventData::is_ephemeral. - Event
Page - One bounded event read plus cursors needed to continue consistently.
- Event
Range - Bounded forward read over one session timeline.
- Event
Request - An event about to be emitted — same shape as
Eventminus the fields assigned on emission. - Extensions
- Type-keyed bag of
Arc<T>values, one per type. Cheap to clone (each entry is anArc). - External
Actor - Identity of a user message originating outside the embedding application.
- FnTool
- A tool built from a closure — the quickest way to hand the model a function.
- History
- A session’s message history: the fold of its event log, and nothing else.
- Hook
Context - Session and optional turn identity supplied to a hook.
- Hook
Matcher - Restricted matcher for tool hook events.
- Hook
Payload - Structured input delivered to one hook invocation.
- Hook
Rejection - A block decision returned by a prompt hook.
- Image
Content Part - Image content, as a URL or inline base64 data (mirrors everruns’
ImageContentPart). - InMemory
Event Log - In-memory event log. The default for
Agent::session()and the natural choice for tests. - InMemory
Model Catalog - A catalog built from entries you supply — the straightforward implementation, for hosts whose model knowledge is a literal list.
- InMemory
Snapshot Store - In-memory snapshot storage for tests and short-lived applications.
- InProcess
Executor - Executes every operation from
TurnEngineimmediately in the caller’s async task. - Input
Queue - Messages waiting to join a turn already in progress. Cheap to clone; every clone shares one queue.
- Message
- One message in a conversation.
- Model
Profile - What one model supports. Every field is optional knowledge:
Nonemeans “not stated”, never “not supported”, so a partial catalog entry can still be useful. - Model
Spec - A model, by value (everruns:
ResolvedModel): wire model name, the driver that speaks its protocol, and optional credentials/endpoint. Build it inline and hand it to the agent — nothing to register. - Noop
Event Listener - Listener that intentionally ignores every event.
- Passthrough
Context Assembler - Sends the full history unchanged — the default.
- Prepared
Step - One engine decision: persist
events, then executeoperation. - Prepared
Tool Call - One call in a prepared tool batch.
- Prepared
Turn Start - Canonical effects of opening a turn, before any model work is scheduled.
- Projection
Snapshot - Disposable projection anchored to an immutable session point.
- Reasoning
Config - Reasoning/thinking configuration for models that support it. Mirrors
everruns’
ReasoningConfig. - RunOptions
- Everything one
Session::run_with_optionscall can override. Defaults (RunOptions::default()) reproduce plainSession::run: an uncancellable turn on the agent’s default model. - Session
- A conversation with an agent.
- Session
Point - Immutable address of a durable point in a session timeline.
- Session
View - Read-only projection of a session at an immutable historical point.
- System
Prompt Context - Context available while assembling the system prompt.
- Text
Content Part - Text content.
- Tool
Call - A tool invocation requested by the model.
- Tool
Context - Execution-time context handed to a tool.
- Tool
Definition - What the model sees: name, description, and a JSON-schema for arguments.
- Tool
Invocation - One tool call about to run (or just finished), with everything a middleware needs to judge it.
- Tool
Output - The result of executing a tool.
- Tool
Policy - Host-side policy about a tool — how it is offered, not what it does.
- Tool
Progress - One progress report from a tool that is still running.
- Turn
Controls - Per-turn overrides, applied on top of the agent’s default model.
- Turn
Engine - The single interpreter of Agentyk turn semantics.
- Turn
Host - Agent composition plus the session-specific resources for one turn.
- Turn
Result - The outcome of one executed turn.
- Turn
State - Serializable turn bookkeeping. Everything else a step needs — model, credentials, assembled tools, message history — is environment the host provides per step; it is deliberately NOT part of this state.
- Usage
- Token counts for one completion.
Enums§
- Budget
Decision - Whether a turn may take its next action.
- Content
Part - A part of message content: text or an image. Tool calls and tool results
stay as dedicated
Messagefields rather than content-part variants — a deliberate simplification over everruns’ unified content-part model. - Deferrable
Policy - Whether a tool’s definition is sent to the model up front. Mirrors
everruns’
DeferrablePolicy(what ToolSearch-style deferred-tool discovery is built on). - Error
- Errors surfaced by agentyk.
- Event
Data - The payload of an
Event— what actually happened. - Expected
Version - Required stream version when appending a durable event batch.
- Hook
Error Policy - Policy applied when a hook returns
HookOutcome::Error. - Hook
Event - A stable lifecycle point at which a user hook can run.
- Hook
Outcome - What a hook asks the engine to do.
- LlmError
Kind - Coarse classification of an LLM driver failure, so a host (in particular
a durable executor retrying activities) can tell a transient failure
worth retrying apart from a terminal one that will never succeed by
itself. Mirrors the intent of everruns’
LlmErrorKind. - Role
- Who a
Messagecame from. - Seal
Reason - Why a turn was deliberately sealed rather than left to run to
MaxIterationsor fail. Mirrors everruns’SealReason. - Tool
Call Decision - What a middleware decides about a tool call it is shown.
- Tool
Chain Outcome - The resolution of a whole
TurnMiddleware::before_toolchain. - Turn
Action - The next thing a host must do. One
TurnActionmaps to one durable activity. - Turn
Operation - External work requested by one prepared engine step.
- Turn
Outcome - How a turn ended. Mirrors everruns’
TurnOutcome(Success/Failed/MaxIterations/Sealed) —Cancelledis the agentyk analogue of a caller-driven seal viacrate::cancellation::CancellationToken;Sealedis a host- or budget-driven one. - Turn
Phase - Current phase of the turn.
PendingActcarries the whole batch from the triggering reason step so a resumed host — sequential or parallel — knows exactly what remains.
Traits§
- Budget
Checker - Decides whether a turn may keep going.
- Capability
- A bundle of behavior attached to an agent: prompt text, tools, and slash commands.
- Chat
Driver - One provider protocol. Implementations translate
ChatRequestto the provider’s wire format and back. - Context
Assembler - Decides what a turn actually sends to the model.
- Delta
Sink - Receives incremental text as a
ChatDriverstreams a completion.accumulatedis the full text so far, includingdelta— the executor forwards each call to the engine host’s event recorder as an ephemeraloutput.message.deltaevent. - Event
Listener - Observes events after they are emitted. Attach listeners via
AgentBuilder::listener. Receives both durable and ephemeral events — checkEvent::sequence(Nonefor ephemeral) to distinguish. - Event
Log - Compatibility name for
EventStore. Append-only, per-session-sequenced event storage. - Event
Store - Append-only, per-session-sequenced event storage.
- Hook
- One user hook attached by value to an agent.
- Model
Catalog - Where a host’s knowledge about models lives.
- Snapshot
Store - Optional storage for disposable replay accelerators.
- Tool
- A function the model can call.
- Tool
Progress Sink - Where a running tool’s progress reports go.
- Turn
Middleware - Intercepts points in a turn. Every method has a default, so an implementation only writes the ones it cares about.
Functions§
- after_
tool_ chain - Run the
after_toolchain in order, threading each middleware’s output into the next. - before_
tool_ chain - Run the
before_toolchain in order: aToolCallDecision::Rewritefeeds the next middleware (and ultimately the execution), and the firstToolCallDecision::Denyshort-circuits. - messages_
from_ events - Rebuild message history from a session’s events — shorthand for
History::from_eventswhen you only want the messages. - notify_
event_ listeners - Notify listeners in order, honoring their event filters and isolating panics.
Type Aliases§
- EventId
- A
event_-prefixed identifier. Generated by the library, readable on demand, never something you must mint. - Message
Id - A
msg_-prefixed identifier. Generated by the library, readable on demand, never something you must mint. - Result
Resultwith this crate’sError.- Session
Id - A
session_-prefixed identifier. Generated by the library, readable on demand, never something you must mint. - TurnId
- A
turn_-prefixed identifier. Generated by the library, readable on demand, never something you must mint.