Skip to main content

Crate agentyk

Crate agentyk 

Source
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;fs
pub use filesystem::FileStat;fs
pub use filesystem::FileSystem;fs
pub use filesystem::FileSystemCapability;fs
pub use filesystem::InMemoryFileSystem;fs
pub use filesystem::RealDiskFileSystem;fs
pub use filesystem::WriteBlocklistFileSystem;fs
pub use hooks::ShellHook;hooks
pub use jsonl_log::JsonlEventLog;
pub use mcp::oauth::McpOAuthLoginOptions;mcp-oauth
pub use mcp::oauth::McpOAuthTokenProvider;mcp-oauth
pub use mcp::oauth::McpOAuthTokenSet;mcp-oauth
pub use mcp::oauth::PreparedMcpOAuthLogin;mcp-oauth
pub use mcp::oauth::prepare_mcp_oauth_login;mcp-oauth
pub use mcp::oauth::refresh_mcp_oauth_tokens;mcp-oauth
pub use mcp::McpAuthProvider;mcp
pub use mcp::McpCapability;mcp
pub use mcp::McpClient;mcp
pub use mcp::McpProtocolMode;mcp
pub use mcp::McpServer;mcp
pub use mcp::McpServerDiscovery;mcp
pub use mcp::McpTransport;mcp
pub use mcp::StaticBearer;mcp
pub use drivers::anthropic::AnthropicDriver;http
pub 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::TurnState transitions.
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::ChatDriver implementations.
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_type and on disk.
extensions
A typed extension bag — axum’s Extensions pattern, so crate::tool::ToolContext can 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 (no SessionFileSystem, no credential store type, nothing DB- or server-shaped in this crate).
filesystemfs
File system access as a bundled capability.
hook
User hooks at stable agent lifecycle boundaries.
hookshooks
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 Event per line — the batteries-included durability option (the yolop pattern).
mcpmcp
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).
AgentBuilder
Fluent, by-value agent composition.
AgentDefinition
Agent behavior, separate from the resources that run it.
AgentEnvironment
Host resources used to execute an AgentDefinition.
CancellationToken
A cancellation signal shared between a caller and a running turn.
ChatRequest
One LLM completion request: everything a driver needs to produce the next assistant message.
ChatResponse
What one completion produced.
CommandContext
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 no turn_id — only a session.
CommandDescriptor
One slash-command a capability exposes — everruns’ CommandDescriptor, pared down to what a host needs to list and invoke it.
CompositeEventListener
Listener that forwards each event to an ordered collection of listeners.
ContextAssembly
Model messages plus the accounting and provenance behind them.
ContextEvent
Durable observational event produced while assembling context.
ContextRequest
Everything a context policy needs to shape one model request.
ContextSource
Provenance for one contribution to assembled model context.
DriverId
Names a provider protocol implementation, e.g. "openai", "anthropic", "llmsim". An open string (not a closed enum) so embedders can register their own drivers.
DriverRegistry
Routes a ModelSpec to the ChatDriver that speaks its protocol.
Event
A fully-recorded event. id and ts are always assigned on emission; sequence is Some (contiguous per session, starting at 1) for durable events and None for ephemeral ones — see EventData::is_ephemeral.
EventPage
One bounded event read plus cursors needed to continue consistently.
EventRange
Bounded forward read over one session timeline.
EventRequest
An event about to be emitted — same shape as Event minus the fields assigned on emission.
Extensions
Type-keyed bag of Arc<T> values, one per type. Cheap to clone (each entry is an Arc).
ExternalActor
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.
HookContext
Session and optional turn identity supplied to a hook.
HookMatcher
Restricted matcher for tool hook events.
HookPayload
Structured input delivered to one hook invocation.
HookRejection
A block decision returned by a prompt hook.
ImageContentPart
Image content, as a URL or inline base64 data (mirrors everruns’ ImageContentPart).
InMemoryEventLog
In-memory event log. The default for Agent::session() and the natural choice for tests.
InMemoryModelCatalog
A catalog built from entries you supply — the straightforward implementation, for hosts whose model knowledge is a literal list.
InMemorySnapshotStore
In-memory snapshot storage for tests and short-lived applications.
InProcessExecutor
Executes every operation from TurnEngine immediately in the caller’s async task.
InputQueue
Messages waiting to join a turn already in progress. Cheap to clone; every clone shares one queue.
Message
One message in a conversation.
ModelProfile
What one model supports. Every field is optional knowledge: None means “not stated”, never “not supported”, so a partial catalog entry can still be useful.
ModelSpec
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.
NoopEventListener
Listener that intentionally ignores every event.
PassthroughContextAssembler
Sends the full history unchanged — the default.
PreparedStep
One engine decision: persist events, then execute operation.
PreparedToolCall
One call in a prepared tool batch.
PreparedTurnStart
Canonical effects of opening a turn, before any model work is scheduled.
ProjectionSnapshot
Disposable projection anchored to an immutable session point.
ReasoningConfig
Reasoning/thinking configuration for models that support it. Mirrors everruns’ ReasoningConfig.
RunOptions
Everything one Session::run_with_options call can override. Defaults (RunOptions::default()) reproduce plain Session::run: an uncancellable turn on the agent’s default model.
Session
A conversation with an agent.
SessionPoint
Immutable address of a durable point in a session timeline.
SessionView
Read-only projection of a session at an immutable historical point.
SystemPromptContext
Context available while assembling the system prompt.
TextContentPart
Text content.
ToolCall
A tool invocation requested by the model.
ToolContext
Execution-time context handed to a tool.
ToolDefinition
What the model sees: name, description, and a JSON-schema for arguments.
ToolInvocation
One tool call about to run (or just finished), with everything a middleware needs to judge it.
ToolOutput
The result of executing a tool.
ToolPolicy
Host-side policy about a tool — how it is offered, not what it does.
ToolProgress
One progress report from a tool that is still running.
TurnControls
Per-turn overrides, applied on top of the agent’s default model.
TurnEngine
The single interpreter of Agentyk turn semantics.
TurnHost
Agent composition plus the session-specific resources for one turn.
TurnResult
The outcome of one executed turn.
TurnState
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§

BudgetDecision
Whether a turn may take its next action.
ContentPart
A part of message content: text or an image. Tool calls and tool results stay as dedicated Message fields rather than content-part variants — a deliberate simplification over everruns’ unified content-part model.
DeferrablePolicy
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.
EventData
The payload of an Event — what actually happened.
ExpectedVersion
Required stream version when appending a durable event batch.
HookErrorPolicy
Policy applied when a hook returns HookOutcome::Error.
HookEvent
A stable lifecycle point at which a user hook can run.
HookOutcome
What a hook asks the engine to do.
LlmErrorKind
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 Message came from.
SealReason
Why a turn was deliberately sealed rather than left to run to MaxIterations or fail. Mirrors everruns’ SealReason.
ToolCallDecision
What a middleware decides about a tool call it is shown.
ToolChainOutcome
The resolution of a whole TurnMiddleware::before_tool chain.
TurnAction
The next thing a host must do. One TurnAction maps to one durable activity.
TurnOperation
External work requested by one prepared engine step.
TurnOutcome
How a turn ended. Mirrors everruns’ TurnOutcome (Success/Failed/MaxIterations/Sealed) — Cancelled is the agentyk analogue of a caller-driven seal via crate::cancellation::CancellationToken; Sealed is a host- or budget-driven one.
TurnPhase
Current phase of the turn. PendingAct carries the whole batch from the triggering reason step so a resumed host — sequential or parallel — knows exactly what remains.

Traits§

BudgetChecker
Decides whether a turn may keep going.
Capability
A bundle of behavior attached to an agent: prompt text, tools, and slash commands.
ChatDriver
One provider protocol. Implementations translate ChatRequest to the provider’s wire format and back.
ContextAssembler
Decides what a turn actually sends to the model.
DeltaSink
Receives incremental text as a ChatDriver streams a completion. accumulated is the full text so far, including delta — the executor forwards each call to the engine host’s event recorder as an ephemeral output.message.delta event.
EventListener
Observes events after they are emitted. Attach listeners via AgentBuilder::listener. Receives both durable and ephemeral events — check Event::sequence (None for ephemeral) to distinguish.
EventLog
Compatibility name for EventStore. Append-only, per-session-sequenced event storage.
EventStore
Append-only, per-session-sequenced event storage.
Hook
One user hook attached by value to an agent.
ModelCatalog
Where a host’s knowledge about models lives.
SnapshotStore
Optional storage for disposable replay accelerators.
Tool
A function the model can call.
ToolProgressSink
Where a running tool’s progress reports go.
TurnMiddleware
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_tool chain in order, threading each middleware’s output into the next.
before_tool_chain
Run the before_tool chain in order: a ToolCallDecision::Rewrite feeds the next middleware (and ultimately the execution), and the first ToolCallDecision::Deny short-circuits.
messages_from_events
Rebuild message history from a session’s events — shorthand for History::from_events when 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.
MessageId
A msg_-prefixed identifier. Generated by the library, readable on demand, never something you must mint.
Result
Result with this crate’s Error.
SessionId
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.