//! Optional execution components over the Causa material kernel.
//!
//! [`TurnRunner`] owns only a gateway and [`ToolExecutor`]. Each run consumes
//! a context and returns it in [`TurnOutcome`], with any uncommitted tool batch.
//! Model identity, generation, limits, optional preparation and observation
//! are explicit per-run choices. Both entry points share the same loop.
//!
//! [`ToolExecutor::bind`] fixes the actual tool surface and targets before
//! preparation. When the bound tools differ from the context's tool state, the
//! runner appends one [`causa_kernel::ToolChange`] block (the first round of a
//! context without tool facts appends the declaration), so the context records
//! which tools the model saw when. The prepared frame must still add up to the
//! bound tools; otherwise the round stops with
//! [`TurnInterruption::PrepareFailed`]. Processing owns controlled collection
//! of started calls; the runner validates and atomically appends results only
//! after success.
//! Unknown results are committed and stop further model rounds.
//!
//! # Policy surface
//!
//! | Choice | Default and owner |
//! |---|---|
//! | Model rounds / tool declarations | [`TurnLimits`]: 10 / 64 |
//! | Model retries | None; optional [`RetryingGateway`] around the chosen gateway |
//! | Material preparation | None; use the current context frame |
//! | Tool changes | Appended to the context after each bind that changes the bound tools; a prepared frame that drops them fails the round |
//! | Observation | None; an optional synchronous borrowed callback |
//! | Tool processing | Executor-owned ordered before/after processors |
//! | Tool metadata | Carried from each tool or source to processors at bind time via [`ToolMetadata`](causa_kernel::ToolMetadata), never interpreted, rendered or stored in the context |
//! | Call attachments | None by default; ephemeral [`CallAttachments`](causa_kernel::CallAttachments) attached to pending calls in before-processors, handed read-only to tool execution, and cleared on resolution, never persisted or sent to models |
//! | Processor data | None; optional host value in [`TurnRunOptions::processor_data`], passed to every processor unchanged and never inspected |
//! | 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 |
//! | 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 |
//! | 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` |
//! | 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 |
//! | 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)) |
//! | 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` |
//! | Stop after a batch finished processing | Commit its results, then report the stop |
//! | Output retention and persistence | Caller-owned policies and storage |
//!
//! # Optional retries
//!
//! Retries are off by default: the runner makes one logical gateway call per
//! round and the first error ends it. A host that wants bounded retries wraps
//! its gateway in [`RetryingGateway`] with a [`RetryPolicy`]. The wrapper
//! is an ordinary [`causa_kernel::ModelGateway`]: every attempt sends the
//! same request, only `Transient` and `TimedOut` failures are retried, waits
//! stay inside the caller's cancellation and deadline, and the call is never
//! retried once any stream delta has been yielded. Only the final error
//! reaches the runner.
//!
//! The runner does not interpret imported tool declarations as work to resume.
//! It creates work only from the current model output. Session admission,
//! history, input queues, retries, budget strategies and observation storage
//! belong to callers. Dropping a run future or panicking bypasses the normal
//! material-return guarantee; stopping local waits cannot undo remote effects.
//!
//! # Target path of one model call
//!
//! ```text
//! host
//! TurnRunner (causa-runtime), per round:
//! ToolExecutor::bind -> ToolSurface
//! commit ToolChange when the bound tools differ from the context's
//! ContextPreparer (host, opt.) -> ContextFrame; its tool state must equal the surface
//! build ModelRequest { invocation_id, frame, model, generation, cache }
//! ModelGateway::invoke | stream <- contract, causa-kernel
//! [optional] retry wrapper (causa-runtime) same request each attempt; waits
//! retry_delay or backs off; never
//! retries after a delta was yielded
//! HTTP gateway (causa-provider)
//! MediaResolver -> MediaSet
//! render (causa-protocol) frame -> wire JSON; rejects unsupported
//! generation options before any HTTP
//! send (reqwest), raced against CallControl
//! status / headers -> ModelInvokeErrorKind, retry_delay
//! parse | StreamDecoder (causa-protocol) wire -> ModelOutput, one stop
//! mapping per protocol for both entry points
//! <- ModelOutput { response, usage, stop_reason, raw_stop_reason, reasoning }
//! stop policy: continue on EndTurn / ToolUse; any other reason returns an
//! interruption that carries the uncommitted output
//! commit: ModelResponse::to_blocks -> Context
//! ```
//!
//! Ownership by layer: the kernel defines the shapes and the trait; the
//! protocol crate owns every wire rule; the provider crate owns HTTP and the
//! classification of HTTP outcomes; the runtime owns ordering, stop policy and
//! the optional retry; the host owns preparation, limits and persistence.
#![deny(unsafe_code)]
#![deny(missing_docs)]
pub mod composition;
pub mod config;
mod control;
pub mod driver;
pub mod event;
pub mod executor;
pub mod ids;
mod processors;
mod retry;
pub use composition::ToolBridge;
pub use config::{TurnLimits, TurnRunOptions};
pub use driver::{TurnInterruption, TurnOutcome, TurnResult, TurnRunner};
pub use event::{RunEvent, RunObserver};
pub use executor::{
BoundTools, ToolCatalogError, ToolExecutor, ToolExecutorOptions, ToolProcessingError,
ToolProcessorPhase, ToolRegistryError,
};
pub use ids::new_block_id;
pub use retry::{RetryPolicy, RetryingGateway};