Skip to main content

Crate causa_kernel

Crate causa_kernel 

Source
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 (the ConversationState aggregate, 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 shared merged_frame projection.
  • 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 in causa-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): Some serializes as the snapshot projection, None as null. The session aggregate lives in causa-runtime and serializes its active slot through this bridge.
turn_context_as_snapshot
Serde bridge: a TurnContext is serialized as its immutable TurnSnapshot projection and rebuilt from that shape on load. The wire representation of the field is always a TurnSnapshot.

Structs§

AppliedModelOutput
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.
ArtifactHint
Provenance a caller attaches to bytes handed to ArtifactStore::persist, so the store can label what it receives.
ArtifactRef
Pointer to a tool output persisted out-of-band (e.g. a spilled oversized observation), kept on the result instead of the full content.
AttemptControl
One model attempt’s control plane: the turn-shared CancellationToken plus the effective attempt deadline (turn deadline folded with the attempt timeout).
AttemptNumber
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.
BlockMeta
Envelope provenance. Fields are serde-additive so legacy snapshots without them still deserialize.
BlockSequence
Monotonic per-turn block ordinal, assigned once when the fact machine commits a block; dense and gap-free (validated on replay).
CallControl
One tool call’s control plane: the same turn-shared CancellationToken with the deadline narrowed to the call.
CancellationToken
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.
ContextBlock
A typed fact. Three axes: identity, content, envelope provenance.
ContextFrame
One deterministic projection of fact state handed to (or from) a model round: identity, scope, the round it belongs to, and the block content.
ContextVersion
Counts canonical fact commits of a turn; bumps exactly once per non-empty commit and pins the frame identity for a round.
ConversationId
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; see from_scope for the preimage formats.
GenerationOptions
Sampling knobs a caller may pin for the invocation. None means “unspecified”: renderers omit the knob and the provider default applies.
InvocationId
Identity of one model invocation: which turn, and which round inside it.
MediaRef
A media fact: a cheap, durable reference. Bytes never enter facts — they appear only in resolved render payloads (provider side).
ModelContext
The model-facing context of a frame: the ordered fact blocks a round saw.
ModelInvokeError
A model-invocation failure: a ModelInvokeErrorKind plus human-readable detail (provider text included where available).
ModelOutput
The gateway’s result envelope: the model door consumes only the ModelResponse and ModelStopReason facts from it; usage and reasoning stay caller-retained.
ModelRef
Opaque model identifier, rendered verbatim into the provider request’s model field. The kernel never parses it; resolution is the gateway’s job.
ModelRequest
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.
ModelResponse
The model door’s fact shape: what the model said (text) and asked (tool calls). Named for the participant, not for any wire role.
ModelUsage
Provider-reported token accounting for one model response.
OrderedBlocks
The fact machine’s block log: append-only and order-preserving.
ReasoningPayload
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.
TextPayload
A single string of text. Serializes transparently as the inner string.
ToolCallContext
Identity of one tool dispatch, handed to Tool::execute.
ToolCallDraft
A tool call as the model proposed it, before the kernel assigns the canonical ToolCallId. Exactly what the gateway parsed off the wire.
ToolCallId
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.
ToolCallPayload
A model-issued tool call. call_id is the kernel-generated causal key; any provider-issued identifier rides on BlockMeta::provider_call_id.
ToolDefinition
The model-facing description of one callable tool; renderers map it onto the protocol’s tool entries (name, description, parameter schema).
ToolOutput
What a tool returned, as recorded by the tool door.
ToolOutputMeta
Optional observability sidecar on a tool output; never part of pairing.
ToolResultPayload
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.
ToolSurface
The tool definitions offered to the model for one invocation; renderers turn this into the protocol’s tools array.
TurnContext
Current turn’s ordered fact state. All mutation goes through the three controlled doors (append_input / append_model_output / append_tool_results) plus seal; there is no second &mut seam — fields are private by design. The only projection the fact machine offers is the lossless frame(); policy-shaped materialization lives in causa_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.
TurnSnapshot
Immutable, serializable projection of a turn — the canonical wire shape for a persisted turn (a live TurnContext is never serialized directly). The snapshot describes the record itself only: identity, blocks, fact version, and write lifecycle. Session ordering lives in the runtime’s HistoryEntry, not here.

Enums§

ArtifactKind
What an artifact holds.
BlockContent
The content shape of a block. Three shapes: one message’s ordered parts (any role), a tool call, a tool result.
CacheDirective
Prompt-cache instruction carried on a ModelRequest. The Anthropic translation face renders explicit cache_control breakpoints at the stable-prefix anchors; OpenAI-family providers cache server-side and accept the directive as a documented no-op.
ContentPart
One content atom inside a BlockContent::Parts block: ordered, identity-free, sharing the block’s envelope. New modalities arrive as new variants (additive); media bytes stay out of facts forever.
ContextError
Fact-machine rejections: lifecycle, pairing, or structural-validity violations. None carry transport or execution semantics.
ControlError
Why a control check failed.
FrameScope
Frame identity/provenance tag. Turn scopes a single-turn projection; Conversation scopes the lossless merged view (history + active turn). Adding a scope variant is additive; the scope never changes block-level operation rules.
ModelInvokeErrorKind
Classification of a model-invocation failure — the fact the retry policy branches on.
ModelStopReason
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.
SourceError
Listing failure — the catalog as a whole is unusable right now.
StoreError
Error surface of the ArtifactStore port.
StreamDelta
One incremental observation from a streaming provider.
ToolExecutionError
Single-call failure inside a source. The executor’s tool adapter (ToolBridge in causa_runtime) turns every variant into a structured tool result the model reads; the status mapping lives there, not here.
ToolResultStatus
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.
TurnLifecycle
Whether a turn still accepts appends or is terminal.

Traits§

ArtifactStore
Persistence port for tool artifacts — where oversized tool outputs are spilled and read back. Callers persist raw bytes plus an ArtifactHint and receive an ArtifactRef to embed in the result; concrete stores are host concerns.
DynamicToolSource
One external tool catalog. Implementors own their connection, their naming (see the mcp_{server_id}_{tool} namespace convention in causa-extension), and their change notifications.
ModelGateway
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 UnknownOutcome result 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-Done stream — the degenerate form the default stream implementation 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 in causa-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§

ModelStream
Bounded stream of provider deltas. Cancellation is observable through the same AttemptControl the invoke path uses — drivers race next() against the cancellation token, never poll.