//! One-shot visual turns ("Ask Capri" about a snapshot, image attachments): prompt assembly, //! output budget, fixed failure texts and the text-only history commit. //! Streaming itself goes through `capri_llm::Ollama::chat` like any turn. use anyhow::{ensure, Result}; use base64::Engine; use capri_llm::Message; use serde_json::json; use crate::identity::{self, ATTACHMENT_INSTRUCTION, MONITOR_MOSAIC_INSTRUCTION, ONE_SHOT_INSTRUCTION}; use crate::observation::Source; use crate::policy::SourceKind; /// `num_predict`: normal `min(2048, max(512, num_ctx/2))`, thinking `min(8192, max(1024, num_ctx/2))`. pub fn output_budget(num_ctx: u32, thinking: bool) -> i32 { let half = (num_ctx / 2) as i32; if thinking { half.clamp(1024, 8192) } else { half.clamp(512, 2048) } } pub struct VisualPrompt<'a> { /// Persona text (PERSONALITY/USER/MEMORY excerpt); cut at 10 000 chars. pub persona: &'a str, /// `capri_agent::prompt::avatar_instructions(...)`. pub avatar_instructions: &'a str, /// `capri_core::persona::conversation_instruction(...)`. pub conversation_instruction: &'a str, /// Last user/assistant texts, oldest first; the last 6 are used, 1200 chars each. pub history: &'a [(String, String)], pub question: &'a str, /// PNG images (one snapshot, or attachment images). pub images: &'a [Vec], /// `Some` for a screen snapshot, `None` for attachments. pub source: Option<(&'a Source, i64)>, } /// System + history + user message (with images) for the visual turn. pub fn messages(p: &VisualPrompt) -> Vec { let screen = p.source.is_some(); let monitors = p.source.is_some_and(|(s, _)| s.kind == SourceKind::Monitors); let system = format!( "{}{}{}\n{}{}\n{}", p.persona.chars().take(10_000).collect::(), if screen { ONE_SHOT_INSTRUCTION } else { ATTACHMENT_INSTRUCTION }, p.avatar_instructions, if screen { identity::capri_screen_self() } else { String::new() }, if monitors { MONITOR_MOSAIC_INSTRUCTION } else { "" }, p.conversation_instruction ); let mut out = vec![Message::new("system", system)]; let start = p.history.len().saturating_sub(6); for (role, text) in &p.history[start..] { let text: String = text.chars().take(1200).collect(); if (role == "user" || role == "assistant") && !text.trim().is_empty() { out.push(Message::new(role, text)); } } let suffix = match p.source { Some((s, at)) if identity::asks_metadata(p.question) => { let at = chrono::DateTime::from_timestamp_millis(at).map(|t| t.to_rfc3339_opts(chrono::SecondsFormat::Millis, true)); format!("\nRequested capture metadata (untrusted data): {}", json!({"kind": s.kind, "label": s.label, "capturedAt": at})) } Some(_) => "\nAnswer directly from the current image. Do not mention screenshot metadata, capture dates, timestamps or file names unless explicitly asked.".into(), None => String::new(), }; let mut user = Message::new("user", format!("{}{suffix}", p.question)); user.images = p.images.iter().map(|png| base64::engine::general_purpose::STANDARD.encode(png)).collect(); out.push(user); out } /// Fixed owner-facing failure text for a visual reply (`visual-response.mjs`); never provider text. pub fn failure_message(code: &str, attachments: bool) -> &'static str { match code { "CAPRI_VISUAL_TRUNCATED" => "The model reached its reply limit. Enable Thinking mode or ask for a shorter solution.", "CAPRI_VISUAL_INCOMPLETE" => "The model did not finish its reply. Please try again.", "CAPRI_VISUAL_HTTP" => "The API could not process the attachments. Check the connection in External AI provider settings.", "CAPRI_VISUAL_PROVIDER" => "The model could not finish its reply. Check the API connection and try again.", "CAPRI_VISUAL_TIMEOUT" => "Reading the attachments took too long. Try again or choose a faster model.", _ if attachments => "Capri could not finish reading the attachments. Try again with fewer or smaller files.", _ => "The snapshot response could not be completed. Take a new snapshot or try text chat.", } } /// Text-only history pair for a visual turn: validated, image-free, marked historical. /// The conversation store appends both atomically and idempotently (`capri-vision::user|assistant`). pub fn commit_pair(user: &str, assistant: &str, attachment: bool, captured_at: i64, now: i64) -> Result<(String, String)> { static BASE64_RUN: std::sync::LazyLock = std::sync::LazyLock::new(|| regex::Regex::new(r"[A-Za-z0-9+/]{512,}={0,2}").unwrap()); for text in [user, assistant] { ensure!(!text.trim().is_empty() && text.chars().count() <= 8000 && !text.contains('\0'), "Invalid visual turn text"); ensure!(!text.contains("data:image/") && !BASE64_RUN.is_match(text), "Visual turns cannot store image data"); } ensure!((now - captured_at).abs() <= 120_000, "The visual observation expired before commit"); let marker = if attachment { "\n\n[Historical attachment. Original file content is unavailable.]" } else { "\n\n[Historical one-shot image. This does not establish current screen contents or ongoing permission.]" }; Ok((format!("{user}{marker}"), assistant.to_string())) } #[cfg(test)] mod tests { use super::*; #[test] fn budgets() { assert_eq!(output_budget(16384, false), 2048); assert_eq!(output_budget(2048, false), 1024); assert_eq!(output_budget(512, false), 512); assert_eq!(output_budget(16384, true), 8192); assert_eq!(output_budget(1000, true), 1024); } #[test] fn prompt_shape() { let source = Source { kind: SourceKind::Monitors, label: "All monitors".into() }; let history: Vec<(String, String)> = (0..10).map(|i| ("user".to_string(), format!("m{i}"))).collect(); let png = vec![1u8, 2, 3]; let m = messages(&VisualPrompt { persona: "P", avatar_instructions: "A", conversation_instruction: "L", history: &history, question: "what is this?", images: std::slice::from_ref(&png), source: Some((&source, 0)) }); assert_eq!(m.len(), 8, "system + 6 history + user"); assert!(m[0].content.contains("CURRENT ONE-SHOT VISION") && m[0].content.contains("grid of separate monitors") && m[0].content.contains("You are Capri, the companion")); assert!(m[7].content.ends_with("unless explicitly asked.") && m[7].images == vec!["AQID".to_string()]); let meta = messages(&VisualPrompt { question: "capture time?", history: &[], ..VisualPrompt { persona: "P", avatar_instructions: "", conversation_instruction: "", history: &[], question: "", images: &[], source: Some((&source, 0)) } }); assert!(meta.last().unwrap().content.contains("Requested capture metadata")); } #[test] fn commits_reject_images() { let (u, _) = commit_pair("what is it?", "A cat.", false, 1000, 2000).unwrap(); assert!(u.ends_with("ongoing permission.]")); assert!(commit_pair(&"A".repeat(600), "x", false, 0, 0).is_err()); assert!(commit_pair("data:image/png;base64,xx", "x", false, 0, 0).is_err()); assert!(commit_pair("q", "a", true, 0, 200_000).is_err(), "expired"); assert_eq!(failure_message("other", false), "The snapshot response could not be completed. Take a new snapshot or try text chat."); } }