Skip to main content

causa_runtime/
lib.rs

1//! causa-runtime — optional components over the context kernel.
2//!
3//! The kernel is facts (`context`) + contracts (`ports`) only. This crate
4//! is a set of optional, reference components on top of them: adopt the
5//! execution stack, take a single piece, or read them as a reference and
6//! build your own. Each component documents the policy it bakes in and what
7//! adopting it brings along.
8//!
9//! - **Driver stack** (`driver`, `executor`, `hook`, `config`, `control`):
10//!   `TurnRunner` orchestrates turns over the kernel's ports —
11//!   retry scheduling, tool batch dispatch, artifact spill, traces, and
12//!   run control.
13//! - **Budget & interaction components** (`budget`, `interaction`): the
14//!   frame-materialization policy (`FramePolicy`, window budget,
15//!   compaction, token counting) and the host↔driver `TurnInteraction`
16//!   seam — the component's documented opinions, not fact-layer invariants.
17//!   A custom host composes the kernel's lossless `TurnContext::frame`
18//!   differently.
19//! - **Session aggregate** (`conversation`): `ConversationState` (single
20//!   active slot, completed-only history, commit-time `TurnSequence` as
21//!   `HistoryEntry`), the `SealedResult` stamp, and the `ConversationStore`
22//!   archive port. These are component decisions, not fact-layer invariants;
23//!   a custom host composes the kernel facts differently.
24//! - **Session coordination** (`session`): one [`Session`] owner per
25//!   conversation drives accepted work through the assembled [`TurnRunner`]
26//!   — cloneable [`SessionHandle`]s submit / observe / wait / resume / cancel,
27//!   one active work at a time, per-work `TurnId`s assigned at acceptance and
28//!   never reused, local `request_key` dedup, explicit retained-work capacity,
29//!   and an observable `Faulted` state. The material-free save loop is
30//!   implemented: an idle or paused session exports a versioned
31//!   [`SessionCheckpoint`], and `SessionCheckpoint::restore` registers it
32//!   against freshly assembled capabilities without calling the model or a
33//!   tool. Multi-session coordination and per-work materials are out of
34//!   scope.
35//! - **Tool-use filters** (`DedupFilter`, `AllowAllFilter`, `DenyAllFilter`,
36//!   `FilterChain`) implement this crate's `ToolUseHook` directly — the
37//!   trait, its consumer, and its policies share one crate. The default is
38//!   `PassthroughHook` (no opinion); composition and policy are opt-in.
39//! - **Events** (`ContextEvent` / `project_turn`) project a finished turn's
40//!   facts (`TurnContext` + `TurnResult` + `TurnTrace`) into an IPC-ready
41//!   event sequence for UI / observability / audit consumers.
42//!
43//! Implementation-side note: implementing a `ModelGateway` or a `Tool`
44//! requires only `causa-kernel`; this crate exists to *use the optional
45//! execution components*, not to fill the kernel's ports.
46//!
47//! # Optional components
48//!
49//! Everything here is optional, and each piece is offered as a reference:
50//! adopt it whole, or read it and build your own. The four responsibilities
51//! below are how the crate is organized — not a promise about how finely it
52//! can be split. What adopting a piece brings along is noted as cost, not as
53//! a contract.
54//!
55//! 1. **Execution stack** — [`TurnRunner`] plus its config
56//!    ([`TurnRunOptions`], policy axes), resume ([`resume_turn`]), hook
57//!    seam, the budget ([`FramePolicy`]) and interaction
58//!    ([`TurnInteraction`]) components, and the session owner
59//!    ([`Session`] / [`SessionHandle`] / [`SessionCheckpoint`]).
60//!    Adopting it brings those policy components along; the defaults they
61//!    bake in are documented in the policy table below, not fact-layer
62//!    invariants.
63//! 2. **Tool execution** — [`ToolExecutor::execute_with_limits`] runs one
64//!    call (panic isolation, deadline backstop, limit truncation, error
65//!    mapping) with no runner and no session; adopting it also brings the
66//!    config and budget vocabulary. Its catalog cache and static-name
67//!    priority are executor policies, documented at the impl site.
68//! 3. **Session aggregate** — [`ConversationState`] owns the single-active
69//!    slot, completed-only history, and commit ordering ([`HistoryEntry`]).
70//!    A host with different session needs composes kernel facts directly.
71//! 4. **Observation** — traces and [`ContextEvent`] are projections of a
72//!    finished turn for UI / audit consumers; reading them brings the
73//!    execution stack along. The host chooses what to persist; there is no
74//!    separate wire model.
75//!
76//! # Policy surface
77//!
78//! Every default the driver bakes in is one of two kinds — a swappable
79//! policy object, or a documented opinion. No trait seams exist for
80//! single-implementation policies; a seam is added only when a second real
81//! shape appears.
82//!
83//! | Policy | Kind | Where |
84//! |---|---|---|
85//! | Retry schedule (disabled by default; when enabled, 500 ms base, 8 s ceiling, exponential) | config object [`RetryPolicy`] | `config` |
86//! | Turn limits (10 model rounds, 64 tool calls by default) | config object [`TurnLimits`] in [`TurnPolicy`] | `config` |
87//! | Frame compaction (none by default; host supplies compactor, token counter and thresholds) | config object [`FramePolicy`] | `budget` |
88//! | Interaction / approval gate | port object [`NoopInteraction`] default | `config` |
89//! | Tool-use filtering | port object [`HookCtx`] / [`ToolUseHook`], default [`PassthroughHook`] | `hook`, `filter` |
90//! | Tool-output token estimation fallback (chars/4; frame estimation defaults to zero) | documented opinion, single home | `defaults::placeholder_token_estimate_value` (crate-internal), [`FramePolicy`] |
91//! | Output truncation shape (retained head 60% + tail 40% sized to the declared token budget — notice and JSON-string wrapping measured, notice-only floor at tiny budgets; artifact spill; content replaced by a JSON string; `Truncation::Middle` marker) | documented opinion | `executor::ToolExecutor::execute_with_limits` |
92//! | Unknown-outcome continuation (default `Stop`, per-executed-name overrides, explicit per-call host decisions) | config object [`UnknownOutcomeConfig`] + checkpoint [`UnknownDecision`] data | `config`, `hook`, `driver` |
93//! | Batch semantics (dedup-then-parallel, per-call panic isolation → `Failed`, call-deadline backstop → `UnknownOutcome`) | documented opinion | `executor` |
94//! | Session retention (256 works, rejects new work at capacity) and work deadline (none by default) | config object [`SessionConfig`] | `session` |
95//! | Session admission (one active work, no queue), completed-only history and checkpoint eligibility | documented component opinions | [`Session`], [`ConversationState`], [`SessionCheckpoint`] |
96//!
97//! This table summarizes the main execution and session policies. Component
98//! and configuration docs describe further defaults and constraints; absence
99//! from this table does not make a runtime decision a kernel invariant.
100
101#![deny(unsafe_code)]
102#![deny(missing_docs)]
103
104pub mod budget;
105pub mod composition;
106pub mod config;
107pub mod control;
108pub mod conversation;
109mod defaults;
110pub mod driver;
111pub mod event;
112pub mod executor;
113pub mod filter;
114pub mod hook;
115pub mod interaction;
116pub mod resume;
117pub mod session;
118
119// --- reference budget & interaction -----------------------------------------
120pub use budget::{
121    Compaction, CompactionError, CompactionInput, CompactionOutput, FrameError, FramePolicy,
122    TokenCounter, WindowBudget,
123};
124pub use interaction::{BatchDecision, TurnInteraction};
125
126// --- driver stack -----------------------------------------------------------
127pub use composition::ToolBridge;
128pub use config::{
129    ExecutionOptions, NoopInteraction, RetryPolicy, ToolOutputLimits, TurnInvocation, TurnLimits,
130    TurnPolicy, TurnRunOptions, UnknownOutcomeConfig, UnknownOutcomePolicy,
131};
132pub use control::RunControl;
133pub use conversation::{
134    ConversationError, ConversationState, ConversationStore, ConversationStoreError,
135    ConversationVersion, HistoryEntry, SealedResult, TurnSequence,
136};
137pub use driver::{
138    AttemptTrace, Continuation, ConversationOutcome, ModelRoundTrace, OutputSummary, PausePoint,
139    PreparedApproval, ToolBatchTrace, ToolCallTrace, TurnInterruption, TurnOutcome, TurnResult,
140    TurnRunner, TurnTrace,
141};
142pub use executor::{ToolExecutor, ToolRegistryError};
143pub use hook::{HookCtx, HookOutcome, PassthroughHook, ToolUseHook, UnknownDecision};
144pub use resume::{ResumeRejection, ResumeRequest, resume_turn};
145pub use session::{
146    CancelOutcome, CancelReceipt, CheckpointPhase, FinishedKind, SESSION_CHECKPOINT_VERSION,
147    SavedCancelKey, SavedResumeKey, SavedSubmitKey, SavedWork, Session, SessionBuildRejection,
148    SessionCheckpoint, SessionConfig, SessionConfigDescription, SessionError, SessionHandle,
149    SessionRestoreRejection, SubmitRequest, WaitEnd, WaitOutcome, WorkObservation, WorkReceipt,
150    WorkRef, WorkState,
151};
152
153// --- framework policies and projections --------------------------------------
154pub use event::{
155    ContextEvent, ContextEventKind, StreamEventCollector, project_streaming_turn, project_turn,
156};
157pub use filter::{AllowAllFilter, DedupFilter, DenyAllFilter, FilterChain};