Expand description
causa-kernel — ContextBlock conversation kernel. No dependency on a host application, a UI shell, or another agent framework.
§Layering (the kernel is facts + contracts, nothing else)
context— the external rule interface: exactly what the fact machine stores and validates — block content shapes, the turn state machine and its deterministic projections, and ids. Session-level vocabulary (theConversationStateaggregate, its eligibility stamp, ordering, and the conversation store port) is runtime territory; the kernel keeps the facts (TurnContext/TurnSnapshot), the validated recovery entries, and the sharedmerged_frameprojection.ports— the behavior seams external implementors fill in, each self-contained:ModelGateway(request params, result envelope, transport error),Tool+ArtifactStore(definitions, execution context, outcome policy, limits),DynamicToolSource, control planes. A type belongs here iff it is the contract surface third parties implement or call against; the kernel itself consumes none of it. The reference budget/compaction and host↔driver interaction seams are the runtime components’ opinions, not cross-host contracts, and live incausa-runtime.
The execution stack, executor, hook seam, config axes, and run control
live in causa-runtime. Anything left here is either a fact or a
contract; both are load-bearing.
The physical modules are private; every re-export below is the entire public contract. Nothing else is a cross-crate commitment.
Modules§
- option_
turn_ context_ as_ snapshot - Serde bridge for
Option<TurnContext>fields (the session aggregate’s active slot):Someserializes as the snapshot projection,Noneas null. The session aggregate lives incausa-runtimeand serializes its active slot through this bridge. - turn_
context_ as_ snapshot - Serde bridge: a
TurnContextis serialized as its immutableTurnSnapshotprojection and rebuilt from that shape on load. The wire representation of the field is always aTurnSnapshot.
Structs§
- Applied
Model Output - Receipt of the model door: the committed fact block ids plus the prepared tool calls in model draft order. The tool calls are the execution handoff — call ids are generated exactly once, here, so the driver dispatches the same payloads the kernel committed and never re-reads blocks.
- Artifact
Hint - Provenance a caller attaches to bytes handed to
ArtifactStore::persist, so the store can label what it receives. - Artifact
Ref - Pointer to a tool output persisted out-of-band (e.g. a spilled oversized observation), kept on the result instead of the full content.
- Attempt
Control - One model attempt’s control plane: the turn-shared
CancellationTokenplus the effective attempt deadline (turn deadline folded with the attempt timeout). - Attempt
Number - Attempt-loop ordinal, carried on requests and attempt traces. Not a fact: the kernel’s doors never branch on it.
- BlockId
- Unique identity of a fact block: the owning turn plus the block’s dense position within that turn.
- Block
Meta - Envelope provenance. Fields are serde-additive so legacy snapshots without them still deserialize.
- Block
Sequence - Monotonic per-turn block ordinal, assigned once when the fact machine commits a block; dense and gap-free (validated on replay).
- Call
Control - One tool call’s control plane: the same turn-shared
CancellationTokenwith the deadline narrowed to the call. - Cancellation
Token - The cancellation primitive behind the control planes, re-exported so the port is self-contained for external drivers. A token which can be used to signal a cancellation request to one or more tasks.
- Context
Block - A typed fact. Three axes: identity, content, envelope provenance.
- Context
Frame - One deterministic projection of fact state handed to (or from) a model round: identity, scope, the round it belongs to, and the block content.
- Context
Version - Counts canonical fact commits of a turn; bumps exactly once per non-empty commit and pins the frame identity for a round.
- Conversation
Id - Unique identity of a conversation aggregate. Opaque string; scopes the conversation’s turns, sequences, and versions.
- FrameId
- Deterministic frame identity: a blake3 digest of the scope and round,
truncated to 16 hex chars. Equal
(scope, round)inputs always yield the same id; seefrom_scopefor the preimage formats. - Generation
Options - Sampling knobs a caller may pin for the invocation.
Nonemeans “unspecified”: renderers omit the knob and the provider default applies. - Invocation
Id - Identity of one model invocation: which turn, and which round inside it.
- Media
Ref - A media fact: a cheap, durable reference. Bytes never enter facts — they appear only in resolved render payloads (provider side).
- Model
Context - The model-facing context of a frame: the ordered fact blocks a round saw.
- Model
Invoke Error - A model-invocation failure: a
ModelInvokeErrorKindplus human-readable detail (provider text included where available). - Model
Output - The gateway’s result envelope: the model door consumes only the
ModelResponseandModelStopReasonfacts from it; usage and reasoning stay caller-retained. - Model
Ref - Opaque model identifier, rendered verbatim into the provider request’s
modelfield. The kernel never parses it; resolution is the gateway’s job. - Model
Request - Everything one gateway attempt needs: invocation identity, the context to
render, and the invocation knobs. Invariant across retries of the same
logical invocation except for
ModelRequest::attempt. - Model
Response - The model door’s fact shape: what the model said (text) and asked (tool calls). Named for the participant, not for any wire role.
- Model
Usage - Provider-reported token accounting for one model response.
- Ordered
Blocks - The fact machine’s block log: append-only and order-preserving.
- Reasoning
Payload - Structured reasoning content: the model’s thinking text plus the optional provider signature some APIs attach so it can be replayed on later turns. Recorded as-is by callers; the kernel does not interpret or persist it.
- RoundId
- Ordinal of a model round within a turn (0-based). Enters the frame-identity and tool-call-id hash preimages, so the same logical call in different rounds never collides.
- Text
Payload - A single string of text. Serializes transparently as the inner string.
- Tool
Call Context - Identity of one tool dispatch, handed to
Tool::execute. - Tool
Call Draft - A tool call as the model proposed it, before the kernel assigns the
canonical
ToolCallId. Exactly what the gateway parsed off the wire. - Tool
Call Id - Canonical causal key pairing a tool call with its result. Kernel-generated
(see
generate), unique within a single turn context; never the provider-issued call id, which rides on the envelope metadata. - Tool
Call Payload - A model-issued tool call. call_id is the kernel-generated causal key; any provider-issued identifier rides on BlockMeta::provider_call_id.
- Tool
Definition - The model-facing description of one callable tool; renderers map it onto the protocol’s tool entries (name, description, parameter schema).
- Tool
Output - What a tool returned, as recorded by the tool door.
- Tool
Output Meta - Optional observability sidecar on a tool output; never part of pairing.
- Tool
Result Payload - The result fact for one tool call: the paired call id, terminal status, and the output. Committed through the tool door; pairing against the committed call block is kernel-enforced.
- Tool
Surface - The tool definitions offered to the model for one invocation; renderers
turn this into the protocol’s
toolsarray. - Turn
Context - Current turn’s ordered fact state. All mutation goes through the three
controlled doors (
append_input/append_model_output/append_tool_results) plusseal; there is no second&mutseam — fields are private by design. The only projection the fact machine offers is the losslessframe(); policy-shaped materialization lives incausa_runtime::budget::FramePolicy::materialize, so context never depends on harness policy and never awaits behavior. - TurnId
- Unique identity of a turn. Opaque string; scopes every block, sequence, and version belonging to that turn, and is checked on every model-door invocation.
- Turn
Snapshot - Immutable, serializable projection of a turn — the canonical wire shape
for a persisted turn (a live
TurnContextis never serialized directly). The snapshot describes the record itself only: identity, blocks, fact version, and write lifecycle. Session ordering lives in the runtime’sHistoryEntry, not here.
Enums§
- Artifact
Kind - What an artifact holds.
- Block
Content - The content shape of a block. Three shapes: one message’s ordered parts (any role), a tool call, a tool result.
- Cache
Directive - Prompt-cache instruction carried on a
ModelRequest. The Anthropic translation face renders explicitcache_controlbreakpoints at the stable-prefix anchors; OpenAI-family providers cache server-side and accept the directive as a documented no-op. - Content
Part - One content atom inside a
BlockContent::Partsblock: ordered, identity-free, sharing the block’s envelope. New modalities arrive as new variants (additive); media bytes stay out of facts forever. - Context
Error - Fact-machine rejections: lifecycle, pairing, or structural-validity violations. None carry transport or execution semantics.
- Control
Error - Why a control check failed.
- Frame
Scope - Frame identity/provenance tag.
Turnscopes a single-turn projection;Conversationscopes the lossless merged view (history + active turn). Adding a scope variant is additive; the scope never changes block-level operation rules. - Model
Invoke Error Kind - Classification of a model-invocation failure — the fact the retry policy branches on.
- Model
Stop Reason - Why the model stopped producing output for this round, as reported by the gateway. The kernel validates only the EndTurn/ToolUse structural pairing; interpreting terminal reasons is driver policy.
- Source
Error - Listing failure — the catalog as a whole is unusable right now.
- Store
Error - Error surface of the
ArtifactStoreport. - Stream
Delta - One incremental observation from a streaming provider.
- Tool
Execution Error - Single-call failure inside a source. The executor’s tool adapter
(
ToolBridgeincausa_runtime) turns every variant into a structured tool result the model reads; the status mapping lives there, not here. - Tool
Result Status - Terminal status of one tool invocation, recorded verbatim as a fact; mapping from execution errors is the driver’s job, not the kernel’s.
- Truncation
- Whether tool output content was shortened to fit the token limit.
- Turn
Lifecycle - Whether a turn still accepts appends or is terminal.
Traits§
- Artifact
Store - Persistence port for tool artifacts — where oversized tool outputs are
spilled and read back. Callers persist raw bytes plus an
ArtifactHintand receive anArtifactRefto embed in the result; concrete stores are host concerns. - Dynamic
Tool Source - One external tool catalog. Implementors own their connection, their
naming (see the
mcp_{server_id}_{tool}namespace convention incausa-extension), and their change notifications. - Model
Gateway - The model-invocation port: concrete gateways (provider adapters) live
outside the kernel and translate
ModelRequests onto their transport, honoring the attempt’s control plane. - Tool
- The tool port: one callable tool the model can invoke. Implementations
live outside the kernel; the driver’s executor dispatches them. A tool
returns only its recorded result — whether an
UnknownOutcomeresult may continue the turn and how output is retained are runtime-component configuration (causa_runtime), not tool declarations.
Functions§
- completed_
model_ stream - Wrap an already-complete output as a single-
Donestream — the degenerate form the defaultstreamimplementation and tests use. - effective_
deadline - Fold a parent deadline and a timeout into the effective deadline: the earlier of the two, where “no parent”/“no timeout” each leave the other side in force. External drivers narrow turn deadlines into attempt deadlines through this fold.
- merged_
frame - Shared lossless merged materialization over committed history plus the
active turn — the single semantics both the runtime’s
ConversationState::frame()and any external conversation driver’s merged-view entry use. The session aggregate that calls it lives incausa-runtime, but the projection itself is common frame vocabulary and stays with the facts. No reordering, no dedup, no trimming; nothing is written back.
Type Aliases§
- Model
Stream - Bounded stream of provider deltas. Cancellation is observable through
the same
AttemptControltheinvokepath uses — drivers racenext()against the cancellation token, never poll.