stakpak_api/local/
mod.rs

1use crate::local::hooks::file_scratchpad_context::{
2    FileScratchpadContextHook, FileScratchpadContextHookOptions,
3};
4// use crate::local::hooks::inline_scratchpad_context::{
5//     InlineScratchpadContextHook, InlineScratchpadContextHookOptions,
6// };
7use crate::{AgentProvider, ApiStreamError, GetMyAccountResponse};
8use crate::{ListRuleBook, models::*};
9use async_trait::async_trait;
10use futures_util::Stream;
11use libsql::{Builder, Connection};
12use reqwest::Error as ReqwestError;
13use reqwest::header::HeaderMap;
14use rmcp::model::Content;
15use stakpak_shared::hooks::{HookContext, HookRegistry, LifecycleEvent};
16use stakpak_shared::models::integrations::anthropic::{AnthropicConfig, AnthropicModel};
17use stakpak_shared::models::integrations::gemini::{GeminiConfig, GeminiModel};
18use stakpak_shared::models::integrations::openai::{
19    AgentModel, ChatCompletionChoice, ChatCompletionResponse, ChatCompletionStreamChoice,
20    ChatCompletionStreamResponse, ChatMessage, FinishReason, MessageContent, OpenAIConfig,
21    OpenAIModel, Role, Tool,
22};
23use stakpak_shared::models::integrations::search_service::*;
24use stakpak_shared::models::llm::{
25    GenerationDelta, LLMInput, LLMMessage, LLMMessageContent, LLMModel, LLMProviderConfig,
26    LLMStreamInput,
27};
28use stakpak_shared::models::stakai_adapter::StakAIClient;
29use stakpak_shared::tls_client::{TlsClientConfig, create_tls_client};
30use std::pin::Pin;
31use std::sync::Arc;
32use tokio::sync::mpsc;
33use uuid::Uuid;
34
35mod context_managers;
36mod db;
37mod hooks;
38
39#[cfg(test)]
40mod tests;
41
42#[derive(Clone, Debug)]
43pub struct LocalClient {
44    pub db: Connection,
45    pub stakpak_base_url: Option<String>,
46    pub anthropic_config: Option<AnthropicConfig>,
47    pub openai_config: Option<OpenAIConfig>,
48    pub gemini_config: Option<GeminiConfig>,
49    pub model_options: ModelOptions,
50    pub hook_registry: Option<Arc<HookRegistry<AgentState>>>,
51    _search_services_orchestrator: Option<Arc<SearchServicesOrchestrator>>,
52}
53
54#[derive(Clone, Debug)]
55pub struct ModelOptions {
56    pub smart_model: Option<LLMModel>,
57    pub eco_model: Option<LLMModel>,
58    pub recovery_model: Option<LLMModel>,
59}
60
61#[derive(Clone, Debug)]
62pub struct ModelSet {
63    pub smart_model: LLMModel,
64    pub eco_model: LLMModel,
65    pub recovery_model: LLMModel,
66    pub hook_registry: Option<Arc<HookRegistry<AgentState>>>,
67    pub _search_services_orchestrator: Option<Arc<SearchServicesOrchestrator>>,
68}
69
70impl ModelSet {
71    fn get_model(&self, agent_model: &AgentModel) -> LLMModel {
72        match agent_model {
73            AgentModel::Smart => self.smart_model.clone(),
74            AgentModel::Eco => self.eco_model.clone(),
75            AgentModel::Recovery => self.recovery_model.clone(),
76        }
77    }
78}
79
80impl From<ModelOptions> for ModelSet {
81    fn from(value: ModelOptions) -> Self {
82        let smart_model = value
83            .smart_model
84            .unwrap_or(LLMModel::Anthropic(AnthropicModel::Claude45Sonnet));
85        let eco_model = value
86            .eco_model
87            .unwrap_or(LLMModel::Anthropic(AnthropicModel::Claude45Haiku));
88        let recovery_model = value
89            .recovery_model
90            .unwrap_or(LLMModel::OpenAI(OpenAIModel::GPT5));
91
92        Self {
93            smart_model,
94            eco_model,
95            recovery_model,
96            hook_registry: None,
97            _search_services_orchestrator: None,
98        }
99    }
100}
101
102pub struct LocalClientConfig {
103    pub stakpak_base_url: Option<String>,
104    pub store_path: Option<String>,
105    pub anthropic_config: Option<AnthropicConfig>,
106    pub openai_config: Option<OpenAIConfig>,
107    pub gemini_config: Option<GeminiConfig>,
108    pub smart_model: Option<String>,
109    pub eco_model: Option<String>,
110    pub recovery_model: Option<String>,
111    pub hook_registry: Option<HookRegistry<AgentState>>,
112}
113
114#[derive(Debug)]
115enum StreamMessage {
116    Delta(GenerationDelta),
117    Ctx(Box<HookContext<AgentState>>),
118}
119
120const DEFAULT_STORE_PATH: &str = ".stakpak/data/local.db";
121const TITLE_GENERATOR_PROMPT: &str = include_str!("./prompts/session_title_generator.v1.txt");
122
123impl LocalClient {
124    pub async fn new(config: LocalClientConfig) -> Result<Self, String> {
125        let store_path = config
126            .store_path
127            .map(std::path::PathBuf::from)
128            .unwrap_or_else(|| {
129                std::env::home_dir()
130                    .unwrap_or_default()
131                    .join(DEFAULT_STORE_PATH)
132            });
133
134        if let Some(parent) = store_path.parent() {
135            std::fs::create_dir_all(parent)
136                .map_err(|e| format!("Failed to create database directory: {}", e))?;
137        }
138
139        let db = Builder::new_local(store_path.display().to_string())
140            .build()
141            .await
142            .map_err(|e| e.to_string())?;
143
144        let conn = db.connect().map_err(|e| e.to_string())?;
145
146        // Initialize database schema
147        db::init_schema(&conn).await?;
148
149        let model_options = ModelOptions {
150            smart_model: config.smart_model.map(LLMModel::from),
151            eco_model: config.eco_model.map(LLMModel::from),
152            recovery_model: config.recovery_model.map(LLMModel::from),
153        };
154
155        // Add hooks
156        let mut hook_registry = config.hook_registry.unwrap_or_default();
157        // hook_registry.register(
158        //     LifecycleEvent::BeforeInference,
159        //     Box::new(InlineScratchpadContextHook::new(
160        //         InlineScratchpadContextHookOptions {
161        //             model_options: model_options.clone(),
162        //             history_action_message_size_limit: Some(100),
163        //             history_action_message_keep_last_n: Some(1),
164        //             history_action_result_keep_last_n: Some(50),
165        //         },
166        //     )),
167        // );
168        hook_registry.register(
169            LifecycleEvent::BeforeInference,
170            Box::new(FileScratchpadContextHook::new(
171                FileScratchpadContextHookOptions {
172                    history_action_message_size_limit: Some(100),
173                    history_action_message_keep_last_n: Some(1),
174                    history_action_result_keep_last_n: Some(50),
175                    scratchpad_path: None,
176                    todo_path: None,
177                    model_options: model_options.clone(),
178                    overwrite_if_different: Some(true),
179                },
180            )),
181        );
182
183        Ok(Self {
184            db: conn,
185            stakpak_base_url: config.stakpak_base_url.map(|url| url + "/v1"),
186            anthropic_config: config.anthropic_config,
187            gemini_config: config.gemini_config,
188            openai_config: config.openai_config,
189            model_options,
190            hook_registry: Some(Arc::new(hook_registry)),
191            _search_services_orchestrator: Some(Arc::new(SearchServicesOrchestrator)),
192        })
193    }
194}
195
196#[async_trait]
197impl AgentProvider for LocalClient {
198    async fn get_my_account(&self) -> Result<GetMyAccountResponse, String> {
199        Ok(GetMyAccountResponse {
200            username: "local".to_string(),
201            id: "local".to_string(),
202            first_name: "local".to_string(),
203            last_name: "local".to_string(),
204        })
205    }
206
207    async fn list_rulebooks(&self) -> Result<Vec<ListRuleBook>, String> {
208        if self.stakpak_base_url.is_none() {
209            return Ok(vec![]);
210        }
211
212        let stakpak_base_url = self
213            .stakpak_base_url
214            .as_ref()
215            .ok_or("Stakpak base URL not set")?;
216
217        let url = format!("{}/rules", stakpak_base_url);
218
219        let client = create_tls_client(
220            TlsClientConfig::default().with_timeout(std::time::Duration::from_secs(300)),
221        )?;
222
223        let response = client
224            .get(url)
225            .send()
226            .await
227            .map_err(|e: ReqwestError| e.to_string())?;
228
229        let value: serde_json::Value = response.json().await.map_err(|e| e.to_string())?;
230
231        match serde_json::from_value::<ListRulebooksResponse>(value.clone()) {
232            Ok(response) => Ok(response.results),
233            Err(e) => {
234                eprintln!("Failed to deserialize response: {}", e);
235                eprintln!("Raw response: {}", value);
236                Err("Failed to deserialize response:".into())
237            }
238        }
239    }
240
241    async fn get_rulebook_by_uri(&self, uri: &str) -> Result<RuleBook, String> {
242        let stakpak_base_url = self
243            .stakpak_base_url
244            .as_ref()
245            .ok_or("Stakpak base URL not set")?;
246
247        let encoded_uri = urlencoding::encode(uri);
248
249        let url = format!("{}/rules/{}", stakpak_base_url, encoded_uri);
250
251        let client = create_tls_client(
252            TlsClientConfig::default().with_timeout(std::time::Duration::from_secs(300)),
253        )?;
254
255        let response = client
256            .get(&url)
257            .send()
258            .await
259            .map_err(|e: ReqwestError| e.to_string())?;
260
261        let value: serde_json::Value = response.json().await.map_err(|e| e.to_string())?;
262
263        match serde_json::from_value::<RuleBook>(value.clone()) {
264            Ok(response) => Ok(response),
265            Err(e) => {
266                eprintln!("Failed to deserialize response: {}", e);
267                eprintln!("Raw response: {}", value);
268                Err("Failed to deserialize response:".into())
269            }
270        }
271    }
272
273    async fn create_rulebook(
274        &self,
275        _uri: &str,
276        _description: &str,
277        _content: &str,
278        _tags: Vec<String>,
279        _visibility: Option<RuleBookVisibility>,
280    ) -> Result<CreateRuleBookResponse, String> {
281        // TODO: Implement create rulebook
282        Err("Local provider does not support rulebooks yet".to_string())
283    }
284
285    async fn delete_rulebook(&self, _uri: &str) -> Result<(), String> {
286        // TODO: Implement delete rulebook
287        Err("Local provider does not support rulebooks yet".to_string())
288    }
289
290    async fn list_agent_sessions(&self) -> Result<Vec<AgentSession>, String> {
291        db::list_sessions(&self.db).await
292    }
293
294    async fn get_agent_session(&self, session_id: Uuid) -> Result<AgentSession, String> {
295        db::get_session(&self.db, session_id).await
296    }
297
298    async fn get_agent_session_stats(
299        &self,
300        _session_id: Uuid,
301    ) -> Result<AgentSessionStats, String> {
302        // TODO: Implement get agent session stats
303        Ok(AgentSessionStats::default())
304    }
305
306    async fn get_agent_checkpoint(&self, checkpoint_id: Uuid) -> Result<RunAgentOutput, String> {
307        db::get_checkpoint(&self.db, checkpoint_id).await
308    }
309
310    async fn get_agent_session_latest_checkpoint(
311        &self,
312        session_id: Uuid,
313    ) -> Result<RunAgentOutput, String> {
314        db::get_latest_checkpoint(&self.db, session_id).await
315    }
316
317    async fn chat_completion(
318        &self,
319        model: AgentModel,
320        messages: Vec<ChatMessage>,
321        tools: Option<Vec<Tool>>,
322    ) -> Result<ChatCompletionResponse, String> {
323        let mut ctx = HookContext::new(None, AgentState::new(model, messages, tools));
324
325        if let Some(hook_registry) = &self.hook_registry {
326            hook_registry
327                .execute_hooks(&mut ctx, &LifecycleEvent::BeforeRequest)
328                .await
329                .map_err(|e| e.to_string())?
330                .ok()?;
331        }
332
333        let current_checkpoint = self.initialize_session(&ctx.state.messages).await?;
334        ctx.set_session_id(current_checkpoint.session.id);
335
336        let new_message = self.run_agent_completion(&mut ctx, None).await?;
337        ctx.state.append_new_message(new_message.clone());
338
339        let result = self
340            .update_session(&current_checkpoint, ctx.state.messages.clone())
341            .await?;
342        let checkpoint_created_at = result.checkpoint.created_at.timestamp() as u64;
343        ctx.set_new_checkpoint_id(result.checkpoint.id);
344
345        if let Some(hook_registry) = &self.hook_registry {
346            hook_registry
347                .execute_hooks(&mut ctx, &LifecycleEvent::AfterRequest)
348                .await
349                .map_err(|e| e.to_string())?
350                .ok()?;
351        }
352
353        Ok(ChatCompletionResponse {
354            id: ctx.new_checkpoint_id.unwrap().to_string(),
355            object: "chat.completion".to_string(),
356            created: checkpoint_created_at,
357            model: ctx
358                .state
359                .llm_input
360                .as_ref()
361                .map(|llm_input| llm_input.model.clone().to_string())
362                .unwrap_or_default(),
363            choices: vec![ChatCompletionChoice {
364                index: 0,
365                message: ctx.state.messages.last().cloned().unwrap(),
366                logprobs: None,
367                finish_reason: FinishReason::Stop,
368            }],
369            usage: ctx
370                .state
371                .llm_output
372                .as_ref()
373                .map(|u| u.usage.clone())
374                .unwrap_or_default(),
375            system_fingerprint: None,
376            metadata: None,
377        })
378    }
379
380    async fn chat_completion_stream(
381        &self,
382        model: AgentModel,
383        messages: Vec<ChatMessage>,
384        tools: Option<Vec<Tool>>,
385        _headers: Option<HeaderMap>,
386    ) -> Result<
387        (
388            Pin<
389                Box<dyn Stream<Item = Result<ChatCompletionStreamResponse, ApiStreamError>> + Send>,
390            >,
391            Option<String>,
392        ),
393        String,
394    > {
395        let mut ctx = HookContext::new(None, AgentState::new(model, messages, tools));
396
397        if let Some(hook_registry) = &self.hook_registry {
398            hook_registry
399                .execute_hooks(&mut ctx, &LifecycleEvent::BeforeRequest)
400                .await
401                .map_err(|e| e.to_string())?
402                .ok()?;
403        }
404
405        let current_checkpoint = self.initialize_session(&ctx.state.messages).await?;
406        ctx.set_session_id(current_checkpoint.session.id);
407
408        let (tx, mut rx) = mpsc::channel::<Result<StreamMessage, String>>(100);
409
410        let _ = tx
411            .send(Ok(StreamMessage::Delta(GenerationDelta::Content {
412                content: format!(
413                    "\n<checkpoint_id>{}</checkpoint_id>\n",
414                    current_checkpoint.checkpoint.id
415                ),
416            })))
417            .await;
418
419        let client = self.clone();
420        let self_clone = self.clone();
421        let mut ctx_clone = ctx.clone();
422        tokio::spawn(async move {
423            let result = client
424                .run_agent_completion(&mut ctx_clone, Some(tx.clone()))
425                .await;
426
427            match result {
428                Err(e) => {
429                    let _ = tx.send(Err(e)).await;
430                }
431                Ok(new_message) => {
432                    ctx_clone.state.append_new_message(new_message.clone());
433                    let _ = tx
434                        .send(Ok(StreamMessage::Ctx(Box::new(ctx_clone.clone()))))
435                        .await;
436
437                    let output = self_clone
438                        .update_session(&current_checkpoint, ctx_clone.state.messages.clone())
439                        .await;
440
441                    match output {
442                        Err(e) => {
443                            let _ = tx.send(Err(e)).await;
444                        }
445                        Ok(output) => {
446                            ctx_clone.set_new_checkpoint_id(output.checkpoint.id);
447                            let _ = tx.send(Ok(StreamMessage::Ctx(Box::new(ctx_clone)))).await;
448                            let _ = tx
449                                .send(Ok(StreamMessage::Delta(GenerationDelta::Content {
450                                    content: format!(
451                                        "\n<checkpoint_id>{}</checkpoint_id>\n",
452                                        output.checkpoint.id
453                                    ),
454                                })))
455                                .await;
456                        }
457                    }
458                }
459            }
460        });
461
462        let hook_registry = self.hook_registry.clone();
463        let stream = async_stream::stream! {
464            while let Some(delta_result) = rx.recv().await {
465                match delta_result {
466                    Ok(delta) => match delta {
467                            StreamMessage::Ctx(updated_ctx) => {
468                                ctx = *updated_ctx;
469                            }
470                            StreamMessage::Delta(delta) => {
471                                yield Ok(ChatCompletionStreamResponse {
472                                    id: ctx.request_id.to_string(),
473                                    object: "chat.completion.chunk".to_string(),
474                                    created: chrono::Utc::now().timestamp() as u64,
475                                    model: ctx.state.llm_input.as_ref().map(|llm_input| llm_input.model.clone().to_string()).unwrap_or_default(),
476                                    choices: vec![ChatCompletionStreamChoice {
477                                        index: 0,
478                                        delta: delta.into(),
479                                        finish_reason: None,
480                                    }],
481                                    usage: ctx.state.llm_output.as_ref().map(|u| u.usage.clone()),
482                                    metadata: None,
483                                })
484                            }
485                        }
486                    Err(e) => yield Err(ApiStreamError::Unknown(e)),
487                }
488            }
489
490            if let Some(hook_registry) = hook_registry {
491                hook_registry
492                    .execute_hooks(&mut ctx, &LifecycleEvent::AfterRequest)
493                    .await
494                    .map_err(|e| e.to_string())?
495                    .ok()?;
496            }
497        };
498
499        Ok((Box::pin(stream), None))
500    }
501
502    async fn cancel_stream(&self, _request_id: String) -> Result<(), String> {
503        Ok(())
504    }
505
506    async fn search_docs(&self, input: &SearchDocsRequest) -> Result<Vec<Content>, String> {
507        let config = SearchServicesOrchestrator::start()
508            .await
509            .map_err(|e| e.to_string())?;
510
511        // SECURITY TODO:
512        // This uses plain-text, unauthenticated HTTP over localhost.
513        // While acceptable for local development, this is an injection
514        //
515        // Mitigations to consider:
516        // - Add mutual authentication (e.g., token)
517        // - Validate the expected service identity
518
519        let api_url = format!("http://localhost:{}", config.api_port);
520        let search_client = SearchClient::new(api_url);
521
522        let initial_query = if let Some(exclude) = &input.exclude_keywords {
523            format!("{} -{}", input.keywords, exclude)
524        } else {
525            input.keywords.clone()
526        };
527
528        let llm_config = self.get_llm_config();
529        let search_model = get_search_model(
530            &llm_config,
531            self.model_options.eco_model.clone(),
532            self.model_options.smart_model.clone(),
533        );
534
535        let analysis = analyze_search_query(&llm_config, &search_model, &initial_query).await?;
536        let required_documentation = analysis.required_documentation;
537        let mut current_query = analysis.reformulated_query;
538        let mut previous_queries = Vec::new();
539        let mut final_valid_docs = Vec::new();
540        let mut accumulated_needed_urls = Vec::new();
541
542        const MAX_ITERATIONS: usize = 3;
543
544        for _iteration in 0..MAX_ITERATIONS {
545            previous_queries.push(current_query.clone());
546
547            let search_results = search_client
548                .search_and_scrape(current_query.clone(), None)
549                .await
550                .map_err(|e| e.to_string())?;
551
552            if search_results.is_empty() {
553                break;
554            }
555
556            let validation_result = validate_search_docs(
557                &llm_config,
558                &search_model,
559                &search_results,
560                &current_query,
561                &required_documentation,
562                &previous_queries,
563                &accumulated_needed_urls,
564            )
565            .await?;
566
567            for url in &validation_result.needed_urls {
568                if !accumulated_needed_urls.contains(url) {
569                    accumulated_needed_urls.push(url.clone());
570                }
571            }
572
573            for doc in validation_result.valid_docs.into_iter() {
574                let is_duplicate = final_valid_docs
575                    .iter()
576                    .any(|existing_doc: &ScrapedContent| existing_doc.url == doc.url);
577
578                if !is_duplicate {
579                    final_valid_docs.push(doc);
580                }
581            }
582
583            if validation_result.is_satisfied {
584                break;
585            }
586
587            if let Some(new_query) = validation_result.new_query {
588                if new_query != current_query && !previous_queries.contains(&new_query) {
589                    current_query = new_query;
590                } else {
591                    break;
592                }
593            } else {
594                break;
595            }
596        }
597
598        if final_valid_docs.is_empty() {
599            return Ok(vec![Content::text("No results found".to_string())]);
600        }
601
602        let contents: Vec<Content> = final_valid_docs
603            .into_iter()
604            .map(|result| {
605                let content = result.content.unwrap_or_default();
606                Content::text(format!("URL: {}\nContent: {}", result.url, content))
607            })
608            .collect();
609
610        Ok(contents)
611    }
612
613    async fn search_memory(&self, _input: &SearchMemoryRequest) -> Result<Vec<Content>, String> {
614        // TODO: Implement search memory
615        Ok(Vec::new())
616    }
617
618    async fn slack_read_messages(
619        &self,
620        _input: &SlackReadMessagesRequest,
621    ) -> Result<Vec<Content>, String> {
622        // TODO: Implement slack read messages
623        Ok(Vec::new())
624    }
625
626    async fn slack_read_replies(
627        &self,
628        _input: &SlackReadRepliesRequest,
629    ) -> Result<Vec<Content>, String> {
630        // TODO: Implement slack read replies
631        Ok(Vec::new())
632    }
633
634    async fn slack_send_message(
635        &self,
636        _input: &SlackSendMessageRequest,
637    ) -> Result<Vec<Content>, String> {
638        // TODO: Implement slack send message
639        Ok(Vec::new())
640    }
641
642    async fn memorize_session(&self, _checkpoint_id: Uuid) -> Result<(), String> {
643        // TODO: Implement memorize session
644        Ok(())
645    }
646}
647
648impl LocalClient {
649    fn get_llm_config(&self) -> LLMProviderConfig {
650        LLMProviderConfig {
651            anthropic_config: self.anthropic_config.clone(),
652            openai_config: self.openai_config.clone(),
653            gemini_config: self.gemini_config.clone(),
654        }
655    }
656
657    async fn run_agent_completion(
658        &self,
659        ctx: &mut HookContext<AgentState>,
660        stream_channel_tx: Option<mpsc::Sender<Result<StreamMessage, String>>>,
661    ) -> Result<ChatMessage, String> {
662        if let Some(hook_registry) = &self.hook_registry {
663            hook_registry
664                .execute_hooks(ctx, &LifecycleEvent::BeforeInference)
665                .await
666                .map_err(|e| e.to_string())?
667                .ok()?;
668        }
669
670        let input = if let Some(llm_input) = ctx.state.llm_input.clone() {
671            llm_input
672        } else {
673            return Err(
674                "Run agent completion: LLM input not found, make sure to register a context hook before inference"
675                    .to_string(),
676            );
677        };
678
679        let llm_config = self.get_llm_config();
680        let stakai_client = StakAIClient::new(&llm_config)
681            .map_err(|e| format!("Failed to create StakAI client: {}", e))?;
682
683        let (response_message, usage) = if let Some(tx) = stream_channel_tx {
684            let (internal_tx, mut internal_rx) = mpsc::channel::<GenerationDelta>(100);
685            let input = LLMStreamInput {
686                model: input.model,
687                messages: input.messages,
688                max_tokens: input.max_tokens,
689                tools: input.tools,
690                stream_channel_tx: internal_tx,
691                provider_options: input.provider_options,
692            };
693
694            let chat_future = async move {
695                stakai_client
696                    .chat_stream(input)
697                    .await
698                    .map_err(|e| e.to_string())
699            };
700
701            let receive_future = async move {
702                while let Some(delta) = internal_rx.recv().await {
703                    if tx.send(Ok(StreamMessage::Delta(delta))).await.is_err() {
704                        break;
705                    }
706                }
707            };
708
709            let (chat_result, _) = tokio::join!(chat_future, receive_future);
710            let response = chat_result?;
711            (response.choices[0].message.clone(), response.usage)
712        } else {
713            let response = stakai_client.chat(input).await.map_err(|e| e.to_string())?;
714            (response.choices[0].message.clone(), response.usage)
715        };
716
717        ctx.state.set_llm_output(response_message, usage);
718
719        if let Some(hook_registry) = &self.hook_registry {
720            hook_registry
721                .execute_hooks(ctx, &LifecycleEvent::AfterInference)
722                .await
723                .map_err(|e| e.to_string())?
724                .ok()?;
725        }
726
727        let llm_output = ctx
728            .state
729            .llm_output
730            .as_ref()
731            .ok_or_else(|| "LLM output is missing from state".to_string())?;
732
733        Ok(ChatMessage::from(llm_output))
734    }
735
736    async fn initialize_session(&self, messages: &[ChatMessage]) -> Result<RunAgentOutput, String> {
737        // 1. Validate input
738        if messages.is_empty() {
739            return Err("At least one message is required".to_string());
740        }
741
742        // 2. Extract session/checkpoint ID or create new session
743        let checkpoint_id = ChatMessage::last_server_message(messages).and_then(|message| {
744            message
745                .content
746                .as_ref()
747                .and_then(|content| content.extract_checkpoint_id())
748        });
749
750        let current_checkpoint = if let Some(checkpoint_id) = checkpoint_id {
751            db::get_checkpoint(&self.db, checkpoint_id).await?
752        } else {
753            let title = self.generate_session_title(messages).await?;
754
755            // Create new session
756            let session_id = Uuid::new_v4();
757            let now = chrono::Utc::now();
758            let session = AgentSession {
759                id: session_id,
760                title,
761                agent_id: AgentID::PabloV1,
762                visibility: AgentSessionVisibility::Private,
763                created_at: now,
764                updated_at: now,
765                checkpoints: vec![],
766            };
767            db::create_session(&self.db, &session).await?;
768
769            // Create initial checkpoint (root)
770            let checkpoint_id = Uuid::new_v4();
771            let checkpoint = AgentCheckpointListItem {
772                id: checkpoint_id,
773                status: AgentStatus::Complete,
774                execution_depth: 0,
775                parent: None,
776                created_at: now,
777                updated_at: now,
778            };
779            let initial_state = AgentOutput::PabloV1 {
780                messages: messages.to_vec(),
781                node_states: serde_json::json!({}),
782            };
783            db::create_checkpoint(&self.db, session_id, &checkpoint, &initial_state).await?;
784
785            db::get_checkpoint(&self.db, checkpoint_id).await?
786        };
787
788        Ok(current_checkpoint)
789    }
790
791    async fn update_session(
792        &self,
793        checkpoint_info: &RunAgentOutput,
794        new_messages: Vec<ChatMessage>,
795    ) -> Result<RunAgentOutput, String> {
796        let now = chrono::Utc::now();
797        let complete_checkpoint = AgentCheckpointListItem {
798            id: Uuid::new_v4(),
799            status: AgentStatus::Complete,
800            execution_depth: checkpoint_info.checkpoint.execution_depth + 1,
801            parent: Some(AgentParentCheckpoint {
802                id: checkpoint_info.checkpoint.id,
803            }),
804            created_at: now,
805            updated_at: now,
806        };
807
808        let mut new_state = checkpoint_info.output.clone();
809        new_state.set_messages(new_messages);
810
811        db::create_checkpoint(
812            &self.db,
813            checkpoint_info.session.id,
814            &complete_checkpoint,
815            &new_state,
816        )
817        .await?;
818
819        Ok(RunAgentOutput {
820            checkpoint: complete_checkpoint,
821            session: checkpoint_info.session.clone(),
822            output: new_state,
823        })
824    }
825
826    async fn generate_session_title(&self, messages: &[ChatMessage]) -> Result<String, String> {
827        let llm_config = self.get_llm_config();
828
829        let llm_model = if let Some(eco_model) = &self.model_options.eco_model {
830            eco_model.clone()
831        } else if llm_config.openai_config.is_some() {
832            LLMModel::OpenAI(OpenAIModel::GPT5Mini)
833        } else if llm_config.anthropic_config.is_some() {
834            LLMModel::Anthropic(AnthropicModel::Claude45Haiku)
835        } else if llm_config.gemini_config.is_some() {
836            LLMModel::Gemini(GeminiModel::Gemini25Flash)
837        } else {
838            return Err("No LLM config found".to_string());
839        };
840
841        let messages = vec![
842            LLMMessage {
843                role: "system".to_string(),
844                content: LLMMessageContent::String(TITLE_GENERATOR_PROMPT.into()),
845            },
846            LLMMessage {
847                role: "user".to_string(),
848                content: LLMMessageContent::String(
849                    messages
850                        .iter()
851                        .map(|msg| {
852                            msg.content
853                                .as_ref()
854                                .unwrap_or(&MessageContent::String("".to_string()))
855                                .to_string()
856                        })
857                        .collect(),
858                ),
859            },
860        ];
861
862        let input = LLMInput {
863            model: llm_model,
864            messages,
865            max_tokens: 100,
866            tools: None,
867            provider_options: None,
868        };
869
870        let stakai_client = StakAIClient::new(&llm_config)
871            .map_err(|e| format!("Failed to create StakAI client: {}", e))?;
872        let response = stakai_client.chat(input).await.map_err(|e| e.to_string())?;
873
874        Ok(response.choices[0].message.content.to_string())
875    }
876}
877
878async fn analyze_search_query(
879    llm_config: &LLMProviderConfig,
880    model: &LLMModel,
881    query: &str,
882) -> Result<AnalysisResult, String> {
883    let system_prompt = r#"You are an expert search query analyzer specializing in technical documentation retrieval.
884
885## Your Task
886
887Analyze the user's search query to:
8881. Identify the specific types of documentation needed
8892. Reformulate the query for optimal search engine results
890
891## Guidelines for Required Documentation
892
893Identify specific documentation types such as:
894- API references and specifications
895- Installation/setup guides
896- Configuration documentation
897- Tutorials and getting started guides
898- Troubleshooting guides
899- Architecture/design documents
900- CLI/command references
901- SDK/library documentation
902
903## Guidelines for Query Reformulation
904
905Create an optimized search query that:
906- Uses specific technical terminology
907- Includes relevant keywords (e.g., "documentation", "guide", "API")
908- Removes ambiguous or filler words
909- Targets authoritative sources when possible
910- Is concise but comprehensive (5-10 words ideal)
911
912## Response Format
913
914Respond ONLY with valid XML in this exact structure:
915
916<analysis>
917  <required_documentation>
918    <item>specific documentation type needed</item>
919  </required_documentation>
920  <reformulated_query>optimized search query string</reformulated_query>
921</analysis>"#;
922
923    let user_prompt = format!(
924        r#"<user_query>{}</user_query>
925
926Analyze this query and provide the required documentation types and an optimized search query."#,
927        query
928    );
929
930    let input = LLMInput {
931        model: model.clone(),
932        messages: vec![
933            LLMMessage {
934                role: Role::System.to_string(),
935                content: LLMMessageContent::String(system_prompt.to_string()),
936            },
937            LLMMessage {
938                role: Role::User.to_string(),
939                content: LLMMessageContent::String(user_prompt.to_string()),
940            },
941        ],
942        max_tokens: 2000,
943        tools: None,
944        provider_options: None,
945    };
946
947    let stakai_client = StakAIClient::new(llm_config)
948        .map_err(|e| format!("Failed to create StakAI client: {}", e))?;
949    let response = stakai_client.chat(input).await.map_err(|e| e.to_string())?;
950
951    let content = response.choices[0].message.content.to_string();
952
953    parse_analysis_xml(&content)
954}
955
956fn parse_analysis_xml(xml: &str) -> Result<AnalysisResult, String> {
957    let extract_tag = |tag: &str| -> Option<String> {
958        let start_tag = format!("<{}>", tag);
959        let end_tag = format!("</{}>", tag);
960        xml.find(&start_tag).and_then(|start| {
961            let content_start = start + start_tag.len();
962            xml[content_start..]
963                .find(&end_tag)
964                .map(|end| xml[content_start..content_start + end].trim().to_string())
965        })
966    };
967
968    let extract_all_tags = |tag: &str| -> Vec<String> {
969        let start_tag = format!("<{}>", tag);
970        let end_tag = format!("</{}>", tag);
971        let mut results = Vec::new();
972        let mut search_start = 0;
973
974        while let Some(start) = xml[search_start..].find(&start_tag) {
975            let abs_start = search_start + start + start_tag.len();
976            if let Some(end) = xml[abs_start..].find(&end_tag) {
977                results.push(xml[abs_start..abs_start + end].trim().to_string());
978                search_start = abs_start + end + end_tag.len();
979            } else {
980                break;
981            }
982        }
983        results
984    };
985
986    let required_documentation = extract_all_tags("item");
987    let reformulated_query =
988        extract_tag("reformulated_query").ok_or("Failed to extract reformulated_query from XML")?;
989
990    Ok(AnalysisResult {
991        required_documentation,
992        reformulated_query,
993    })
994}
995
996async fn validate_search_docs(
997    llm_config: &LLMProviderConfig,
998    model: &LLMModel,
999    docs: &[ScrapedContent],
1000    query: &str,
1001    required_documentation: &[String],
1002    previous_queries: &[String],
1003    accumulated_needed_urls: &[String],
1004) -> Result<ValidationResult, String> {
1005    let docs_preview = docs
1006        .iter()
1007        .enumerate()
1008        .take(10)
1009        .map(|(i, r)| {
1010            format!(
1011                "<doc index=\"{}\">\n  <title>{}</title>\n  <url>{}</url>\n</doc>",
1012                i + 1,
1013                r.title.clone().unwrap_or_else(|| "Untitled".to_string()),
1014                r.url
1015            )
1016        })
1017        .collect::<Vec<_>>()
1018        .join("\n");
1019
1020    let required_docs_formatted = required_documentation
1021        .iter()
1022        .map(|d| format!("  <item>{}</item>", d))
1023        .collect::<Vec<_>>()
1024        .join("\n");
1025
1026    let previous_queries_formatted = previous_queries
1027        .iter()
1028        .map(|q| format!("  <query>{}</query>", q))
1029        .collect::<Vec<_>>()
1030        .join("\n");
1031
1032    let accumulated_urls_formatted = accumulated_needed_urls
1033        .iter()
1034        .map(|u| format!("  <url>{}</url>", u))
1035        .collect::<Vec<_>>()
1036        .join("\n");
1037
1038    let system_prompt = r#"You are an expert search result validator. Your task is to evaluate whether search results adequately satisfy a documentation query.
1039
1040## Evaluation Criteria
1041
1042For each search result, assess:
10431. **Relevance**: Does the document directly address the required documentation topics?
10442. **Authority**: Is this an official source, documentation site, or authoritative reference?
10453. **Completeness**: Does it provide comprehensive information, not just passing mentions?
10464. **Freshness**: For technical docs, prefer current/maintained sources over outdated ones.
1047
1048## Decision Guidelines
1049
1050Mark results as SATISFIED when:
1051- All required documentation topics have at least one authoritative source
1052- The sources provide actionable, detailed information
1053- No critical gaps remain in coverage
1054
1055Suggest a NEW QUERY when:
1056- Key topics are missing from results
1057- Results are too general or tangential
1058- A more specific query would yield better results
1059- Previous queries haven't addressed certain requirements
1060
1061## Response Format
1062
1063Respond ONLY with valid XML in this exact structure:
1064
1065<validation>
1066  <is_satisfied>true or false</is_satisfied>
1067  <valid_docs>
1068    <doc><url>exact URL from results</url></doc>
1069  </valid_docs>
1070  <needed_urls>
1071    <url>specific URL pattern or domain still needed</url>
1072  </needed_urls>
1073  <new_query>refined search query if not satisfied, omit if satisfied</new_query>
1074  <reasoning>brief explanation of your assessment</reasoning>
1075</validation>"#;
1076
1077    let user_prompt = format!(
1078        r#"<search_context>
1079  <original_query>{}</original_query>
1080  <required_documentation>
1081{}
1082  </required_documentation>
1083  <previous_queries>
1084{}
1085  </previous_queries>
1086  <accumulated_needed_urls>
1087{}
1088  </accumulated_needed_urls>
1089</search_context>
1090
1091<current_results>
1092{}
1093</current_results>
1094
1095Evaluate these search results against the requirements. Which documents are valid and relevant? Is the documentation requirement satisfied? If not, what specific query would help find missing information?"#,
1096        query,
1097        if required_docs_formatted.is_empty() {
1098            "    <item>None specified</item>".to_string()
1099        } else {
1100            required_docs_formatted
1101        },
1102        if previous_queries_formatted.is_empty() {
1103            "    <query>None</query>".to_string()
1104        } else {
1105            previous_queries_formatted
1106        },
1107        if accumulated_urls_formatted.is_empty() {
1108            "    <url>None</url>".to_string()
1109        } else {
1110            accumulated_urls_formatted
1111        },
1112        docs_preview
1113    );
1114
1115    let input = LLMInput {
1116        model: model.clone(),
1117        messages: vec![
1118            LLMMessage {
1119                role: Role::System.to_string(),
1120                content: LLMMessageContent::String(system_prompt.to_string()),
1121            },
1122            LLMMessage {
1123                role: Role::User.to_string(),
1124                content: LLMMessageContent::String(user_prompt.to_string()),
1125            },
1126        ],
1127        max_tokens: 4000,
1128        tools: None,
1129        provider_options: None,
1130    };
1131
1132    let stakai_client = StakAIClient::new(llm_config)
1133        .map_err(|e| format!("Failed to create StakAI client: {}", e))?;
1134    let response = stakai_client.chat(input).await.map_err(|e| e.to_string())?;
1135
1136    let content = response.choices[0].message.content.to_string();
1137
1138    let validation = parse_validation_xml(&content, docs)?;
1139
1140    Ok(validation)
1141}
1142
1143fn parse_validation_xml(xml: &str, docs: &[ScrapedContent]) -> Result<ValidationResult, String> {
1144    let extract_tag = |tag: &str| -> Option<String> {
1145        let start_tag = format!("<{}>", tag);
1146        let end_tag = format!("</{}>", tag);
1147        xml.find(&start_tag).and_then(|start| {
1148            let content_start = start + start_tag.len();
1149            xml[content_start..]
1150                .find(&end_tag)
1151                .map(|end| xml[content_start..content_start + end].trim().to_string())
1152        })
1153    };
1154
1155    let extract_all_tags = |tag: &str| -> Vec<String> {
1156        let start_tag = format!("<{}>", tag);
1157        let end_tag = format!("</{}>", tag);
1158        let mut results = Vec::new();
1159        let mut search_start = 0;
1160
1161        while let Some(start) = xml[search_start..].find(&start_tag) {
1162            let abs_start = search_start + start + start_tag.len();
1163            if let Some(end) = xml[abs_start..].find(&end_tag) {
1164                results.push(xml[abs_start..abs_start + end].trim().to_string());
1165                search_start = abs_start + end + end_tag.len();
1166            } else {
1167                break;
1168            }
1169        }
1170        results
1171    };
1172
1173    let is_satisfied = extract_tag("is_satisfied")
1174        .map(|s| s.to_lowercase() == "true")
1175        .unwrap_or(false);
1176
1177    let valid_urls: Vec<String> = extract_all_tags("url")
1178        .into_iter()
1179        .filter(|url| docs.iter().any(|d| d.url == *url))
1180        .collect();
1181
1182    let valid_docs: Vec<ScrapedContent> = valid_urls
1183        .iter()
1184        .filter_map(|url| docs.iter().find(|d| d.url == *url).cloned())
1185        .collect();
1186
1187    let needed_urls: Vec<String> = extract_all_tags("url")
1188        .into_iter()
1189        .filter(|url| !docs.iter().any(|d| d.url == *url))
1190        .collect();
1191
1192    let new_query = extract_tag("new_query").filter(|q| !q.is_empty() && q != "omit if satisfied");
1193
1194    Ok(ValidationResult {
1195        is_satisfied,
1196        valid_docs,
1197        needed_urls,
1198        new_query,
1199    })
1200}
1201
1202fn get_search_model(
1203    llm_config: &LLMProviderConfig,
1204    eco_model: Option<LLMModel>,
1205    smart_model: Option<LLMModel>,
1206) -> LLMModel {
1207    let base_model = eco_model.or(smart_model);
1208
1209    match base_model {
1210        Some(LLMModel::OpenAI(_)) => LLMModel::OpenAI(OpenAIModel::O4Mini),
1211        Some(LLMModel::Anthropic(_)) => LLMModel::Anthropic(AnthropicModel::Claude45Haiku),
1212        Some(LLMModel::Gemini(_)) => LLMModel::Gemini(GeminiModel::Gemini3Flash),
1213        Some(LLMModel::Custom(model)) => LLMModel::Custom(model),
1214        None => {
1215            if llm_config.openai_config.is_some() {
1216                LLMModel::OpenAI(OpenAIModel::O4Mini)
1217            } else if llm_config.anthropic_config.is_some() {
1218                LLMModel::Anthropic(AnthropicModel::Claude45Haiku)
1219            } else if llm_config.gemini_config.is_some() {
1220                LLMModel::Gemini(GeminiModel::Gemini3Flash)
1221            } else {
1222                LLMModel::OpenAI(OpenAIModel::O4Mini)
1223            }
1224        }
1225    }
1226}