Skip to main content

lash_core/session_model/
mod.rs

1pub mod context;
2pub use lash_sansio::session_model::message;
3pub use lash_sansio::session_model::prompt;
4
5use std::sync::Arc;
6use tokio::sync::mpsc;
7
8use crate::ModelSpec;
9use crate::llm::types::{LlmEventSender, LlmStreamEvent};
10use crate::plugin::PluginMessage;
11use crate::provider::{ProviderBinding, ProviderHandle, ProviderResolutionError};
12
13pub use lash_sansio::format_tool_output_content;
14pub use lash_sansio::session_model::{
15    ConversationRecord, ErrorEnvelope, MAIN_AGENT_INTRO, Message, MessageRole, Part, PartKind,
16    PromptBuiltin, PromptSlot, PromptTemplate, PromptTemplateEntry, PromptTemplateSection,
17    ProtocolEvent, PruneState, SessionStreamEvent, TokenUsage, TurnTerminationPolicyState,
18    default_prompt_template, make_error_envelope, make_error_event, reassign_part_ids,
19    render_prompt, render_transcript_prompt, shared_parts,
20};
21
22pub fn fresh_message_id() -> String {
23    format!("m{}", uuid::Uuid::new_v4().simple())
24}
25
26pub type SessionHistoryRecord = lash_sansio::session_model::SessionHistoryRecord<ProtocolEvent>;
27
28pub const PLUGIN_RUNTIME_PROTOCOL_PLUGIN_ID: &str = "lash.plugin_runtime";
29
30#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
31pub struct PersistedPluginRuntimeEvent {
32    pub plugin_id: String,
33    pub event: crate::PluginRuntimeEvent,
34}
35
36pub fn plugin_runtime_protocol_event(
37    plugin_id: impl Into<String>,
38    event: crate::PluginRuntimeEvent,
39) -> Result<ProtocolEvent, serde_json::Error> {
40    ProtocolEvent::typed(
41        PLUGIN_RUNTIME_PROTOCOL_PLUGIN_ID,
42        PersistedPluginRuntimeEvent {
43            plugin_id: plugin_id.into(),
44            event,
45        },
46    )
47}
48
49pub fn plugin_runtime_event_from_protocol(
50    event: &ProtocolEvent,
51) -> Result<Option<PersistedPluginRuntimeEvent>, serde_json::Error> {
52    event.decode(PLUGIN_RUNTIME_PROTOCOL_PLUGIN_ID)
53}
54
55/// Send an event to the channel if it's still open.
56pub(crate) async fn send_event(tx: &mpsc::Sender<SessionStreamEvent>, event: SessionStreamEvent) {
57    if !tx.is_closed() {
58        let _ = tx.send(event).await;
59    }
60}
61
62pub(crate) fn plugin_message_to_message(plugin_message: &PluginMessage) -> Message {
63    let message_id = plugin_message
64        .id
65        .as_deref()
66        .filter(|id| !id.is_empty())
67        .map(str::to_string)
68        .unwrap_or_else(fresh_message_id);
69    let mut parts = if plugin_message.parts.is_empty() {
70        vec![Part {
71            id: format!("{message_id}.p0"),
72            kind: PartKind::Text,
73            content: plugin_message.content.clone(),
74            attachment: None,
75            tool_call_id: None,
76            tool_name: None,
77            tool_replay: None,
78            prune_state: PruneState::Intact,
79            reasoning_meta: None,
80            response_meta: None,
81        }]
82    } else {
83        plugin_message.parts.clone()
84    };
85    reassign_part_ids(&message_id, &mut parts);
86    Message {
87        id: message_id,
88        role: plugin_message.role,
89        parts: Arc::new(parts),
90        origin: plugin_message.origin.clone().or_else(|| {
91            Some(crate::MessageOrigin::Plugin {
92                plugin_id: "plugin".to_string(),
93                transient: false,
94            })
95        }),
96    }
97}
98
99#[derive(Clone, Debug, Default, PartialEq, Eq)]
100pub struct SessionPolicy {
101    pub model: ModelSpec,
102    pub provider_id: String,
103    pub session_id: Option<String>,
104    pub autonomous: bool,
105    pub max_turns: Option<usize>,
106    pub prompt: crate::PromptLayer,
107}
108
109impl SessionPolicy {
110    pub fn recorded_provider_id(&self) -> &str {
111        self.provider_id.trim()
112    }
113
114    pub fn model_id(&self) -> &str {
115        &self.model.id
116    }
117
118    pub fn model_variant(&self) -> &crate::ReasoningSelection {
119        &self.model.variant
120    }
121
122    pub fn context_window_tokens(&self) -> usize {
123        self.model.context_window_tokens()
124    }
125}
126
127impl serde::Serialize for SessionPolicy {
128    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
129    where
130        S: serde::Serializer,
131    {
132        use serde::ser::SerializeStruct;
133
134        let mut fields = 5;
135        if !self.prompt.is_empty() {
136            fields += 1;
137        }
138        let mut state = serializer.serialize_struct("SessionPolicy", fields)?;
139        state.serialize_field("model", &self.model)?;
140        state.serialize_field("provider_id", self.recorded_provider_id())?;
141        state.serialize_field("session_id", &self.session_id)?;
142        state.serialize_field("autonomous", &self.autonomous)?;
143        state.serialize_field("max_turns", &self.max_turns)?;
144        if !self.prompt.is_empty() {
145            state.serialize_field("prompt", &self.prompt)?;
146        }
147        state.end()
148    }
149}
150
151impl<'de> serde::Deserialize<'de> for SessionPolicy {
152    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
153    where
154        D: serde::Deserializer<'de>,
155    {
156        #[derive(serde::Deserialize)]
157        #[serde(deny_unknown_fields)]
158        struct Wire {
159            #[serde(default)]
160            model: ModelSpec,
161            #[serde(default)]
162            provider_id: String,
163            #[serde(default)]
164            session_id: Option<String>,
165            #[serde(default)]
166            autonomous: bool,
167            #[serde(default)]
168            max_turns: Option<usize>,
169            #[serde(default)]
170            prompt: crate::PromptLayer,
171        }
172
173        let value = serde_json::Value::deserialize(deserializer)?;
174        if value
175            .as_object()
176            .is_some_and(|object| object.contains_key("provider"))
177        {
178            return Err(serde::de::Error::custom(
179                "legacy serialized provider config is not supported in session state; persist provider_id only",
180            ));
181        }
182        let wire = Wire::deserialize(value).map_err(serde::de::Error::custom)?;
183        Ok(Self {
184            model: wire.model,
185            provider_id: wire.provider_id,
186            session_id: wire.session_id,
187            autonomous: wire.autonomous,
188            max_turns: wire.max_turns,
189            prompt: wire.prompt,
190        })
191    }
192}
193
194/// Runtime-only policy resolved against host-owned live dependencies.
195#[derive(Clone, Debug, Default, PartialEq, Eq)]
196pub struct RuntimeSessionPolicy {
197    pub policy: SessionPolicy,
198    pub binding: ProviderBinding,
199}
200
201impl RuntimeSessionPolicy {
202    pub fn new(policy: SessionPolicy, binding: ProviderBinding) -> Self {
203        Self { policy, binding }
204    }
205
206    pub fn from_provider(
207        policy: SessionPolicy,
208        provider: ProviderHandle,
209    ) -> Result<Self, ProviderResolutionError> {
210        let binding = ProviderBinding::new(policy.recorded_provider_id(), provider)?;
211        Ok(Self { policy, binding })
212    }
213
214    pub fn provider(&self) -> &ProviderHandle {
215        &self.binding.provider
216    }
217
218    pub fn into_policy(self) -> SessionPolicy {
219        self.policy
220    }
221}
222
223impl std::ops::Deref for RuntimeSessionPolicy {
224    type Target = SessionPolicy;
225
226    fn deref(&self) -> &Self::Target {
227        &self.policy
228    }
229}
230
231impl std::ops::DerefMut for RuntimeSessionPolicy {
232    fn deref_mut(&mut self) -> &mut Self::Target {
233        &mut self.policy
234    }
235}
236
237/// Reusable session configuration overlay.
238///
239/// `SessionSpec` is the public configuration shape for callers that want to
240/// describe either a root session or a child session without constructing the
241/// persisted [`SessionPolicy`] directly.
242#[derive(Clone, Debug, PartialEq, Eq)]
243pub struct SessionSpec {
244    inherit: bool,
245    pub provider_id: Option<String>,
246    pub model: Option<ModelSpec>,
247    pub max_turns: Option<Option<usize>>,
248    pub prompt: Option<crate::PromptLayer>,
249}
250
251impl SessionSpec {
252    /// Create an explicit root-style spec. Unset fields resolve from the
253    /// runtime's core defaults.
254    pub fn new() -> Self {
255        Self {
256            inherit: false,
257            provider_id: None,
258            model: None,
259            max_turns: None,
260            prompt: None,
261        }
262    }
263
264    /// Create a parent-relative spec. Unset fields inherit from the live
265    /// parent policy at resolution time.
266    pub fn inherit() -> Self {
267        Self {
268            inherit: true,
269            ..Self::new()
270        }
271    }
272
273    pub fn inherits(&self) -> bool {
274        self.inherit
275    }
276
277    pub fn provider_id(mut self, provider_id: impl Into<String>) -> Self {
278        self.provider_id = Some(provider_id.into());
279        self
280    }
281
282    pub fn model(mut self, model: ModelSpec) -> Self {
283        self.model = Some(model);
284        self
285    }
286
287    pub fn max_turns(mut self, max_turns: usize) -> Self {
288        self.max_turns = Some(Some(max_turns));
289        self
290    }
291
292    pub fn clear_max_turns(mut self) -> Self {
293        self.max_turns = Some(None);
294        self
295    }
296
297    pub fn prompt_layer(mut self, prompt: crate::PromptLayer) -> Self {
298        self.prompt = Some(prompt);
299        self
300    }
301
302    pub fn resolve_against(&self, base: &SessionPolicy) -> SessionPolicy {
303        let mut policy = base.clone();
304        if let Some(provider_id) = self.provider_id.as_ref() {
305            policy.provider_id = provider_id.clone();
306        }
307        if let Some(model) = self.model.as_ref() {
308            policy.model = model.clone();
309        }
310        if let Some(max_turns) = self.max_turns {
311            policy.max_turns = max_turns;
312        }
313        if let Some(prompt) = self.prompt.as_ref() {
314            policy.prompt = prompt.clone();
315        }
316        policy
317    }
318}
319
320impl Default for SessionSpec {
321    fn default() -> Self {
322        Self::new()
323    }
324}
325
326pub(crate) fn transport_stream_events(
327    provider: &ProviderHandle,
328    requested: Option<tokio::sync::mpsc::UnboundedSender<LlmStreamEvent>>,
329) -> Option<LlmEventSender> {
330    if let Some(requested) = requested {
331        return Some(make_stream_event_sender(requested));
332    }
333
334    if provider.requires_streaming() {
335        let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<LlmStreamEvent>();
336        drop(rx);
337        Some(make_stream_event_sender(tx))
338    } else {
339        None
340    }
341}
342
343fn make_stream_event_sender(
344    tx: tokio::sync::mpsc::UnboundedSender<LlmStreamEvent>,
345) -> LlmEventSender {
346    LlmEventSender::new(move |event| {
347        let _ = tx.send(event);
348    })
349}
350
351#[cfg(test)]
352mod tests {
353    use super::*;
354
355    #[test]
356    fn protocol_event_writes_tagged_payload() {
357        let event = ProtocolEvent::typed("test_protocol", serde_json::json!({ "value": 42 }))
358            .expect("typed event");
359        let serialized = serde_json::to_value(event).expect("serialize");
360        assert_eq!(serialized["plugin_id"], "test_protocol");
361        assert!(serialized.get("payload").is_some());
362    }
363
364    #[test]
365    fn session_policy_rejects_legacy_provider_config() {
366        let err = serde_json::from_value::<SessionPolicy>(serde_json::json!({
367            "model": {},
368            "provider": {
369                "type": "openai",
370                "api_key": "must-not-load"
371            }
372        }))
373        .expect_err("legacy provider config must fail");
374
375        assert!(
376            err.to_string()
377                .contains("legacy serialized provider config is not supported")
378        );
379    }
380
381    #[test]
382    fn session_policy_serializes_provider_id_without_provider_handle() {
383        let policy = SessionPolicy {
384            provider_id: "mock-provider".to_string(),
385            model: ModelSpec::from_token_limits("mock-model", Default::default(), 200_000, None)
386                .expect("valid test model"),
387            ..SessionPolicy::default()
388        };
389
390        let value = serde_json::to_value(&policy).expect("serialize policy");
391
392        assert_eq!(value["provider_id"], "mock-provider");
393        assert!(value.get("provider").is_none());
394    }
395}