Skip to main content

wabot_feature_mindset/
lib.rs

1//! # wabot-feature-mindset
2//!
3//! Rust port of `wabot-ts/src/feature/mindset`. Provides:
4//!
5//! * The [`Mindset`] trait — what user code implements to describe a
6//!   bot's personality and preferred LLM models. Mirrors `IMindset`.
7//! * The [`MindsetOperator`] — the boring runtime that turns a
8//!   [`Mindset`] + a set of tools into a system prompt and a function
9//!   dispatcher. Mirrors `MindsetOperator`.
10//! * [`MindsetCache`] — opt-in reuse of a mindset's description across
11//!   chats and messages.
12//!
13//! Tools themselves live in [`wabot_feature_tool`], shared with the
14//! agent feature; the `#[tools]` / `#[tool]` macros in `wabot-macros`
15//! generate the per-impl-block plumbing that feeds it.
16//!
17//! ## The shape of a mindset
18//!
19//! [`Mindset::describe`] returns the whole persona in one call, which
20//! is what makes [`MindsetCache`] possible — one `await` to memoize
21//! rather than five independent ones that could each see different
22//! state:
23//!
24//! ```ignore
25//! #[async_trait]
26//! impl Mindset for ElisaMindset {
27//!     async fn describe(&self) -> MindsetDescription {
28//!         MindsetDescription::new(MindsetIdentity::new("Elisa", "spanish"))
29//!             .with_context(self.store.summary().await)
30//!             .with_skills("Answer questions about orders.")
31//!     }
32//!     async fn models(&self) -> MindsetModels {
33//!         MindsetModels::new().with(ModelKind::Llm, vec![MindsetModelRef::new("claude-opus-5")])
34//!     }
35//! }
36//! ```
37
38use std::collections::{HashMap, HashSet};
39use std::sync::Arc;
40
41use async_trait::async_trait;
42use serde::{Deserialize, Serialize};
43use tokio::sync::OnceCell;
44use wabot_core::injection::{Container, IsSingleton};
45
46pub mod agents;
47pub mod cache;
48
49pub use agents::{
50    mindset_agent_tools_provider, register_mindset_agent_tools_provider,
51    DynMindsetAgentToolsProvider, MindsetAgentBinding, MindsetAgentTools,
52    MindsetAgentToolsProvider,
53};
54pub use cache::{LoadedMindset, MindsetCache, MindsetCacheConfig};
55
56pub use wabot_feature_tool::{
57    normalize_optional_arguments, parse_tool_arguments, ToolDefinition, ToolError, ToolGate,
58    ToolInvokeFn, ToolInvoker, ToolParameter, ToolSchema,
59};
60
61/// The tool schema an adapter ships to the model. Alias of
62/// [`ToolSchema`], which mindsets and agents share — same relationship
63/// `IMindsetTool` has to `IToolSchema` in TS.
64pub type MindsetTool = ToolSchema;
65/// Alias of [`ToolParameter`].
66pub type MindsetToolParameter = ToolParameter;
67/// Alias of [`ToolDefinition`], what `#[tools]` emits per method.
68pub type MindsetToolDefinition = ToolDefinition;
69/// Alias of [`ToolError`].
70pub type MindsetError = ToolError;
71
72/// Per-bot identity. Mirrors `IMindsetIdentity` in TS.
73#[derive(Debug, Clone, Default, Serialize, Deserialize)]
74pub struct MindsetIdentity {
75    pub name: String,
76    pub language: String,
77    #[serde(skip_serializing_if = "Option::is_none")]
78    pub personality: Option<String>,
79    #[serde(skip_serializing_if = "Option::is_none")]
80    pub emotions: Option<String>,
81}
82
83impl MindsetIdentity {
84    pub fn new(name: impl Into<String>, language: impl Into<String>) -> Self {
85        Self {
86            name: name.into(),
87            language: language.into(),
88            personality: None,
89            emotions: None,
90        }
91    }
92
93    pub fn with_personality(mut self, personality: impl Into<String>) -> Self {
94        self.personality = Some(personality.into());
95        self
96    }
97
98    pub fn with_emotions(mut self, emotions: impl Into<String>) -> Self {
99        self.emotions = Some(emotions.into());
100        self
101    }
102}
103
104/// Everything a mindset says about itself. Mirrors
105/// `IMindsetDescription`.
106///
107/// One value rather than five trait methods: the operator loads a
108/// persona in a single step, so it can memoize it (see
109/// [`MindsetCache`]) and can't observe a half-updated one.
110#[derive(Debug, Clone, Default, Serialize, Deserialize)]
111pub struct MindsetDescription {
112    pub identity: MindsetIdentity,
113    pub context: String,
114    pub skills: String,
115    pub limits: String,
116    pub workflow: String,
117}
118
119impl MindsetDescription {
120    pub fn new(identity: MindsetIdentity) -> Self {
121        Self {
122            identity,
123            ..Default::default()
124        }
125    }
126
127    pub fn with_context(mut self, context: impl Into<String>) -> Self {
128        self.context = context.into();
129        self
130    }
131
132    pub fn with_skills(mut self, skills: impl Into<String>) -> Self {
133        self.skills = skills.into();
134        self
135    }
136
137    pub fn with_limits(mut self, limits: impl Into<String>) -> Self {
138        self.limits = limits.into();
139        self
140    }
141
142    pub fn with_workflow(mut self, workflow: impl Into<String>) -> Self {
143        self.workflow = workflow.into();
144        self
145    }
146}
147
148/// Modality of an LLM the mindset can request. Mirrors
149/// `IMindsetModelKind`. The operator falls back to `Llm` for
150/// `VisionLlm`/`AudioLlm` when the mindset hasn't supplied a more
151/// specific model — matches the TS `MODEL_KIND_FALLBACK` table.
152#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
153pub enum ModelKind {
154    Llm,
155    VisionLlm,
156    AudioLlm,
157    SpeechToText,
158    TextToSpeech,
159    ImageGen,
160    Embedding,
161}
162
163/// Lightweight model identifier — same fields as `IMindsetModelRef`.
164#[derive(Debug, Clone, Serialize, Deserialize)]
165pub struct MindsetModelRef {
166    #[serde(skip_serializing_if = "Option::is_none")]
167    pub provider: Option<String>,
168    pub model: String,
169}
170
171impl MindsetModelRef {
172    pub fn new(model: impl Into<String>) -> Self {
173        Self {
174            provider: None,
175            model: model.into(),
176        }
177    }
178    pub fn with_provider(mut self, provider: impl Into<String>) -> Self {
179        self.provider = Some(provider.into());
180        self
181    }
182}
183
184/// Models grouped by kind. `Default` returns an empty set.
185#[derive(Debug, Clone, Default)]
186pub struct MindsetModels {
187    map: HashMap<ModelKind, Vec<MindsetModelRef>>,
188}
189
190impl MindsetModels {
191    pub fn new() -> Self {
192        Self::default()
193    }
194    pub fn with(mut self, kind: ModelKind, refs: Vec<MindsetModelRef>) -> Self {
195        self.map.insert(kind, refs);
196        self
197    }
198    pub fn get(&self, kind: ModelKind) -> Option<&[MindsetModelRef]> {
199        self.map.get(&kind).map(|v| v.as_slice())
200    }
201}
202
203/// What user mindsets implement. Mirrors `IMindset`: a persona
204/// ([`Mindset::describe`]) and the models to run it on
205/// ([`Mindset::models`]).
206#[async_trait]
207pub trait Mindset: Send + Sync {
208    /// Identity, context, skills, limits and workflow — the whole
209    /// persona in one call.
210    async fn describe(&self) -> MindsetDescription;
211
212    /// Models per modality. Empty means the app must supply them
213    /// another way; [`MindsetOperator::resolve_models`] will report
214    /// none.
215    async fn models(&self) -> MindsetModels {
216        MindsetModels::new()
217    }
218
219    /// Opt into caching this mindset's description process-wide.
220    ///
221    /// The Rust stand-in for TS's `@mindset({ cache })`. Only enable
222    /// it when the persona is static — a `describe()` that reads
223    /// per-chat state would otherwise serve one chat's context to
224    /// every other chat.
225    fn cache(&self) -> Option<MindsetCacheConfig> {
226        None
227    }
228
229    /// Cache identity. Defaults to the implementing type's name,
230    /// which is what makes the cache per-mindset-class like TS's,
231    /// with nothing for an implementor to remember.
232    fn cache_key(&self) -> &'static str {
233        std::any::type_name::<Self>()
234    }
235}
236
237/// The mindset-driven runtime that `ChatBot` consumes.
238///
239/// ```ignore
240/// let operator = MindsetOperator::new(container.clone(), Arc::new(ElisaMindset))
241///     .with_module_tools(OrderTools::register_tools(&container))
242///     .with_agents(vec![agent_binding::<RefundAgent>().allow(["quote_refund"])]);
243/// ```
244pub struct MindsetOperator {
245    mindset: Arc<dyn Mindset>,
246    container: Container,
247    invoker: ToolInvoker,
248    agent_tools: Option<Arc<dyn MindsetAgentTools>>,
249    cache: Option<Arc<MindsetCache>>,
250    cache_config: Option<MindsetCacheConfig>,
251    /// Per-operator memo, so a message's many model round-trips load
252    /// the persona once even when the process-wide cache is off.
253    loaded: OnceCell<LoadedMindset>,
254}
255
256impl MindsetOperator {
257    pub fn new(container: Container, mindset: Arc<dyn Mindset>) -> Self {
258        let cache_config = mindset.cache();
259        // Only touch the cache when the mindset opted in — an app that
260        // never caches never registers or builds one.
261        let cache = cache_config.map(|_| {
262            if !container.is_registered::<MindsetCache>() {
263                MindsetCache::register_in(&container);
264            }
265            container.resolve::<MindsetCache>()
266        });
267        Self {
268            mindset,
269            invoker: ToolInvoker::new(container.clone(), Vec::new()),
270            container,
271            agent_tools: None,
272            cache,
273            cache_config,
274            loaded: OnceCell::new(),
275        }
276    }
277
278    /// Add every tool a `#[tools]` impl block exposes. Equivalent to
279    /// listing the class in `@mindset({ tools: [OrderTools] })`.
280    pub fn with_module_tools(mut self, tools: Vec<ToolDefinition>) -> Self {
281        let mut all: Vec<ToolDefinition> = self.invoker.all().to_vec();
282        all.extend(tools);
283        self.invoker = ToolInvoker::new(self.container.clone(), all).with_gate(self.gate().clone());
284        self
285    }
286
287    /// Restrict which tools this mindset may reach.
288    pub fn with_gate(mut self, gate: ToolGate) -> Self {
289        let tools: Vec<ToolDefinition> = self.invoker.all().to_vec();
290        self.invoker = ToolInvoker::new(self.container.clone(), tools).with_gate(gate);
291        self
292    }
293
294    /// Let the mindset delegate to agents. Each binding becomes a
295    /// callable tool; invoking it runs an isolated agent session whose
296    /// reply feeds back into the chat loop.
297    ///
298    /// # Panics
299    ///
300    /// If no agent-tools provider is registered. Declaring agents means
301    /// the app depends on the agent feature, so a missing provider is a
302    /// wiring bug to surface at startup — same reason the container
303    /// panics on an unregistered type.
304    pub fn with_agents(mut self, bindings: Vec<MindsetAgentBinding>) -> Self {
305        if bindings.is_empty() {
306            return self;
307        }
308        let provider = mindset_agent_tools_provider(&self.container).expect(
309            "a mindset declared agents but no agent-tools provider is registered; \
310             call wabot_feature_agent::register_agents(&container) during setup",
311        );
312        // Reserve the mindset's own tool names so a delegation tool can
313        // never shadow a real one.
314        let reserved: HashSet<String> = self
315            .invoker
316            .all()
317            .iter()
318            .map(|t| t.name.to_string())
319            .collect();
320        self.agent_tools = Some(provider.create(bindings, &self.container, &reserved));
321        self
322    }
323
324    pub fn mindset(&self) -> &Arc<dyn Mindset> {
325        &self.mindset
326    }
327    pub fn container(&self) -> &Container {
328        &self.container
329    }
330    fn gate(&self) -> &ToolGate {
331        self.invoker.gate()
332    }
333
334    /// Load the persona + models, memoized per operator and — when the
335    /// mindset opted in — reused process-wide through
336    /// [`MindsetCache`], honouring `revalidate`.
337    async fn load(&self) -> &LoadedMindset {
338        self.loaded
339            .get_or_init(|| async {
340                let key = self.mindset.cache_key();
341                if let (Some(cache), Some(config)) = (&self.cache, &self.cache_config) {
342                    if let Some(hit) = cache.get(key) {
343                        if !hit.is_stale(config) {
344                            return hit;
345                        }
346                    }
347                }
348                let (description, models) =
349                    tokio::join!(self.mindset.describe(), self.mindset.models());
350                let loaded = LoadedMindset {
351                    description: Arc::new(description),
352                    models: Arc::new(models),
353                    generated_at: std::time::Instant::now(),
354                };
355                if let Some(cache) = &self.cache {
356                    cache.set(key, loaded.clone());
357                }
358                loaded
359            })
360            .await
361    }
362
363    /// The whole persona, as the operator sees it.
364    pub async fn describe(&self) -> Arc<MindsetDescription> {
365        self.load().await.description.clone()
366    }
367
368    pub async fn identity(&self) -> MindsetIdentity {
369        self.load().await.description.identity.clone()
370    }
371
372    pub async fn models(&self) -> Arc<MindsetModels> {
373        self.load().await.models.clone()
374    }
375
376    /// Resolve models for `kind`, falling back to `Llm` for the
377    /// vision/audio variants when no specific model is configured.
378    /// Matches TS's `MODEL_KIND_FALLBACK`.
379    pub async fn resolve_models(&self, kind: ModelKind) -> Vec<MindsetModelRef> {
380        let models = self.models().await;
381        if let Some(refs) = models.get(kind) {
382            if !refs.is_empty() {
383                return refs.to_vec();
384            }
385        }
386        if matches!(kind, ModelKind::VisionLlm | ModelKind::AudioLlm) {
387            if let Some(refs) = models.get(ModelKind::Llm) {
388                return refs.to_vec();
389            }
390        }
391        Vec::new()
392    }
393
394    /// Build the LLM-facing system prompt. Same template as
395    /// `MindsetOperator.systemPrompt` in TS — strips `#` from
396    /// user-supplied strings so they can't open markdown sections of
397    /// their own.
398    pub async fn system_prompt(&self) -> String {
399        let description = self.describe().await;
400        let identity = &description.identity;
401
402        let language = identity.language.replace('#', " ");
403        let name = identity.name.replace('#', " ");
404        let personality = identity
405            .personality
406            .as_deref()
407            .map(|p| p.replace('#', " "))
408            .filter(|p| !p.is_empty());
409        let context = description.context.replace('#', " ");
410        let skills = description.skills.replace('#', " ");
411        let limits = description.limits.replace('#', " ");
412        let workflow = description.workflow.replace('#', " ");
413        let personality_block = personality
414            .map(|p| format!("## Personality (in your main language)\n{p}"))
415            .unwrap_or_default();
416        format!(
417            "# System Instructions\n\
418             you should act as a assistant.\n\
419             your main language is {language}.\n\
420             your name is {name}.\n\n\
421             {personality_block}\n\n\
422             ## Context (in your main language)\n{context}\n\n\
423             ## Skills (in your main language)\n{skills}\n\n\
424             ## Workflow (in your main language)\n{workflow}\n\n\
425             ## System limitations (in your main language)\n{limits}\n\n\
426             ## Chat memory\n\
427             Next you will receive a chat history, you should use this \
428             information to answer the user."
429        )
430    }
431
432    /// The tool list shipped to the LLM: the mindset's own tools plus
433    /// any agent delegations.
434    ///
435    /// Errors when two exposed tools share a name — the model can't
436    /// disambiguate them and dispatch would silently pick one.
437    pub fn tools(&self) -> Result<Vec<MindsetTool>, ToolError> {
438        let mut schemas = self.invoker.schema()?;
439        if let Some(agent_tools) = &self.agent_tools {
440            schemas.extend(agent_tools.schema());
441        }
442        Ok(schemas)
443    }
444
445    /// Dispatch one function call from the model, agent delegations
446    /// included.
447    pub async fn call_function(&self, name: &str, args_json: &str) -> Result<String, ToolError> {
448        if let Some(agent_tools) = &self.agent_tools {
449            if agent_tools.has(name) {
450                return agent_tools.call(name, args_json).await;
451            }
452        }
453        self.invoker.call(name, args_json).await
454    }
455}
456
457#[cfg(test)]
458mod tests;