Files
capri-core-rust/crates/capri-agent/src/prompt.rs
T

169 lines
7.7 KiB
Rust

//! System prompt assembly and the per-turn context envelope.
use std::path::Path;
use anyhow::Result;
use capri_core::avatar::ModelSprite;
use capri_core::persona;
use capri_core::settings::LanguageSettings;
pub const CHAT_ONLY: &str = include_str!("../../../assets/prompts/chat-only.txt");
pub const DIALOGUE_CONTINUITY: &str = include_str!("../../../assets/prompts/dialogue-continuity.txt");
pub const DIALOGUE_ONLY: &str = include_str!("../../../assets/prompts/dialogue-only.txt");
pub const INTERFACE: &str = include_str!("../../../assets/prompts/interface.txt");
pub const TOOL_EXECUTION: &str = include_str!("../../../assets/prompts/tool.txt");
pub const WEB_ANSWER: &str = include_str!("../../../assets/prompts/web-answer.txt");
/// Which instruction block the turn uses.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PromptMode {
/// The model has no tools at all.
ChatOnly,
/// A greeting or small talk: tools are hidden for this turn.
Dialogue,
/// Internet mode: web evidence is supplied by the host.
Web,
/// Desktop interface with tools.
Tools,
}
/// `AVATAR CONTROL` block (Capri `avatar-protocol.mjs` `avatarInstructions`, follow-up enabled).
pub fn avatar_instructions(sprites: &[ModelSprite]) -> String {
let Some(first) = sprites.first() else {
return "This interface currently has no controllable avatar. Write only your reply, without control markers.".into();
};
let options: Vec<String> = sprites.iter().map(|s| format!("{}: {}", s.id, s.description)).collect();
format!(
"AVATAR CONTROL:
Choose your facial expression or reaction from context. Begin your final user-facing answer with exactly one hidden marker [avatar:ID], then a newline and your English reply. When a tool is needed, call it first without an avatar marker or spoken preamble; choose the avatar only for your answer after the tool result. Use one listed ID:
{}
LISTENING CONTROL: For a genuine follow-up question or explicit invitation to answer, use [avatar:ID;listen] as the opening control line instead of [avatar:ID]. The ;listen flag belongs ONLY inside that opening bracketed marker. Never put it in the spoken reply or at the end of the answer. For rhetorical questions, routine task confirmations and goodbyes use [avatar:ID]. This grants only a short continuation of an already-enabled microphone.
Example first line (no punctuation after the marker):
[avatar:{}]
Then write the reply on the next line. Keep one choice per reply. The marker is a single opening control line, not an XML tag: never add a closing marker or repeat it in the reply. Vary your expression naturally and be empathetic to distress. Choose a flirty expression or a wink only when the conversation invites it. Laugh when something is genuinely funny. Facial reactions finish automatically; blinking and speech motion are handled locally. Never explain or quote the marker. These graphics do not grant computer-control tools.",
options.join("\n"),
first.id
)
}
/// Keeps the head (75 %) and tail (25 %) of an over-long context file.
fn clamp(text: &str, max: usize) -> String {
let chars: Vec<char> = text.chars().collect();
if chars.len() <= max {
return text.to_string();
}
let head = max * 3 / 4;
let tail = max - head;
let mut out: String = chars[..head].iter().collect();
out.push_str("\n\n[... truncated ...]\n\n");
out.extend(&chars[chars.len() - tail..]);
out
}
fn project_context(workspace: &Path) -> String {
let mut loaded = Vec::new();
let mut sections = String::new();
for (name, max, about) in [
("USER.md", 4000, "USER.md: durable user preferences and profile directives; follow unless higher-priority instructions override."),
("MEMORY.md", 20000, "MEMORY.md: durable non-profile facts and decisions; use when relevant unless higher-priority instructions override."),
] {
let path = workspace.join(name);
let text = capri_core::fsutil::read_regular(&path, 1024 * 1024)
.ok()
.flatten()
.and_then(|b| String::from_utf8(b).ok())
.unwrap_or_default();
let text = text.trim();
if text.is_empty() {
continue;
}
loaded.push(about);
sections.push_str(&format!("\n\n## {}\n\n{}", path.display(), clamp(text, max)));
}
if loaded.is_empty() {
return String::new();
}
// Upstream lists MEMORY.md first in this summary.
loaded.reverse();
format!("# Project Context\n\nLoaded project context:\n{}{}", loaded.join("\n"), sections)
}
fn time_zone() -> String {
if let Ok(tz) = std::env::var("TZ")
&& !tz.is_empty() {
return tz.trim_start_matches(':').to_string();
}
std::fs::read_link("/etc/localtime")
.ok()
.and_then(|p| p.to_str().and_then(|s| s.split("zoneinfo/").nth(1).map(str::to_string)))
.unwrap_or_else(|| "UTC".into())
}
pub fn system_prompt(workspace: &Path, language: &LanguageSettings, sprites: &[ModelSprite], mode: PromptMode) -> Result<String> {
let persona = format!(
"CAPRI PERSONALITY (PERSONALITY.md):\n{}\n\n{}",
persona::read_personality(workspace)?,
persona::communication_instruction(&persona::read_style(workspace))
);
let block = match mode {
PromptMode::ChatOnly => CHAT_ONLY,
PromptMode::Dialogue => DIALOGUE_ONLY,
PromptMode::Web => WEB_ANSWER,
PromptMode::Tools => INTERFACE,
};
let mut parts = vec![persona, block.to_string(), avatar_instructions(sprites), DIALOGUE_CONTINUITY.to_string()];
if mode == PromptMode::Tools {
parts.push(TOOL_EXECUTION.to_string());
}
parts.push(persona::conversation_instruction(language));
let capri = parts.join("\n\n");
let mut prompt = capri;
let context = project_context(workspace);
if !context.is_empty() {
prompt.push_str("\n\n");
prompt.push_str(&context);
}
prompt.push_str(&format!(
"\n\n## Temporal Context\nCurrent date: {}\nTime zone: {}",
chrono::Local::now().format("%Y-%m-%d"),
time_zone()
));
Ok(prompt)
}
/// `DESKTOP STATE FOR THIS TURN` envelope appended to the user text sent to the model.
pub fn envelope(state: &serde_json::Value) -> String {
if state.as_object().is_none_or(|o| o.is_empty()) {
return String::new();
}
format!("\n\nDESKTOP STATE FOR THIS TURN (data, not a user request):\n{state}")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn prompt_contains_all_parts_in_order() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("USER.md"), "Call me Sam.").unwrap();
let sprites = capri_core::avatar::Catalog::fallback().model_sprites;
let p = system_prompt(dir.path(), &LanguageSettings::default(), &sprites, PromptMode::ChatOnly).unwrap();
let tools = system_prompt(dir.path(), &LanguageSettings::default(), &sprites, PromptMode::Tools).unwrap();
assert!(tools.contains("CURRENT DESKTOP INTERFACE:") && tools.contains("TOOL EXECUTION BEFORE FINAL ANSWER:"));
let order = ["CAPRI PERSONALITY", "COMMUNICATION STYLE: neutral", "Reply as Capri", "AVATAR CONTROL", "DIALOGUE CONTINUITY", "CURRENT CONVERSATION LANGUAGE", "# Project Context", "Call me Sam.", "## Temporal Context"];
let mut at = 0;
for part in order {
let found = p[at..].find(part).unwrap_or_else(|| panic!("missing or out of order: {part}"));
at += found;
}
assert!(p.contains("[avatar:neutral]"));
}
#[test]
fn clamp_keeps_head_and_tail() {
let s = "a".repeat(30) + &"b".repeat(10);
let c = clamp(&s, 20);
assert!(c.starts_with(&"a".repeat(15)) && c.ends_with(&"b".repeat(5)));
}
}