Skip to main content

tea_kernel/
request.rs

1use tea_model::{ModelRequest, ModelSpec, ReasoningOptions};
2use tea_session::MaterializedSessionState;
3use tea_tools::{ToolName, ToolRegistry};
4
5use crate::{KernelError, KernelErrorCode, KernelRunConfig};
6
7/// Immutable model request plus the durable tail used to construct it.
8#[derive(Debug, Clone, PartialEq)]
9pub struct TurnRequestSnapshot {
10    request: ModelRequest,
11    client_tool_names: Vec<ToolName>,
12    hosted_tool_names: Vec<ToolName>,
13    durable_tail: tea_protocol::SessionSequence,
14}
15
16impl TurnRequestSnapshot {
17    /// Builds and validates one immutable request from committed session state.
18    ///
19    /// Registered tool specifications are projected in canonical name order and
20    /// parallel calls remain disabled for the sequential milestone scheduler.
21    ///
22    /// # Errors
23    ///
24    /// Returns a typed error when no model is selected, the provider does not
25    /// advertise it, or model/tool/request bounds are incompatible.
26    pub fn build(
27        state: &MaterializedSessionState,
28        config: &KernelRunConfig,
29        tools: &ToolRegistry,
30        model: &ModelSpec,
31    ) -> Result<Self, KernelError> {
32        let model_ref = state.configuration().model_ref().ok_or_else(|| {
33            KernelError::new(KernelErrorCode::InvalidModel, "session has no active model")
34        })?;
35        if model.model_ref() != model_ref {
36            return Err(KernelError::new(
37                KernelErrorCode::InvalidModel,
38                "resolved model does not match the active session model",
39            ));
40        }
41        let definitions = tools.model_definitions(model).map_err(|error| {
42            KernelError::new(KernelErrorCode::InvalidRequest, error.to_string())
43        })?;
44        let mut client_tool_names = Vec::new();
45        let mut hosted_tool_names = Vec::new();
46        for (name, definition) in tools.names().zip(&definitions) {
47            if definition.as_function().is_some() {
48                client_tool_names.push(name.clone());
49            } else if definition.as_hosted().is_some() {
50                hosted_tool_names.push(name.clone());
51            }
52        }
53        let mut request =
54            ModelRequest::new(model_ref.model_id().clone(), state.messages().to_vec())?
55                .with_tools(definitions, false)?
56                .with_metadata(config.request_metadata().clone());
57        if let (Some(requested), Some(profile)) = (
58            state.configuration().reasoning_effort(),
59            model.reasoning_profile(),
60        ) {
61            let effective = profile.resolve(requested).effective();
62            request = request.with_reasoning(ReasoningOptions::new(effective));
63        }
64        if let Some(prompt) = config.system_prompt() {
65            request = request.with_system_prompt(prompt)?;
66        }
67        request.validate_for(model)?;
68        Ok(Self {
69            request,
70            client_tool_names,
71            hosted_tool_names,
72            durable_tail: state.tail_sequence(),
73        })
74    }
75
76    /// Returns the immutable provider request.
77    #[must_use]
78    pub const fn request(&self) -> &ModelRequest {
79        &self.request
80    }
81
82    /// Returns the exact client-executable function names frozen for this turn.
83    ///
84    /// Active hosted projections are deliberately absent even when their
85    /// portable tool specifications also have a client route.
86    #[must_use]
87    pub fn client_tool_names(&self) -> &[ToolName] {
88        &self.client_tool_names
89    }
90
91    /// Returns the exact provider-hosted tool names frozen for this turn.
92    #[must_use]
93    pub fn hosted_tool_names(&self) -> &[ToolName] {
94        &self.hosted_tool_names
95    }
96
97    /// Returns whether a provider function call may enter local execution.
98    #[must_use]
99    pub fn allows_client_tool_call(&self, tool_name: &str) -> bool {
100        self.client_tool_names
101            .iter()
102            .any(|name| name.as_str() == tool_name)
103    }
104
105    /// Returns whether this name was projected as a provider-hosted tool.
106    #[must_use]
107    pub fn is_hosted_tool_projection(&self, tool_name: &str) -> bool {
108        self.hosted_tool_names
109            .iter()
110            .any(|name| name.as_str() == tool_name)
111    }
112
113    /// Consumes the snapshot into its provider request.
114    #[must_use]
115    pub fn into_request(self) -> ModelRequest {
116        self.request
117    }
118
119    /// Returns the durable session tail captured with the request.
120    #[must_use]
121    pub const fn durable_tail(&self) -> tea_protocol::SessionSequence {
122        self.durable_tail
123    }
124}
125
126impl From<tea_model::ModelRequestError> for KernelError {
127    fn from(error: tea_model::ModelRequestError) -> Self {
128        Self::new(KernelErrorCode::InvalidRequest, error.to_string())
129    }
130}