Skip to main content

Crate entelix

Crate entelix 

Source
Expand description

§entelix

Web-service-native Rust agentic AI SDK — LangChain + LangGraph parity, Anthropic managed-agent shape, production-grade observability. This crate is the facade: it re-exports the sub-crates behind feature flags (see Cargo.toml).

Surface includes the composition spine (Runnable, .pipe()), prompt primitives (PromptTemplate, ChatPromptTemplate, MessagesPlaceholder), the IR (ir), every codec (codecs::AnthropicMessagesCodec and siblings), transports (DirectTransport plus optional cloud transports under feature flags), the ChatModel bundle (ChatModel), the Tool hand contract, and optional sub-crates for memory, persistence, MCP, policy, observability, the HTTP server, and agent recipes.

Architectural canon: see CLAUDE.md (22 invariants + naming taxonomy) and docs/architecture/principles.md.

Modules§

auth
Credential resolution for transports.
cancellation
Cancellation primitive for entelix.
codecs
Provider codecs (invariant 4).
events
EventBus — ephemeral broadcast pub-sub for SDK observability.
ir
Provider-neutral intermediate representation (invariant 4).
prelude
Common imports for typical SDK usage.
sandbox
Sandbox — sandbox-agnostic isolated execution environment.
service
tower::Service spine for entelix model + tool calls.
skills
Skills — packaged, progressively-disclosed agent capabilities .
stream
StreamAggregator — accumulates streaming model deltas into a coherent ModelResponse.
tools
The Hand surface — Tool trait + ToolRegistry (layered tower::Service dispatch path) + ToolDispatchScope / ScopedToolLayer (operator hook for ambient request-scope state, e.g. tokio task-locals seeding RLS settings).
transports
Stateful HTTP carriers — Transport trait + concrete impls — and the RetryLayer middleware that wraps any retry-classified Service.

Structs§

ActivateSkillTool
T1 → T2 transition — load one skill’s full instructions and the list of resource keys it exposes. Resource bytes are not included; they are read separately via ReadSkillResourceTool.
AdvisoryKeypostgres or redis
64-bit hashed key used for distributed lock derivation.
Agent
Production agent runtime.
AgentBuilder
Fluent builder for Agent<S>.
AgentContext
Per-run carrier of infra context + typed operator-side dependencies. D defaults to () so deps-less agents pay no type-system tax.
AgentEntry
One named sub-agent in a create_supervisor_agent graph.
AgentRouterBuilderserver
Fluent builder that produces an axum::Router mounted at /v1.
AgentRunResult
Terminal artifact of one agent run.
AlwaysApprove
Always returns Approve — useful as the supervised-mode default when an operator wants the supervised event sequence (ToolCallApprovedToolStart) but no actual gating logic.
Annotated
Newtype that bundles a value T with the reducer R that should merge it. The wrapper is a standalone helper users compose into their state types; it does not hook into StateGraph::add_node directly.
Append
Append: current followed by update. Specialised for Vec<U> where U: Clone + Send + Sync + 'static.
ApprovalLayer
tower::Layer<S> that gates a Service<ToolInvocation, Response = Value, Error = Error> through an Approver. Construct via ApprovalLayer::new; attach to a ToolRegistry via entelix_core::tools::ToolRegistry::layer.
ApprovalRequest
Read-only context the Approver sees for each decision.
ApprovalService
tower::Service<ToolInvocation> produced by ApprovalLayer. Public so operators that wire dispatch paths manually can compose it directly.
AuditSinkHandle
Arc-shaped handle the crate::context::ExecutionContext extension carries. Wraps Arc<dyn AuditSink> in a newtype so the Extensions slot lookup by TypeId is unambiguous.
BedrockCredentialProvideraws
Chain-aware credential provider for crate::bedrock::BedrockTransport.
BedrockSigneraws
Stateless SigV4 signer for Bedrock requests.
BedrockTransportaws
AWS Bedrock Runtime transport.
BedrockTransportBuilderaws
Fluent builder for BedrockTransport.
BroadcastSink
Multi-consumer broadcast sink. Each subscriber gets its own Receiver; slow consumers receive Lagged errors but the agent never blocks. Suitable for SSE fan-out + OTel exporter
Budgetpolicy
Per-tenant cumulative spend ceiling. Compared against CostMeter::spent_by(tenant) at pre-request time.
BufferMemory
Bounded conversation buffer.
ByteCountTokenCounter
Zero-dependency conservative counter — bytes.div_ceil(4).
CachedTokenProvider
Cache + single-flight wrapper around a TokenRefresher.
Calculator
calculator tool — generated from calculator by #[tool]. Register via [SchemaToolExt::into_adapter].
CalculatorInput
Typed input for the Calculator tool.
CalculatorOutput
Typed output of calculator — surfaces both the original expression (for round-trip diagnostics) and the evaluated f64.
CaptureSink
In-memory capture sink for integration tests. Every emitted event is appended to an Arc<Mutex<Vec<_>>>; tests inspect the vector to assert ordering and content.
ChannelApprover
Production-shape approver backed by an mpsc channel.
ChannelApproverConfig
Configurable timeout for waiting on operator decisions.
ChannelSink
Single-consumer mpsc sink. Construct via Self::new — the caller keeps the tokio::sync::mpsc::Receiver for downstream consumption (HTTP SSE driver, file logger, etc.).
ChatFewShotPromptTemplate
Chat-shape few-shot prompt.
ChatModel
Configurable chat model — codec + transport + layer stack.
ChatModelConfig
Builder-side configuration that flows into every ModelRequest the ChatModel issues. Stored separately from the leaf service so layers / streaming / future surfaces share one source of truth.
ChatModelSamplingProvidermcp-chatmodel
Adapter from SamplingProvider to entelix_core::ChatModel<C, T>. Cheap to clone — the underlying chat model is Arc-backed.
ChatPromptTemplate
Heterogeneous list of templated messages and placeholders. Renders to Vec<Message> — the input type expected by entelix_core::ChatModel.
ChatState
State for crate::create_chat_agent and the simplest single-turn recipes — just the conversation so far.
Checkpoint
One snapshot of graph progress for a particular (tenant_id, thread_id). next_node = None indicates the graph terminated cleanly (a finish point ran or a conditional edge routed to END).
CheckpointId
Stable identifier for a checkpoint. Backed by UUID v7 — time-ordered and globally unique across processes.
CompactedHistory
Compacted view over a SessionGraph’s event log.
CompiledGraph
Frozen graph ready to execute.
ConditionalEdge
One conditional-edge dispatch.
Configured
Runnable<I, O> adapter that runs configurer on a cloned ExecutionContext before forwarding to the inner. The original ctx the parent passed in is left untouched.
ConsolidatingBufferMemory
Layered memory: a BufferMemory for recent turns, a SummaryMemory for the running summary, and a Summarizer that bridges the two when the buffer’s policy fires.
ConsolidationContext
Inputs that a ConsolidationPolicy consults when deciding whether to consolidate. Carries the buffer plus optional signals (last-consolidated-at, current/available context tokens) so non-trivial policies — for example, “summarise once we use 80 % of the model’s context window” or “throttle consolidation to at most once per hour” — can express their decision without embedding their own clock or token counter.
ContextualChunker
Anthropic Contextual Retrieval chunker. Each chunk’s content is rewritten as <contextual prefix>\n\n<original chunk> where <contextual prefix> is a model-generated 50-100 token summary of how the chunk relates to its parent document.
ContextualChunkerBuilder
Builder for ContextualChunker. Construct via ContextualChunker::builder; chain config setters; finalise with Self::build.
ContributingNodeAdapter
Runnable<S, S> adapter that snapshots the inbound state, runs an inner Runnable<S, S::Contribution> to produce only the slots the node touched, and folds that contribution into the snapshot via S::merge_contribution.
CorrectiveRagState
State the corrective-RAG graph drives across nodes. Carries the original + current query, the rewrite history, the last retrieval batch + verdicts, the surviving correct subset, and the terminal answer.
CostCalculatorAdapter
Adapter that bridges any CostCalculator (ChatModel pricing source) into the EmbeddingCostCalculator surface.
CostMeterpolicy
Per-tenant cost ledger. Records the cumulative spend for every tenant that has ever been charged.
CragConfig
Operator-tunable knobs for the corrective-RAG recipe. Construct via Self::new or Self::default; chain with_* setters.
Document
The unit a RAG pipeline moves around — content plus everything downstream needs to know about where it came from.
DocumentId
Stable identifier for a Document within its Namespace. Loaders mint these from the source’s natural id (S3 object key, Notion page id, file path); splitters derive child ids by suffixing the parent id with :<chunk_index>.
DroppingSink
No-op sink — the agent runs to completion without surfacing per-event telemetry. Default when no sink is configured.
EdgeId
Stable, opaque edge identifier minted by the backend.
ElicitationRequestmcp
Elicitation request as it arrives from the server. Both fields ride straight from the JSON-RPC params block.
Embedding
One embedded text’s vector plus optional usage metadata.
EmbeddingRetriever
Adapter that combines an Embedder and a VectorStore (scoped to one Namespace) into a Retriever.
EmbeddingUsage
Token-accounting metadata an Embedder reports alongside the computed vector. Mirrors the ChatModel Usage shape so cost meters can charge embedding calls with the same machinery they use for completions.
EntityMemory
Map of entity_name → EntityRecord keyed by namespace.
EntityRecord
One entity’s recorded fact plus provenance metadata.
Episode
One time-stamped episode of operator-shaped payload.
EpisodeId
Stable identifier for one episode. Backed by UUID v7 so two ids minted in order compare in the same order — the audit trail and external correlation paths stay consistent without a separate sequence column.
EpisodicMemory
Time-ordered append-only episode store keyed by Namespace.
ErrorEnvelope
Typed wire shape of an Error — the canonical inspector at sink / SSE / audit boundaries. Built by Error::envelope; never constructed externally so the field set evolves under the same patch-version-stability guarantee as wire_code itself.
ExecutionContext
Carrier for request-scope state that every Runnable, Tool, and codec sees.
Extensions
Type-keyed cross-cutting state attached to an crate::ExecutionContext. Operators add their own values via crate::ExecutionContext::add_extension and read them back via crate::ExecutionContext::extension.
FailOpenSink
Composition adapter that swallows the inner sink’s errors and always returns Ok(()).
Fallback
Runnable<I, O> adapter that falls back through a list of alternatives when the primary returns a classifier-approved transient error.
FanOutSink
Callback-shaped fan-out — every emitted event reaches every inner sink in registration order.
FewShotPromptTemplate
String-shape few-shot prompt.
FixedExampleSelector
Returns the configured examples verbatim, regardless of input.
FoundryCredentialProviderazure
Azure-credential-backed refresher. Generic over any Arc<dyn TokenCredential> — the caller picks the chain.
FoundryTransportazure
Azure AI Foundry HTTP transport.
FoundryTransportBuilderazure
Fluent builder for FoundryTransport.
GenAiMetricsotel
Pre-built per-call instrument set.
GraphHop
One traversal hop produced by GraphMemory::traverse or GraphMemory::find_path.
HeadDropCompactor
Reference compactor: drop oldest turns until the rendered character count fits under budget_chars. Tool round-trips stay paired by construction; the strategy never partially includes a turn.
HfTokenCountertokenizer-hf
TokenCounter backed by a HuggingFace Tokenizer.
HostAllowlist
Host allowlist. Fail-closed: empty allowlist rejects everything.
HttpFetchTool
HTTP fetch Tool for agentic workflows.
HttpFetchToolBuilder
Builder for HttpFetchTool.
HttpMcpClientmcp
Production McpClient — JSON-RPC 2.0 over MCP streamable-http.
IdentityReranker
No-op Reranker: returns the first top_k candidates in the order the underlying VectorStore produced them, copying the retrieval score into RerankedDocument::rerank_score so downstream consumers see a uniform shape.
InMemoryCheckpointer
In-process checkpointer backed by a HashMap<(tenant_id, thread_id), Vec<Checkpoint>>. The composite key encodes Invariant 11 (multi-tenant isolation): the same thread_id under two tenants resolves to two distinct histories.
InMemoryGraphMemory
In-process GraphMemory backed by BTreeMap adjacency lists, sharded per namespace.
InMemorySessionLog
In-process SessionLog for single-binary deployments and tests.
InMemorySkill
Skill whose body lives in struct fields. Construct via InMemorySkillBuilder.
InMemorySkillBuilder
Fluent builder for InMemorySkill.
InMemoryStore
In-process Store<V> backed by a HashMap keyed by (rendered_namespace, key). Cheap to clone — internal state is Arc<Mutex<...>>-shared.
InMemoryVectorStore
In-process VectorStore backed by a per-namespace Vec<Slot>.
IngestError
One per-document failure recorded during ingestion. Carries the originating document id (when known) and a stage label identifying which pipeline phase failed.
IngestReport
Outcome counters and per-document failure list a single IngestionPipeline::run produces.
IngestionPipeline
End-to-end RAG ingestion pipeline. Construct via Self::builder; finalise with IngestionPipelineBuilder::build; drive with Self::run.
IngestionPipelineBuilder
Builder for IngestionPipeline. Required components (loader / splitter / embedder / store) come in via IngestionPipeline::builder; optional Chunker entries accumulate via Self::add_chunker.
JsonOutputParser
Parses an assistant Message as JSON into T.
LengthBasedExampleSelector
Selector that caps the rendered example total at a character budget.
Lineage
Split-history — survives every transformation. A leaf chunk’s Lineage describes which parent it came from, which split produced it, and which chunkers ran over it. Audit / debug flows reconstruct the path from a retrieval hit back to the ingestion source by walking the lineage chain (parent_id → loader’s source URI).
ListSkillsTool
T1 listing — returns [{name, description, version}, ...] for every skill registered in the bound SkillRegistry.
LlmFacingSchema
JSON-Schema sanitiser — strips schemars / draft-meta keys that vendor APIs ignore but that still cost tokens to ship.
LlmQueryRewriter
Reference LLM-driven QueryRewriter. Asks the supplied Runnable<Vec<Message>, Message> model for a corrected query, then trims surrounding whitespace and quote marks.
LlmQueryRewriterBuilder
Builder for LlmQueryRewriter.
LlmRetrievalGrader
Reference LLM-driven RetrievalGrader. Asks the supplied Runnable<Vec<Message>, Message> model to classify relevance, then parses the reply into a GradeVerdict. Operators inheriting from this default tune the prompt via LlmRetrievalGraderBuilder::with_instruction or write their own grader from scratch.
LlmRetrievalGraderBuilder
Builder for LlmRetrievalGrader.
LockGuardpostgres or redis
Owned proof that the holder currently has exclusive access to a key.
Mapping
Runnable<I, P> adapter applying a pure synchronous function to the inner’s output.
MarkdownStructureSplitter
Heading-aware markdown splitter.
Max
Keep the larger of current / update per T: Ord. Useful for “highest score wins” reducers and usize step counters merged across parallel branches.
McpCompletionArgumentmcp
Argument being completed.
McpCompletionResultmcp
Response to a completion/complete.
McpManagermcp
Per-tenant pool of McpClient instances.
McpManagerBuildermcp
Builder for McpManager. Records configurations only — no I/O, no connection attempts.
McpPromptmcp
One prompt template published by an MCP server.
McpPromptArgumentmcp
One argument expected by a prompt.
McpPromptInvocationmcp
Result of a prompts/get invocation — a description plus an ordered transcript of messages the agent should add to its context.
McpPromptMessagemcp
One message in a prompts/get transcript.
McpPromptResourceRefmcp
Resource block embedded inside a McpPromptContent::Resource.
McpResourcemcp
One resource published by an MCP server.
McpRootmcp
One workspace / filesystem root the client exposes to the server.
McpServerConfigmcp
Connection details for one MCP server.
McpToolAdaptermcp
Adapter that exposes one MCP tool through the entelix Tool trait.
McpToolDefinitionmcp
One tool published by an MCP server.
MergeMap
Merge two HashMap<K, V>s, right-biased — entries from update overwrite collisions in current. (Right-bias matches typical LangGraph / dict-update semantics.)
MergeNodeAdapter
Runnable<S, S> that runs an inner Runnable<S, U> and merges the resulting U back into a fresh copy of the inbound S via the supplied closure.
MessagesPlaceholder
Placeholder whose value at render time is a Vec<Message> (typically chat history).
MeteredEmbedder
Embedder decorator that emits OTel-compatible telemetry per call (and optional cost via EmbeddingCostCalculator).
MmrReranker
Maximal Marginal Relevance reranker.
ModelHintmcp
One model hint (a name string the server suggests).
ModelPreferencesmcp
Operator hints + priorities the server passes to bias model selection. All fields optional — the provider chooses how to honour them (or ignores them entirely).
ModelPricingpolicy
Per-model pricing, in cost units per 1000 tokens. The unit is caller-defined (USD cents, GBP pence, internal credits) — the meter is unit-blind and just sums Decimals.
Namespace
Hierarchical key prefix for memory operations.
NamespacePrefix
Hierarchical prefix used by crate::Store::list_namespaces.
NeverConsolidate
Never trigger. Useful as a default when consolidation is wired but the operator wants to disable it temporarily without rebuilding the agent graph.
NodeId
Stable, opaque node identifier minted by the backend.
OnMessageCount
Trigger consolidation once the buffer reaches max_messages.
OnTokenBudget
Trigger consolidation when the buffer’s total text length (summed UTF-8 byte length of every ContentPart::Text) exceeds max_bytes. Approximates a token-budget gate without needing a tokenizer in the SDK.
OpenAiEmbedderembedders-openai
Concrete Embedder backed by OpenAI’s /v1/embeddings HTTPS endpoint. Stateless beyond the connection pool inside reqwest::Client; clone freely or wrap in Arc per F10.
OpenAiEmbedderBuilderembedders-openai
Builder for OpenAiEmbedder.
OtelLayerotel
Layer that emits GenAI semconv events around the wrapped service. Cloning is cheap (Arcs internally).
OtelServiceotel
Service produced by OtelLayer. Specialised Service<ModelInvocation> and Service<ToolInvocation> impls below.
PendingApproval
One in-flight approval — the operator side. Read these from the Receiver paired with ChannelApprover; resolve by sending an ApprovalDecision on the embedded reply.
PendingApprovalDecisions
Resume-side mapping from tool_use_id to the operator’s decision. Attached to ExecutionContext::extension so the agent’s approval layer reads the decision during a re-fired dispatch and short-circuits the approver for any tool_use_id whose decision is present.
PgGraphMemorygraphmemory-pg
Postgres-backed GraphMemory<N, E>.
PgGraphMemoryBuildergraphmemory-pg
Fluent builder for PgGraphMemory. Use PgGraphMemory::builder.
PgVectorStorevectorstores-pgvector
Concrete VectorStore backed by Postgres + pgvector.
PgVectorStoreBuildervectorstores-pgvector
Builder for PgVectorStore.
PiiPatternpolicy
One named redaction pattern.
PolicyExtras
Optional signals fed into BufferMemory::should_consolidate_with. Operators that don’t track tokens or last-consolidated time can pass Self::default and the policy will see the buffer plus whatever the buffer itself tracks via BufferMemory::mark_consolidated.
PolicyLayerpolicy
Layer that wraps an inner service with per-tenant policy enforcement.
PolicyRegistrypolicy
Runtime registry mapping tenant_idTenantPolicy.
PolicyServicepolicy
Service produced by PolicyLayer. Generic over the inner service type; specialised Service<ModelInvocation> and Service<ToolInvocation> impls below.
PostgresCheckpointerpostgres
Postgres-backed Checkpointer<S>.
PostgresLockpostgres
Postgres-backed distributed lock.
PostgresPersistencepostgres
Postgres-backed persistence bundle. Cheap to clone — the pool is reference-counted internally.
PostgresPersistenceBuilderpostgres
Fluent builder for PostgresPersistence. Use PostgresPersistence::builder().
PostgresSessionLogpostgres
Postgres-backed SessionLog.
PostgresStorepostgres
Postgres-backed Store<V>.
PricingTablepolicy
Lookup of model name → ModelPricing. Keys are the same model strings the codecs send to the wire (e.g. "claude-opus-4-7", "gpt-4.1"). Lookup is exact; aliases are the caller’s responsibility.
PromptTemplate
A Jinja2-syntax template that renders to String from a variables map.
PutOptions
Per-write knobs the operator may attach when calling Store::put_with_options. Default::default() corresponds to the simple Store::put path: no TTL, no extra metadata.
QdrantVectorStorevectorstores-qdrant
Concrete VectorStore backed by a single qdrant collection.
QdrantVectorStoreBuildervectorstores-qdrant
Builder for QdrantVectorStore.
QuotaLimiterpolicy
Composite quota gate.
ReActAgentBuilder
Fluent builder for a ReAct-style Agent<ReActState>.
ReActState
State for crate::create_react_agent — messages plus a step count to make traces easier to inspect.
ReadSkillResourceTool
T2 → T3 transition — read one resource from one skill.
RecursiveCharacterSplitter
Recursive character-budget splitter.
RedisCheckpointerredis
Redis-backed Checkpointer<S>.
RedisLockredis
Redis-backed distributed lock.
RedisPersistenceredis
Redis-backed persistence bundle. Cheap to clone — the connection manager is reference-counted internally.
RedisPersistenceBuilderredis
Fluent builder for RedisPersistence.
RedisSessionLogredis
Redis-backed SessionLog.
RedisStoreredis
Redis-backed Store<V>.
RegexRedactorpolicy
Regex-driven PII redactor.
RenderedForLlm
Sealed carrier for a model-facing value of type T. Constructed only by LlmRenderable::for_llm’s default impl — the constructor is pub(crate), so an external crate that implements LlmRenderable<T> for its own type can override render_for_llm (the raw producer) but cannot override for_llm (the carrier-producing wrapper) because it has no way to reach RenderedForLlm::new. Emit sites that accept RenderedForLlm<T> therefore receive a value that structurally must have come through the trait funnel.
Replace
Last-write-wins. Matches the current StateGraph default — included so users who explicitly opt into reducer machinery have a no-op option.
RequestOverrides
ModelRequest-shaped sampling overrides — temperature, top-p, max tokens, stop sequences, reasoning effort, tool choice, response format. Patched onto the call’s crate::context::ExecutionContext via add_extension.
RerankedDocument
One reranked document paired with the score the Reranker assigned.
RetrievalQuery
Declarative description of one retrieval call.
RetrievedDocument
One retrieved document with optional similarity score.
Retrying
Runnable<I, O> adapter applying a RetryPolicy to the inner runnable on every invocation.
RunBudget
Six-axis usage cap shared across one logical run (parent agent + every sub-agent it dispatches). Cloning the budget — done implicitly per ExecutionContext clone — bumps the internal Arc refcount; sub-agent calls accumulate into the same counters as the parent’s.
RunOverrides
Agent-loop overrides — model identifier, system prompt, recursion cap. Patched onto the call’s crate::context::ExecutionContext via add_extension.
RunnableCompacting
Runnable<Vec<Message>, Message> wrapper that compacts the input message slice through an operator-supplied Compactor when the total character count meets or exceeds threshold_chars. Below the threshold the wrapper is a no-op delegate — the inner runnable receives the original Vec<Message> unchanged.
RunnableLambda
Runnable<I, O> backed by a user-supplied async closure.
RunnableParallel
Runnable<I, HashMap<String, O>> that runs every registered branch in parallel against the same input.
RunnablePassthrough
Runnable<T, T> that returns its input unchanged.
RunnableRouter
Runnable<I, O> that picks one of several runnables based on a predicate over the input.
RunnableSequence
Two Runnables composed end-to-end. RunnableSequence<I, M, O> reads “input I → middle M → output O”. Created with .pipe().
RunnableToSummarizerAdapter
Summarizer that delegates to any Runnable<Vec<Message>, Message> — the same shape as a chat model. Prepends a configurable system instruction so the model understands the task even when the buffer itself contains only raw user/assistant turns.
SamplingMessagemcp
One conversation message in a sampling request.
SamplingRequestmcp
Sampling request as it arrives from the server. Mirrors the spec’s sampling/createMessage params block.
SamplingResponsemcp
Sampling response the client sends back. Mirrors the spec’s sampling/createMessage result block.
SchemaToolAdapter
Adapter that exposes any SchemaTool through the erased Tool trait.
SearchResult
One search hit.
SearchTool
Tool wrapper around a SearchProvider.
SemanticMemory
Embedder + VectorStore + Namespace bundle.
SendEdge
Parallel fan-out edge.
SessionAuditSink
Adapter that fans AuditSink::record_* calls into a durable SessionLog.
SessionGraph
Append-only event log for a single conversation thread.
SessionSchemaVersionpostgres or redis
Schema version tag for persisted payloads.
Source
Where a Document originated. Survives every split and chunker pass — the leaf chunk knows the source URI of the parent document and which loader produced it.
SsrfSafeDnsResolver
reqwest::dns::Resolve impl that vets every resolved IP against is_ssrf_blocked before handing addresses back to the HTTP connector. See module docs for the threat model.
StateErasureSink
Adapter that erases an agent’s state type so a single AgentEventSink<()> can fan in from heterogeneous agents (Agent<ReActState>, Agent<SupervisorState>, operator-defined state types) in a multi-agent system.
StateGraph
Builder for a state-machine graph parameterised over its state type S.
StaticElicitationProvidermcp
In-memory ElicitationProvider returning a fixed response.
StaticResource
SkillResource whose payload lives in a struct field — the natural shape for embedded resources and tests.
StaticRootsProvidermcp
In-memory RootsProvider holding a fixed slice of roots.
StaticSamplingProvidermcp
In-memory SamplingProvider returning a fixed response.
StructuredOutputAdapter
Adapts a ChatModel<C, T> to Runnable<Vec<Message>, O> by routing every invoke through ChatModel::complete_typed::<O>.
Subagent
A bounded brain↔hand pairing.
SubagentBuilder
Builder for Subagent. Construct via Subagent::builder(model, &parent_registry).
SubagentMetadata
Compact metadata snapshot of a Subagent for parent-side inspection — the LLM-facing identity (name, description) plus the tool surface bound at construction. Operators that list available sub-agents in a parent agent’s system prompt reach for this struct rather than calling each accessor individually.
SubagentTool
Wrapper exposing a crate::agent::Agent as a Tool. Built via Subagent::into_tool.
SummaryCompactor
LLM-summary Compactor — drops the oldest turns past keep_recent_turns into a single summarised Turn::User, leaving the most recent turns verbatim.
SummaryMemory
Single-string summary keyed by Namespace.
SupervisorState
State for crate::create_supervisor_agent — messages plus the last-active sub-agent identifier for traceability.
SystemClock
Clock backed by tokio::time::Instant. Honours tokio::time::pause so test harnesses can simulate elapsed time without real waits.
TenantId
Validating wrapper around the per-tenant scope identifier.
TenantPolicypolicy
Per-tenant aggregate of policy handles.
ThreadKey
Canonical addressing tuple for every tenant-scoped persistence operation — (tenant_id, thread_id). Encodes Invariant 11 (multi-tenant isolation) at the type level so impls cannot accidentally drop the tenant scope. The tenant_id carries the validating TenantId newtype, so a ThreadKey whose serde payload arrived with an empty tenant is rejected at deserialize time rather than constructed and then silently mis-routed.
TiktokenCountertokenizer-tiktoken
TokenCounter impl backed by tiktoken-rs.
Timed
Runnable<I, O> adapter that aborts the inner with Error::DeadlineExceeded if it does not complete within timeout.
TokenBucketLimiterpolicy
Per-key token-bucket limiter. Buckets are created lazily on first try_acquire; a key never seen before starts full.
TokenCountSplitter
Recursive token-budget splitter.
TokenCounterRegistry
Routing table from (provider, model) pairs to a vendor-accurate TokenCounter.
TokenSnapshot
One refresh result.
ToolApprovalEventSinkHandle
Refcounted handle for ToolApprovalEventSink. Stored in entelix_core::ExecutionContext extensions so ApprovalLayer finds the sink without taking it as a constructor argument.
ToolEventLayer
Layer that emits per-tool AgentEvent variants to the configured sink.
ToolEventService
Service produced by ToolEventLayer. Generic over the inner service so the layer composes with any tower-stacked tool path.
ToolHookLayer
Layer that applies a ToolHookRegistry around tool dispatch.
ToolHookRegistry
Ordered collection of tool hooks.
ToolHookRequest
Immutable snapshot of one tool dispatch as seen by hooks.
ToolHookService
Service produced by ToolHookLayer.
ToolPair
One matched ToolCall / ToolResult pair. Sealed: the only path to construction is Compactor::compact internal grouping, so a pair without both halves cannot exist.
ToolToRunnableAdapter
Wraps any Tool as Runnable<serde_json::Value, serde_json::Value>.
TraceContextTransportotel
Transport decorator that stamps W3C Trace Context headers on every outbound request before delegating to the inner transport.
TypedModelStream
Streaming counterpart to a complete_typed call — raw deltas on stream, the aggregated typed payload on completion.
UsageSnapshot
Frozen snapshot of RunBudget counters at one point in time. Carried in AgentRunResult<S>::usage (B-5) so callers see the final tally without needing to clone the budget.
VertexCredentialProvidergcp
gcp_auth-backed token refresher.
VertexTransportgcp
GCP Vertex AI HTTP transport.
VertexTransportBuildergcp
Fluent builder for VertexTransport.
WithName
Wraps any tower::Layer<S> with a static name so external middleware participates in the crate::ChatModel::layer_names introspection channel. The wrapper is transparent at the tower::Layer boundary — WithName::new("concurrency", ConcurrencyLimitLayer::new(10)).layer(inner) produces the same service the underlying layer would.

Enums§

AgentEvent
Runtime events emitted by the agent during a single execute / execute_stream call.
ApprovalDecision
Outcome of a single tool-dispatch approval decision.
BedrockAuthaws
Auth strategy for BedrockTransport.
ChatPromptPart
One slot in a ChatPromptTemplate: either a templated message (role + text template) or a placeholder for a Vec<Message> variable.
CheckpointGranularity
How often the compiled graph writes a checkpoint when a Checkpointer is attached.
CloudError
Failures emitted by cloud-layer machinery (credential resolution, signing, refreshable token plumbing, binary frame parsing).
Command
Resume directive supplied to CompiledGraph::resume_with.
DebugEvent
Lifecycle marker for StreamMode::Debug.
Direction
Direction of edge traversal — outgoing edges leave a node, incoming edges arrive at it. Both returns the union.
EffectGate
Selector for which tool dispatches the ApprovalLayer gates through the Approver. Routes by the calling tool’s ToolMetadata::effect so operators express intent once at metadata time and the layer honours it without per-tool wiring.
ElicitationResponsemcp
Operator’s answer to an elicitation. Three explicit cases — the spec distinguishes them, callers should too.
Error
Aggregate error returned from public entelix-core APIs.
ErrorClass
Coarse responsibility class for an Error. Two values by design — “transient” / “permanent” is a retry-policy axis, orthogonal to responsibility, and surfaced via Error::Provider’s retry_after field plus the RetryClassifier policy surface.
ExecutionMode
Agent-level switch between immediate and human-supervised tool execution.
FailurePolicy
Per-chunk failure policy — picks how the chunker reacts when the underlying model call fails on one chunk. See module docs for the trade-off matrix.
FoundryAuthazure
Auth strategy for FoundryTransport.
GradeVerdict
Three-way verdict the grader emits per (query, document) pair, matching the CRAG paper’s relevance classes.
GraphEvent
One audit-log entry.
HfTokenizerErrortokenizer-hf
Errors raised when constructing an HfTokenCounter.
HostRule
One allowlist rule.
IncludeContextmcp
How much surrounding context the server wants the client to include in the sampling call. The client decides how to honour this (the spec is intentionally vague — it’s a hint, not a contract).
InterruptionKind
Why a dispatch paused. SDK variants carry typed structured data the resumer needs to thread the decision back; operator-defined pauses surface as Self::Custom with arbitrary payload.
InterruptionPhase
Phase at which a graph-scheduled pause fires — before the marked node runs (Before) or after it returns Ok (After).
McpClientStatemcp
Lifecycle position of an crate::McpClient.
McpCompletionReferencemcp
Reference target for a completion query.
McpErrormcp
MCP-layer failures.
McpPromptContentmcp
Content inside a McpPromptMessage.
McpResourceContentmcp
One block of content returned by resources/read. The MCP spec allows a single read to return multiple blocks (e.g. a file plus its metadata).
OpenAiEmbedderErrorembedders-openai
Errors that can surface from OpenAiEmbedder.
OperationKindotel
What kind of operation produced the metric. Mirrors the gen_ai.operation.name semconv attribute.
PersistenceErrorpostgres or redis
Errors that the persistence layer surfaces to its callers.
PgGraphMemoryErrorgraphmemory-pg
Errors that can surface from PgGraphMemory.
PgVectorDistanceMetricvectorstores-pgvector
Distance metric used for vector similarity. Mirrors pgvector’s own taxonomy 1:1 — operators familiar with <=> / <-> / <#> pick the metric they would have picked there.
PgVectorIndexKindvectorstores-pgvector
ANN index kind. HNSW is the production default; IVFFlat is selected when build time matters more than query latency.
PgVectorStoreErrorvectorstores-pgvector
Errors that can surface from PgVectorStore.
PolicyErrorpolicy
Policy-layer failures.
PromptValue
A variable’s value: either text (for templated parts) or a list of messages (for placeholders).
ProviderErrorKind
Provider failure category — distinguishes transport-class failures (the SDK never received a complete HTTP framing) from HTTP-class failures (the vendor responded with a status). Retry classifiers use this to make typed decisions rather than pattern-matching on status: 0 sentinels (invariant #17).
QdrantDistanceMetricvectorstores-qdrant
Distance metric used for vector similarity. Mirrors qdrant’s own taxonomy 1:1 — operators familiar with qdrant pick the metric they would have picked there.
QdrantStoreErrorvectorstores-qdrant
Errors that can surface from QdrantVectorStore.
ResourceBoundKindmcp
Names the resource bound that fired in McpError::ResourceBounded. #[non_exhaustive] so future bounds (per-method quota, total session bytes, …) can ship without breaking match arms.
RunnableEvent
Runtime event for StreamMode::Events.
SamplingContentmcp
Body of one SamplingMessage. Tagged by type field on the wire — matches the MCP spec’s content-block shape.
ServerBuildErrorserver
Construction-time failure surfaced by crate::AgentRouterBuilder::build.
ServerErrorserver
HTTP-layer error returned by request handlers.
StreamChunk
One chunk of a streaming Runnable invocation.
StreamMode
Which stream shape the caller wants.
SupervisorDecision
Decision a supervisor router emits each turn.
TenantModeserver
How the router resolves the tenant_id for an incoming request.
TiktokenEncodingtokenizer-tiktoken
OpenAI BPE encoding family. Pick the variant matching the target model — see the crate-level docs for the model-to-encoding table.
TiktokenErrortokenizer-tiktoken
Errors raised when constructing a TiktokenCounter.
TokenCounterResolution
Outcome of TokenCounterRegistry::resolve — surfaces whether a registered entry actually matched (provider, model) or the registry’s fallback counter was returned because no entry matched.
ToolError
Tool-layer failures.
ToolHookDecision
Decision returned by ToolHook::before_tool.
ToolIoCaptureModeotel
How the tool side of the layer surfaces gen_ai.tool.input and gen_ai.tool.output on the dispatch span events.
Turn
One turn in a compacted conversation. Sealed so a Turn::Assistant can only carry ToolPairs constructed via the compactor’s internal grouping code (paired calls + results).
UnknownModelPolicypolicy
Behavior when CostMeter::charge is called with a model that has no entry in the PricingTable.
UsageLimitBreach
One RunBudget axis breach — typed pair of axis-discriminator and magnitude. Each variant carries the magnitude shape the axis uses (u64 count for token / request / tool-call axes, Decimal USD for the cost axis), so axis-magnitude pairing is type-enforced rather than runtime-validated.
VectorFilter
Predicate against Document::metadata used by VectorStore::search_filtered. Backends translate this into their native filter language (pgvector WHERE, qdrant Filter, lancedb where); backends that cannot honour a given variant fall back to filterless search and emit a LossyEncode-style warning at the operator layer.

Constants§

CLOUD_DEFAULT_REFRESH_BUFFER
Default lead time before a token’s expiry triggers a refresh.
CONTEXTUAL_CHUNKER_DEFAULT_INSTRUCTION
Default operator-facing instruction prepended to every model call. Verbatim from Anthropic’s published Contextual Retrieval recipe — lifts the model into the right framing without requiring per-corpus tuning.
CORRECTIVE_RAG_AGENT_NAME
Stable agent name surfaced on every emitted entelix_agents::AgentEvent and OTel entelix.agent.run span.
DEFAULT_CHUNK_OVERLAP_CHARS
Default overlap between consecutive chunks. ~10% of DEFAULT_CHUNK_SIZE_CHARS preserves enough trailing context for retrieval grounding without bloating the index.
DEFAULT_CHUNK_OVERLAP_TOKENS
Default overlap between consecutive chunks in tokens. ~12.5% of DEFAULT_CHUNK_SIZE_TOKENS preserves enough trailing context for retrieval grounding without bloating the index.
DEFAULT_CHUNK_SIZE_CHARS
Default chunk size in characters. ~1000 chars maps to roughly 200-300 tokens for English under cl100k_base, comfortably under every shipping vendor’s per-message ceiling.
DEFAULT_CHUNK_SIZE_TOKENS
Default chunk size in tokens. 512 matches the typical embedding context window (text-embedding-3-small and -large both cap at 8191 tokens; chunking under 512 leaves headroom for query + instruction tokens at retrieval time).
DEFAULT_GENERATOR_SYSTEM_PROMPT
Default system prompt the generator node prepends to every answer-generation call. Vendor-neutral, focused on grounded answer style.
DEFAULT_GRADER_INSTRUCTION
Default instruction prepended to every model call. Frames the task verbatim in the CRAG-paper terms so the model emits one of the three canonical labels.
DEFAULT_MARKDOWN_HEADING_LEVELS
Default ATX heading levels that open a new chunk. [1, 2, 3] splits at #, ##, ###; deeper sub-headings (####+) stay inline.
DEFAULT_MAX_REWRITE_ATTEMPTS
Default cap on rewrite-loop attempts before the recipe surrenders and generates over whatever was retrieved last. 3 is the CRAG paper’s reported sweet spot (retrieval rarely improves beyond the third rewrite).
DEFAULT_MIN_CORRECT_FRACTION
Default minimum fraction of retrieved documents that must grade GradeVerdict::Correct for the recipe to skip rewriting and proceed directly to generation. 0.5 matches the CRAG paper’s mid-confidence threshold — operators tuning for higher retrieval precision raise it; tuning for lower model spend (fewer rewrites at the cost of weaker grounding) lower it.
DEFAULT_RECURSION_LIMIT
Default cap on node executions per invoke (F6 mitigation — guards against infinite cycles).
DEFAULT_RECURSIVE_SEPARATORS
Default separator priority list. Paragraph break → line break → word boundary → character. The empty-string fallback guarantees termination even on pathological input (one giant unbroken token).
DEFAULT_RETRIEVAL_TOP_K
Default top-k passed into the retriever on every retrieval pass. Operator-overridable via CragConfig::with_retrieval_top_k.
DEFAULT_REWRITER_INSTRUCTION
Default instruction prepended to every model call. Verbatim matches the CRAG-paper rewriter framing — the model produces one corrected query string, no surrounding explanation.
DEFAULT_SUMMARY_KEEP_RECENT_TURNS
Default count of newest turns the SummaryCompactor keeps verbatim before summarising the older history into one synthetic turn. Four matches the typical LLM-agent rhythm (most recent user/assistant pair plus one preceding pair) — small enough that summarisation kicks in early, large enough that adjacent context survives.
DEFAULT_SUMMARY_SYSTEM_PROMPT
Default system prompt the SummaryCompactor sends to its summariser model when the operator does not override. Phrased as a neutral compress-the-prior-conversation instruction so it works across vendors that route system prompts identically.
DEFAULT_TENANT_ID
Default tenant identifier — applied when callers do not specify one explicitly via crate::ExecutionContext::with_tenant_id. Single-tenant deployments rely on this and never construct a TenantId themselves.
DEFAULT_TOOL_IO_TRUNCATIONotel
Default truncation cap for tool I/O capture (4 KiB). Chosen so the typical {"task": "..."} / {"output": "..."} payload surfaces in full while a 50 KB HTTP-fetch response truncates before ballooning the span. Operators override via OtelLayer::with_tool_io_capture.
END
Sentinel target meaning “terminate without running another node”. Use in add_conditional_edges mapping when a branch should end the graph.
FOUNDRY_SCOPEazure
Standard scope for Azure OpenAI / Foundry data plane access.
HTTP_FETCH_DEFAULT_MAX_REDIRECTS
Default cap on redirect chain length.
HTTP_FETCH_DEFAULT_MAX_RESPONSE_BYTES
Default cap on response body size (1 MiB).
HTTP_FETCH_DEFAULT_TIMEOUT
Default per-call timeout.
MCP_DEFAULT_IDLE_TTLmcp
Default idle TTL for cached MCP clients. Operators schedule crate::McpManager::prune_idle (typically on a tokio::time::interval) to evict clients whose last use exceeded this threshold.
MCP_DEFAULT_LISTENER_CONCURRENCYmcp
Default cap on the number of in-flight server-initiated dispatches per client — 32.
MCP_DEFAULT_MAX_FRAME_BYTESmcp
Default cap on a single SSE frame’s accumulated byte length — 1 MiB.
MCP_DEFAULT_TIMEOUTmcp
Default request timeout for MCP HTTP calls. MCP servers are usually local-network or sidecar deployments; 30s is generous for tools that include LLM calls themselves.
MCP_PROTOCOL_VERSIONmcp
MCP protocol revision this client speaks.
OPENAI_EMBEDDINGS_BASE_URLembedders-openai
Default OpenAI API base URL. Override via OpenAiEmbedderBuilder::with_base_url for proxies, regional endpoints, or test fixtures.
POLICY_DEFAULT_MAX_TENANTSpolicy
Default cap on distinct tenant ledger entries.
POLICY_MAX_WARNED_MODELSpolicy
Cap on distinct model names tracked under WarnOnce.
PROVENANCE_METADATA_KEY
Reserved key on the persisted metadata map under which the pipeline stamps Source + Lineage + namespace. Carries the entelix prefix so an operator’s own metadata fields never collide. Retrieval-side consumers reach back to provenance through this nested object.
QDRANT_CONTENT_KEYvectorstores-qdrant
Payload key carrying the document’s content text.
QDRANT_DOC_ID_KEYvectorstores-qdrant
Payload key carrying the operator-supplied doc_id. Distinct from qdrant’s internal PointId so filters / scrolls can surface the operator id without a server-side reverse mapping.
QDRANT_METADATA_KEYvectorstores-qdrant
Payload key carrying the document’s metadata (flat map). User metadata fields ride here as nested JSON; filter expressions targeting metadata reference them via metadata.<key> paths.
QDRANT_NAMESPACE_KEYvectorstores-qdrant
Payload key under which the rendered Namespace is stamped on every point. Indexed at collection-create time so the must-clause that always rides on every search/count/list query is a single index probe rather than a full scan.
SEARCH_DEFAULT_MAX_RESULTS
Default cap on results returned per query.
SERVER_DEFAULT_TENANT_HEADERserver
Header name conventionally used when the operator opts into multi-tenant mode. Pass to AgentRouterBuilder::with_tenant_header.
TEXT_EMBEDDING_3_LARGEembedders-openai
OpenAI’s higher-quality embedding model. Native dimension 3072; can be reduced via the dimensions request parameter.
TEXT_EMBEDDING_3_LARGE_DIMENSIONembedders-openai
Native dimension of TEXT_EMBEDDING_3_LARGE.
TEXT_EMBEDDING_3_SMALLembedders-openai
OpenAI’s lower-cost embedding model. Native dimension 1536; can be reduced via the dimensions request parameter (operator with_dimension on the builder).
TEXT_EMBEDDING_3_SMALL_DIMENSIONembedders-openai
Native dimension of TEXT_EMBEDDING_3_SMALL.
VERTEX_SCOPEgcp
Standard GCP IAM scope for Vertex AI generative models.

Traits§

AgentEventSink
Consumer trait the agent calls for every emitted event.
AgentObserver
Turn-level agent-lifecycle observer.
AnyRunnable
Object-safe variant of Runnable that operates on serde_json::Value at the public interface. Useful for tool registries, dispatch tables, and dynamic plug-in points.
Approver
Decision-maker for supervised tool execution.
AuditSink
Typed audit-event channel. See module docs.
BudgetCostEstimator
Precision-accurate cost projection for crate::RunBudget axis enforcement.
ChatModelExt
Extension methods on ChatModel that produce typed Runnable adapters.
Checkpointer
Persistent (or in-memory) store of Checkpoint<S>s addressed by ThreadKey.
Chunker
Async transform applied to a sequence of chunks after a TextSplitter ran. Implementations may issue LLM calls, embedding lookups, or external metadata enrichment; the ExecutionContext supplies cancellation, deadline, and any entelix_core::RunBudget caps the parent pipeline configured.
Clock
Monotonic-clock abstraction. Implementors must produce strictly non-decreasing values; jitter or skew breaks any consumer that computes elapsed time from the difference of two reads (rate-limit buckets, exponential backoff, TTL windows).
Compactor
Operator-supplied compaction strategy.
ConsolidationPolicy
Decides whether the current buffered conversation should be consolidated.
CostCalculator
Compute a monetary cost for one model invocation.
DistributedLockpostgres or redis
Acquire-then-release primitive over a distributed key.
DocumentLoader
Source-side trait the ingestion pipeline pulls documents from.
ElicitationProvidermcp
Async source-of-truth for elicitation answers. Mirrors the *Provider taxonomy — async, single-purpose, replaceable.
Embedder
Text → vector encoder.
EmbeddingCostCalculator
Compute a monetary cost for one embedder call.
ExampleSelector
Strategy that picks which examples to inject into a few-shot prompt.
GraphMemory
Generic graph-of-knowledge memory. Trait so backends (Neo4j, ArangoDB, Postgres-with-recursive-CTE) can plug in without touching the consumer code; reference in-process impl is InMemoryGraphMemory.
LlmRenderable
Render a value (typically an error, sub-agent result, or memory-recall summary) into the short, actionable form the model is allowed to see. Implementors define Self::render_for_llm (the raw producer); the default Self::for_llm wraps the result in a sealed RenderedForLlm carrier whose constructor is private to this crate, so emit sites that accept the carrier receive a value that structurally went through the trait.
McpClientmcp
Backend-agnostic MCP client surface.
MessageRunnableCompactionExt
Extension trait that attaches RunnableCompacting to any Runnable<Vec<Message>, Message>. Blanket-impl’d for every such runnable so a model accepting messages — including layered models (OtelLayer, PolicyLayer, RetryService) — can chain .with_compaction(.) without a separate import per concrete type.
NamedLayer
Static identity for a tower::Layer participant in crate::ChatModel::layer / ToolRegistry::layer composition.
OutputValidator
Post-decode validator. Implementors return Error::ModelRetry to signal the ChatModel retry loop should re-prompt the model with corrective feedback. Other error variants bubble unchanged.
PiiRedactorpolicy
Bidirectional PII redaction surface.
QueryRewriter
Async trait the corrective-RAG recipe calls when retrieval quality requires another attempt with a different query. Implementations may be LLM-driven, heuristic (query-expansion / synonym-bag), classifier-routed, or any hybrid — the recipe takes whatever string comes back and re-runs retrieval with it.
RateLimiterpolicy
Backend-agnostic rate-limit surface.
Reducer
Combines a current value and an incoming update into the next value.
Reranker
Re-rank a candidate document set against the originating query.
RetrievalGrader
Async trait the corrective-RAG recipe consults for every retrieved document. Implementations may be LLM-driven (the canonical case, see LlmRetrievalGrader) or keyword / heuristic / classifier-model based — the recipe doesn’t care as long as the verdict is one of the three GradeVerdict variants.
Retriever
Returns documents ranked by relevance to a RetrievalQuery.
RootsProvidermcp
Async source-of-truth for the roots a server may discover via roots/list. Mirrors the *Provider taxonomy — async, single-purpose, replaceable.
Runnable
One end of a composable computation.
RunnableExt
Ergonomic composition surface, blanket-implemented for every Runnable<I, O>.
SamplingProvidermcp
Async source-of-truth for sampling completions. Mirrors the *Provider taxonomy — async, single-purpose, replaceable.
SchemaTool
Typed-I/O sibling of Tool. Implementors get Input/Output typed against the model’s tool dispatch without giving up the erased trait the rest of the SDK speaks.
SchemaToolExt
Provided extension methods on every SchemaTool. Lives in a separate trait so blanket-impls (e.g. Box<dyn SchemaTool>) don’t fight with the user-implemented SchemaTool trait associated types.
SearchProvider
Adapter trait the SearchTool dispatches to.
SemanticMemoryBackend
Object-safe consumer trait — tier 3 of the semantic-memory layering documented at the module level. Consumers (tools, orchestration code, recipes) take Arc<dyn SemanticMemoryBackend> to operate on a namespace-scoped embed-and-search surface without parameterising over the concrete embedder / vector-store types.
SessionLog
Persistent durable session-event log.
StateMerge
State-level merge: how an incoming update folds into the current state. The dispatch-loop counterpart to Reducer<T>, one level up — implemented on the whole S shape rather than a single slot.
Store
Persistent (or in-memory) key/value store, scoped by Namespace.
Summarizer
Reduces a buffer of conversation messages to a summary string.
TextSplitter
Pure-algorithm slice of a Document into smaller documents.
TokenCounter
Counts tokens for budget enforcement, splitter sizing, and content-economy estimation.
TokenRefresher
Source-of-truth that yields a fresh T plus its absolute expiry time when called.
ToolApprovalEventSink
Type-erased sink for tool-approval events. The agent runtime produces an implementation by adapting its Arc<dyn AgentEventSink<S>> (see ToolApprovalEventSinkHandle::for_agent_sink); operators implementing custom downstream observability (OTel direct, audit-log direct) can implement this trait directly without going through AgentEventSink<S>.
ToolCostCalculator
Compute a monetary cost for one tool dispatch.
ToolHook
Hook for tool lifecycle policy and audit extensions.
UnknownModelSinkpolicy
Observer notified on every unknown-model charge attempt.
VectorStore
Vector index keyed by Namespace. Backed by qdrant, lancedb, pgvector, etc. in companion crates.

Functions§

build_chat_graph
Build the single-node chat graph (system message prepend → model → finish) without wrapping it into an Agent. Use this when you want to configure the agent surface (name, sink, approver, observers) via Agent::builder directly.
build_corrective_rag_graph
Compile the corrective-RAG graph from operator-supplied primitives. Use this when you need to embed the graph as a node in a larger StateGraph; for a ready-to-execute agent, prefer create_corrective_rag_agent.
build_react_graph
Builds the compiled ReAct graph (planner ↔ tools ↔ finish loop) without wrapping it into an Agent. Use this when you want to configure the agent-level surface (name, sink, approver, observers) directly via Agent::builder:
build_supervisor_graph
Build a supervisor graph that picks among agents each turn.
create_chat_agent
Build a single-turn chat agent: prepends system (if non-empty) to the conversation, calls model, appends the reply, and finishes.
create_corrective_rag_agent
Build a ready-to-execute corrective-RAG Agent. Wraps build_corrective_rag_graph in the standard Agent<S> shape so the full lifecycle (AgentEvent stream, sink fan-out, observer hooks, supervisor handoff) integrates uniformly with every other recipe (create_react_agent, create_supervisor_agent, create_chat_agent).
create_react_agent
Builds a ReAct-style agent: model decides; if it emits tool calls, dispatch and loop back; otherwise finish.
create_supervisor_agent
Build a supervisor graph that picks among agents each turn.
default_pii_patternspolicy
A small starter set of PII patterns. Production deployments almost always extend or replace these per jurisdiction; this list exists so a RegexRedactor::default() is non-trivial out of the box.
default_token_counter_registry
Build a TokenCounterRegistry pre-populated with every counter the enabled tokenizer features can supply.
erase
Wrap a typed Runnable<I, O> as an AnyRunnable by transcoding I/O through serde_json::Value. Returns Arc<dyn AnyRunnable> so the result drops directly into a registry.
first_non_finite_vector_value
Return the first non-finite vector element, if any.
install_default_tls
Install the default rustls crypto provider for entelix transports. Call once near the top of main, before any Transport::send runs.
interrupt
Pause the current dispatch with a InterruptionKind::Custom reason. The most common HITL primitive — wrap any tool-body branch, node body, or layer hook that needs to hand control back to the caller for human review.
interrupt_with
Pause the current dispatch with a typed InterruptionKind. Used by SDK-internal sites (the agent runtime’s ApprovalLayer raises InterruptionKind::ApprovalPending this way) and by operators with structured pause-reasons of their own.
is_ssrf_blocked
Returns true for IPs the SDK refuses to connect to by default.
luhn_validpolicy
Luhn-checksum validator — reject candidate runs that aren’t well-formed payment-card numbers. Strips spaces, dashes, and non-digit noise before computing.
messages_char_size
Character-length proxy for the token cost of a message slice. Same metric HeadDropCompactor uses to compare against budget_chars, so threshold-driven auto-compaction can use the same yardstick.
messages_to_events
Render an in-flight Vec<Message> (the shape an agent’s working state carries) into a Vec<GraphEvent> that Compactor::compact can consume. Inverse of CompactedHistory::to_messages.
qualified_namemcp
Build the canonical mcp:{server}:{tool} namespaced name.
team_from_supervisor
Adapt a supervisor Agent<SupervisorState> into a Runnable<Vec<Message>, Message> so it can be embedded as one AgentEntry inside a parent supervisor — the nested-supervisor pattern.
trace_context_injectorotel
Build an Arc<Fn(&mut HeaderMap)> that injects the active W3C trace-context (traceparent / tracestate / baggage) into any outbound http::HeaderMap.
validate_server_namemcp
Validate an MCP server name against the documented format.
validate_vector_shape
Validate vector dimension and finite values for vector-store calls.
with_session_lockpostgres or redis
Acquire a session lock keyed by (tenant, thread), run the caller’s closure, then release the lock. The lock is released even if f returns an error.

Type Aliases§

AnyRunnableHandle
Convenience Arc<dyn AnyRunnable> alias for registries / dispatch tables.
BoxStream
Boxed Stream alias used by every stream() return type.
DocumentStream
Boxed stream type alias for documents produced by a DocumentLoader. Items are Result so a partial-success stream can yield successful documents while reporting per-item errors — a single mid-walk failure does not abort the whole ingestion run.
DynObserver
Convenience type alias for the dynamic-dispatch handle the agent stores internally.
EdgeSelector
Closure that picks a conditional-edge target by inspecting state.
Example
One few-shot example: a map of example-prompt variable name → value.
McpResultmcp
Result alias used inside entelix-mcp.
OpenAiEmbedderResultembedders-openai
Result alias used inside entelix-memory-openai.
PersistenceResultpostgres or redis
Result alias used inside entelix-persistence.
PgGraphMemoryResultgraphmemory-pg
Result alias used inside entelix-graphmemory-pg.
PgVectorStoreResultvectorstores-pgvector
Result alias used inside entelix-memory-pgvector.
PolicyResultpolicy
Result alias used inside entelix-policy.
PromptVars
Map of variable name → value, accepted by ChatPromptTemplate::render and the Runnable impl.
QdrantStoreResultvectorstores-qdrant
Result alias used inside entelix-memory-qdrant.
RequestDecoratormcp
Hook that decorates outgoing MCP requests with extra HTTP headers.
Result
Convenience alias used across entelix-core and re-exported by the facade.
RetrievedDocumentId
Stable identifier for an indexed document. Backends mint these at insertion time; passing the same id to VectorStore::update or VectorStore::delete is the canonical way to mutate or remove a previously-indexed document.
SendMerger
Two-state merger applied per branch result during a send-edge fold — the dispatch loop calls it once per branch with (folded_so_far, branch_state) -> next_folded.
SendSelector
Closure returning the parallel branches a send edge dispatches. Each pair is (target_node_name, branch_state); target nodes run concurrently with their respective branch states.
ServerBuildResultserver
Result alias used by crate::AgentRouterBuilder::build.
ServerResultserver
Result alias used by every handler in entelix-server.
SharedExampleSelector
Convenience type-alias for selectors handed around as trait objects.
ToolResult
Result alias used inside entelix-tools.

Attribute Macros§

tool
Generate an entelix_tools::SchemaTool impl from an async fn. See the crate-level docs for the contract and an example.

Derive Macros§

StateMerge
Derive entelix_graph::StateMerge and generate the <Name>Contribution companion struct.