Skip to main content

causa_runtime/
lib.rs

1//! Optional execution components over the Causa material kernel.
2//!
3//! [`TurnRunner`] owns only a gateway and [`ToolExecutor`]. Each run consumes
4//! a context and returns it in [`TurnOutcome`], with any uncommitted tool batch.
5//! Model identity, generation, limits, optional preparation and observation
6//! are explicit per-run choices. Both entry points share the same loop.
7//!
8//! [`ToolExecutor::bind`] fixes the actual tool surface and targets before
9//! preparation. When the bound tools differ from the context's tool state, the
10//! runner appends one [`causa_kernel::ToolChange`] block (the first round of a
11//! context without tool facts appends the declaration), so the context records
12//! which tools the model saw when. The prepared frame must still add up to the
13//! bound tools; otherwise the round stops with
14//! [`TurnInterruption::PrepareFailed`]. Processing owns controlled collection
15//! of started calls; the runner validates and atomically appends results only
16//! after success.
17//! Unknown results are committed and stop further model rounds.
18//!
19//! # Policy surface
20//!
21//! | Choice | Default and owner |
22//! |---|---|
23//! | Model rounds / tool declarations | [`TurnLimits`]: 10 / 64 |
24//! | Model retries | None; optional [`RetryingGateway`] around the chosen gateway |
25//! | Material preparation | None; use the current context frame |
26//! | Tool changes | Appended to the context after each bind that changes the bound tools; a prepared frame that drops them fails the round |
27//! | Observation | None; an optional synchronous borrowed callback |
28//! | Tool processing | Executor-owned ordered before/after processors |
29//! | Tool hints | Carried from each tool or source to processors at bind time, never interpreted, rendered or stored in the context |
30//! | Processor data | None; optional host value in [`TurnRunOptions::processor_data`], passed to every processor unchanged and never inspected |
31//! | Tool dispatch | Every pending call of a batch at once on the caller's task: concurrent, not parallel, unbounded, nothing spawned; panic becomes failed result |
32//! | Tool result order | The order results arrived in (calls resolved before dispatch first, then completion order); an after-processor sorting [`ToolBatch::results_mut`](causa_kernel::ToolBatch::results_mut) by [`ProcessorContext::declaration_order`](causa_kernel::ProcessorContext::declaration_order) commits them in declaration order |
33//! | Tool result status | Committed exactly as the tool reported it; a tool-reported `Cancelled` or `TimedOut` may carry partial output and does not prove that no side effect happened, while a call whose result was not observed becomes `UnknownOutcome` |
34//! | Tool timeout | None by default; a call deadline records an unknown outcome only if the tool does not return, while a tool-reported `TimedOut` is an ordinary result the batch commits |
35//! | Stopping a tool | At the tool's next yield point; a started call left without a result settles as an unknown outcome, once the executor observes the stop it polls no further so a value returned after that is not recorded, and a tool that blocks the thread is not stopped or timed out (see [`Tool`](causa_kernel::Tool)) |
36//! | Unknown outcomes | Commit the successful batch, then stop; a synthesized result names its cause in `meta.extra.reason`: a control check that fails before the first poll records `call_control_stopped` for cancellation and `call_deadline_backstop` for an expired deadline, the deadline backstop records `call_deadline_backstop`, batch settlement records `batch_stopped`, and a tool-source bridge records `source_timed_out` or `source_cancelled`. When a turn stop and a call deadline arrive together, whichever path is observed first decides between `batch_stopped` and `call_deadline_backstop` |
37//! | Stop after a batch finished processing | Commit its results, then report the stop |
38//! | Output retention and persistence | Caller-owned policies and storage |
39//!
40//! # Optional retries
41//!
42//! Retries are off by default: the runner makes one logical gateway call per
43//! round and the first error ends it. A host that wants bounded retries wraps
44//! its gateway in [`RetryingGateway`] with a [`RetryPolicy`]. The wrapper
45//! is an ordinary [`causa_kernel::ModelGateway`]: every attempt sends the
46//! same request, only `Transient` and `TimedOut` failures are retried, waits
47//! stay inside the caller's cancellation and deadline, and the call is never
48//! retried once any stream delta has been yielded. Only the final error
49//! reaches the runner.
50//!
51//! The runner does not interpret imported tool declarations as work to resume.
52//! It creates work only from the current model output. Session admission,
53//! history, input queues, retries, budget strategies and observation storage
54//! belong to callers. Dropping a run future or panicking bypasses the normal
55//! material-return guarantee; stopping local waits cannot undo remote effects.
56//!
57//! # Target path of one model call
58//!
59//! ```text
60//! host
61//!   TurnRunner (causa-runtime), per round:
62//!     ToolExecutor::bind            -> ToolSurface
63//!     commit ToolChange             when the bound tools differ from the context's
64//!     ContextPreparer (host, opt.)  -> ContextFrame; its tool state must equal the surface
65//!     build ModelRequest { invocation_id, frame, model, generation, cache }
66//!     ModelGateway::invoke | stream                      <- contract, causa-kernel
67//!       [optional] retry wrapper (causa-runtime)         same request each attempt; waits
68//!                                                        retry_delay or backs off; never
69//!                                                        retries after a delta was yielded
70//!         HTTP gateway (causa-provider)
71//!           MediaResolver                 -> MediaSet
72//!           render (causa-protocol)       frame -> wire JSON; rejects unsupported
73//!                                         generation options before any HTTP
74//!           send (reqwest), raced against CallControl
75//!           status / headers              -> ModelInvokeErrorKind, retry_delay
76//!           parse | StreamDecoder (causa-protocol)   wire -> ModelOutput, one stop
77//!                                         mapping per protocol for both entry points
78//!     <- ModelOutput { response, usage, stop_reason, raw_stop_reason, reasoning }
79//!     stop policy: continue on EndTurn / ToolUse; any other reason returns an
80//!                  interruption that carries the uncommitted output
81//!     commit: ModelResponse::to_blocks -> Context
82//! ```
83//!
84//! Ownership by layer: the kernel defines the shapes and the trait; the
85//! protocol crate owns every wire rule; the provider crate owns HTTP and the
86//! classification of HTTP outcomes; the runtime owns ordering, stop policy and
87//! the optional retry; the host owns preparation, limits and persistence.
88
89#![deny(unsafe_code)]
90#![deny(missing_docs)]
91
92pub mod composition;
93pub mod config;
94mod control;
95pub mod driver;
96pub mod event;
97pub mod executor;
98pub mod ids;
99mod processors;
100mod retry;
101
102pub use composition::ToolBridge;
103pub use config::{TurnLimits, TurnRunOptions};
104pub use driver::{TurnInterruption, TurnOutcome, TurnResult, TurnRunner};
105pub use event::{RunEvent, RunObserver};
106pub use executor::{
107    BoundTools, ToolCatalogError, ToolExecutor, ToolExecutorOptions, ToolProcessingError,
108    ToolProcessorPhase, ToolRegistryError,
109};
110pub use ids::new_block_id;
111pub use retry::{RetryPolicy, RetryingGateway};