Linux port: first run, packaging, single instance, privacy and wiring
CI / test (push) Has been cancelled

First run and backend
- The companion opens without Ollama or a model (OFFLINE / SETUP REQUIRED),
  opens Settings > Language model and picks the model up once downloaded.
- Model, provider and GPU changes apply without restarting (Ollama is
  restarted when launch settings change); no silent fallback from API mode.
- Fatal startup errors are shown in a window; the fallback avatar loads
  again; the shipped Capri artwork is used when nothing was imported.

Packaging and tooling
- packaging/arch/PKGBUILD, capri.desktop (KWin ScreenShot2 key), icons,
  artwork under /usr/share/capri/assets, Gitea Actions CI.
- xtask: `icons` and `release-check` (no private data or credentials).

Runtime
- One instance per data folder (flock + control socket): second launch
  shows the window; capri stop / restart / toggle / status (JSON, starts
  nothing) / doctor / setup / diagnostics export / purge.
- A foreign program on the Ollama port is refused; an Ollama left behind
  by Capri is replaced.

Privacy and security
- No raw Ollama log on disk; API keys are never saved in plaintext (old
  ones move to the keyring); refused credential notes are stored as
  [Credentials omitted]; launched apps get an allow-listed environment.

Fixes
- Stop/Escape silence the voice; saved voice effects apply to replies;
  settings_control glitch settings apply; distinct KWin cursor scripts;
  KDE window capture authorized for source builds; Linux wording.
- Voice pack references zipped with Windows separators are found.

Wired features
- Initiatives, request router, resource monitor, "clip that", questions
  about a snapshot, sleep mode, tap reactions, stopwatch, attachments,
  Internet mode button, voice-synced subtitles, wake visuals, dictation
  draft, tray switches, Spotify seek/shuffle/repeat; computer-control
  planner and classifier follow model switches and API mode.
- Approval cards: one shown, 8 queued, deduplicated, cancelled on stop,
  failure, lock or pause; one Application access switch.

Desktop
- Compositor detection (no black overlay on i3 without picom), i3lock
  detection, unsupported desktops reported at startup, screenshot-only
  control without AT-SPI, fontconfig fallbacks, translatable feature
  pages with French translations.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
nocodeandClaude Opus 5.5 committed 2026-11-12 20:21:40 +01:00
1 parent a2abf01280
commit 49349d6ecd
73 files changed
+4834 -517

No files matched your search

+272 -18
View File
@@ -31,6 +31,13 @@ const SETTLED_TOOLS_FALLBACK: &str = "The tool run finished, but no final summar
/// Answers a turn without the model (explicit owner notes). `Some(reply)` ends the turn.
pub type FastPath = Arc<dyn Fn(&str) -> Option<String> + Send + Sync>;
/// Request router: `(text, up to 2 previous owner messages)` → `true` for plain small talk,
/// answered with dialogue-only instructions and no action tools (spec 02 INF-66).
pub type Classifier = Arc<dyn Fn(String, Vec<String>) -> Pin<Box<dyn Future<Output = bool> + Send>> + Send + Sync>;
/// `true` when the owner input must be stored as [`CREDENTIALS_OMITTED`].
pub type InputRedactor = Arc<dyn Fn(&str) -> bool + Send + Sync>;
/// Visible-history text of an input that carried credentials.
pub const CREDENTIALS_OMITTED: &str = "[Credentials omitted]";
/// Summarizes `messages` (oldest first) given the previous summary. Must call the model
/// without tools and fall back to an extractive summary itself.
pub type Compactor = Arc<dyn Fn(Vec<Message>, Option<String>) -> Pin<Box<dyn Future<Output = Result<String>> + Send>> + Send + Sync>;
@@ -93,8 +100,10 @@ pub struct Engine {
paths: Paths,
settings: Mutex<Settings>,
backend: Mutex<LlmBackend>,
model: String,
model: Mutex<String>,
capabilities: Mutex<Vec<String>>,
/// The local model's own capabilities, kept while an API is active.
local_caps: Mutex<Vec<String>>,
catalog: Arc<Catalog>,
session: Mutex<Session>,
journal: Mutex<Journal>,
@@ -105,7 +114,14 @@ pub struct Engine {
context: Mutex<Vec<ContextHook>>,
internet: AtomicBool,
fast_path: Mutex<Option<FastPath>>,
router: Mutex<Option<Router>>,
redact_input: Mutex<Option<InputRedactor>>,
classifier: Mutex<Option<Classifier>>,
/// Base64 images for the next owner message (attachments), consumed by it.
pending_images: Mutex<Vec<String>>,
/// Context text for the next owner message (what an attached snapshot shows), consumed by it.
pending_note: Mutex<String>,
/// Pre-model routes, tried in order; the first answer wins (clip command, computer tasks…).
routers: Mutex<Vec<Router>>,
reply_guard: Mutex<Option<ReplyGuard>>,
compactor: Mutex<Option<Compactor>>,
after_turn: Mutex<Option<TurnHook>>,
@@ -123,6 +139,8 @@ fn public_message(error: &TurnError) -> &'static str {
TurnError::Empty => "The response could not be completed. Check the local core or reconnect.",
TurnError::ToolLoop => "The action could not be completed after repeated attempts. Check Application access or try a larger language model.",
TurnError::ModelLoad => "The local model could not load. Free some memory or choose a smaller Qwen model, then try again.",
TurnError::ModelMissing => "No language model is installed yet. Download one in Settings › Language model, then try again.",
TurnError::Offline => "The local core is not running. Install Ollama (pacman -S ollama) or check Settings › Language model, then try again.",
TurnError::Llm(LlmError::Http { status: 401 | 403, .. }) => "The local core rejected authentication. Check its configuration.",
TurnError::Llm(LlmError::Http { status: 409 | 429, .. }) => "The local core is busy. Please wait and try again.",
TurnError::Llm(LlmError::Http { status: 500..=599, .. }) => "The local model could not finish this response. Please try again.",
@@ -135,6 +153,8 @@ enum TurnError {
Timeout,
Empty,
ModelLoad,
ModelMissing,
Offline,
ToolLoop,
Llm(LlmError),
Internal(#[allow(dead_code, reason = "read through Debug in the failure log")] anyhow::Error),
@@ -145,7 +165,8 @@ impl TurnError {
match self {
Self::Timeout => "CAPRI_TIMEOUT",
Self::Empty => "CAPRI_LLM_RESPONSE_EMPTY",
Self::ModelLoad => "CAPRI_MODEL_NOT_READY",
Self::ModelLoad | Self::ModelMissing => "CAPRI_MODEL_NOT_READY",
Self::Offline => "CAPRI_LLM_NETWORK_ERROR",
Self::ToolLoop => "CAPRI_TOOL_LOOP",
Self::Llm(e) => e.code(),
Self::Internal(_) => "CAPRI_INTERNAL",
@@ -217,8 +238,9 @@ impl Engine {
paths,
settings: Mutex::new(settings),
backend: Mutex::new(backend.into()),
model,
model: Mutex::new(model),
capabilities: Mutex::new(capabilities.to_vec()),
local_caps: Mutex::new(capabilities.to_vec()),
catalog,
session: Mutex::new(session),
journal: Mutex::new(journal),
@@ -229,7 +251,11 @@ impl Engine {
context: Mutex::new(vec![]),
internet: AtomicBool::new(false),
fast_path: Mutex::new(None),
router: Mutex::new(None),
redact_input: Mutex::new(None),
classifier: Mutex::new(None),
pending_images: Mutex::new(vec![]),
pending_note: Mutex::new(String::new()),
routers: Mutex::new(vec![]),
reply_guard: Mutex::new(None),
compactor: Mutex::new(None),
after_turn: Mutex::new(None),
@@ -260,8 +286,18 @@ impl Engine {
*self.fast_path.lock() = Some(hook);
}
pub fn set_classifier(&self, classifier: Classifier) {
*self.classifier.lock() = Some(classifier);
}
/// Owner inputs that must not be kept in the visible history (AG-02, AG-04).
pub fn set_input_redactor(&self, hook: InputRedactor) {
*self.redact_input.lock() = Some(hook);
}
/// Adds a pre-model route after the existing ones.
pub fn set_router(&self, router: Router) {
*self.router.lock() = Some(router);
self.routers.lock().push(router);
}
pub fn set_reply_guard(&self, guard: ReplyGuard) {
@@ -327,13 +363,27 @@ impl Engine {
*self.settings.lock() = settings;
}
pub fn model(&self) -> &str {
&self.model
pub fn model(&self) -> String {
self.model.lock().clone()
}
/// Switches the local model (after a download or a model change). The conversation is kept.
/// `capabilities` replace the current ones only while the local backend is active.
pub fn set_model(&self, model: String, capabilities: &[String]) -> Result<(), String> {
if self.busy() {
return Err("Wait for the current reply to finish.".into());
}
if self.backend.lock().is_local() {
*self.capabilities.lock() = capabilities.to_vec();
}
*self.local_caps.lock() = capabilities.to_vec();
*self.model.lock() = model;
Ok(())
}
/// `Local · <model>` or `API · <host> · <model>`.
pub fn label(&self) -> String {
self.backend.lock().label(&self.model)
self.backend.lock().label(&self.model())
}
/// Switches between the local model and an API connection. The conversation is kept.
@@ -343,6 +393,7 @@ impl Engine {
return Err("Wait for the current reply to finish.".into());
}
*self.capabilities.lock() = backend.api_capabilities().unwrap_or_else(|| local_capabilities.to_vec());
*self.local_caps.lock() = local_capabilities.to_vec();
*self.backend.lock() = backend;
Ok(())
}
@@ -351,6 +402,31 @@ impl Engine {
self.capabilities.lock().iter().any(|c| c == capability)
}
/// The backend the conversation uses now (local Ollama or an API), for auxiliary calls.
pub fn backend(&self) -> LlmBackend {
self.backend.lock().clone()
}
/// Capabilities of the local model (the active ones when the local backend is in use).
pub fn local_capabilities(&self) -> Vec<String> {
if self.backend.lock().is_local() { self.capabilities.lock().clone() } else { self.local_caps.lock().clone() }
}
/// Capability of the active model or API (`tools`, `vision`, `thinking`).
pub fn supports(&self, capability: &str) -> bool {
self.has(capability)
}
/// Images (base64) sent with the next owner message; a context hook may call this.
pub fn attach_images(&self, images: Vec<String>) {
self.pending_images.lock().extend(images);
}
/// Context text added to the next owner message only (e.g. which screen a snapshot shows).
pub fn attach_note(&self, note: &str) {
self.pending_note.lock().push_str(note);
}
pub fn catalog(&self) -> &Arc<Catalog> {
&self.catalog
}
@@ -385,7 +461,7 @@ impl Engine {
pub async fn warm_up(&self) -> Result<()> {
let keep_alive = self.settings.lock().keep_alive;
let backend = self.backend.lock().clone();
tokio::time::timeout(self.deadlines.load, backend.load(&self.model, keep_alive))
tokio::time::timeout(self.deadlines.load, backend.load(&self.model(), keep_alive))
.await
.map_err(|_| anyhow::anyhow!("The model took too long to load."))??;
Ok(())
@@ -397,6 +473,122 @@ impl Engine {
Some(AvatarRef { id: id.into(), pose: frame.pose.clone(), expression: frame.expression.clone() })
}
/// A short line Capri says on her own (tap reaction, initiative): one model call without
/// tools or history. `clean` filters the raw text; a kept line is stored as an assistant
/// message (`origin` = `{"kind": …}`) and emitted like a turn so it is shown and spoken.
/// `Ok(None)`: the model gave nothing usable. `Err`: a reply is running or the model failed.
pub async fn say(&self, system: String, user: String, origin: serde_json::Value, clean: impl Fn(&str) -> Option<String>, emit: impl Fn(TurnEvent) + Send + Sync) -> Result<Option<String>, String> {
let cancel = {
let mut active = self.active.lock();
if active.is_some() {
return Err("A reply is already in progress.".into());
}
let token = CancellationToken::new();
*active = Some(token.clone());
token
};
let result = self.say_inner(system, user, origin, clean, &cancel, emit).await;
*self.active.lock() = None;
result
}
async fn say_inner(&self, system: String, user: String, origin: serde_json::Value, clean: impl Fn(&str) -> Option<String>, cancel: &CancellationToken, emit: impl Fn(TurnEvent) + Send + Sync) -> Result<Option<String>, String> {
let settings = self.settings.lock().clone();
let backend = self.backend.lock().clone();
let request = ChatRequest {
model: self.model(),
messages: vec![Message::new("system", system), Message::new("user", user)],
tools: vec![],
options: Options {
num_ctx: backend.context_tokens(&settings).min(4096),
temperature: settings.temperature,
repeat_last_n: settings.repeat_last_n,
num_gpu: (settings.acceleration == "cpu").then_some(0),
num_thread: settings.cpu_threads,
num_predict: Some(96),
},
keep_alive: settings.keep_alive,
stream: true,
think: self.has("thinking").then_some(false),
};
let call = tokio::time::timeout(self.deadlines.load + self.deadlines.first_text, backend.chat(&request, |_| {}));
let done = tokio::select! {
_ = cancel.cancelled() => return Ok(None),
done = call => match done {
Ok(Ok(done)) => done,
Ok(Err(e)) => return Err(e.to_string()),
Err(_) => return Err("Capri took too long to respond.".into()),
},
};
if !done.tool_calls.is_empty() || done.done_reason.as_deref() == Some("length") {
return Ok(None);
}
let Some(line) = clean(&done.content) else { return Ok(None) };
let turn_id = uuid::Uuid::new_v4().to_string();
let mut extra = serde_json::Map::new();
extra.insert("origin".into(), origin);
let message = JournalMessage {
id: uuid::Uuid::new_v4().to_string(),
turn_id: turn_id.clone(),
role: "assistant".into(),
text: line.clone(),
status: "complete".into(),
created_at: now(),
avatar: None,
follow_up: Some(false),
extra,
};
self.journal.lock().put(message).map_err(|e| e.to_string())?;
let observers = self.observers.lock().clone();
let send = |event: TurnEvent| {
for observer in &observers {
observer(&event);
}
emit(event);
};
send(TurnEvent::Started { turn_id: turn_id.clone(), text: String::new() });
send(TurnEvent::Delta { turn_id: turn_id.clone(), text: line.clone() });
send(TurnEvent::Completed { turn_id, text: line.clone() });
Ok(Some(line))
}
/// Keeps a line Capri said on her own (initiative) in the visible history and the model
/// session, so later replies know it was said. `label` describes its origin for the model.
pub fn record_line(&self, turn_id: &str, text: &str, avatar: Option<&str>, origin: serde_json::Value, label: &str) -> Result<()> {
let mut extra = serde_json::Map::new();
extra.insert("origin".into(), origin);
self.journal.lock().put(JournalMessage {
id: uuid::Uuid::new_v4().to_string(),
turn_id: turn_id.into(),
role: "assistant".into(),
text: text.into(),
status: "complete".into(),
created_at: now(),
avatar: avatar.and_then(|id| self.avatar_ref(id)),
follow_up: Some(false),
extra,
})?;
let content = if label.is_empty() { text.to_string() } else { format!("[{label}] {text}") };
self.session.lock().append(Some(turn_id), &[("assistant", Message::new("assistant", content))])?;
Ok(())
}
/// Sends a recorded line to the observers (voice, approval cleanup) like a finished turn.
pub fn announce(&self, turn_id: &str, text: &str, avatar: Option<&str>) {
let observers = self.observers.lock().clone();
let mut events = vec![TurnEvent::Started { turn_id: turn_id.into(), text: String::new() }];
if let Some(id) = avatar {
events.push(TurnEvent::Avatar { turn_id: turn_id.into(), id: id.into(), follow_up: false });
}
events.push(TurnEvent::Delta { turn_id: turn_id.into(), text: text.into() });
events.push(TurnEvent::Completed { turn_id: turn_id.into(), text: text.into() });
for event in &events {
for observer in &observers {
observer(event);
}
}
}
/// Runs one owner turn. `Err` is a validation message shown to the owner without starting a turn.
pub async fn submit(&self, text: &str, emit: impl Fn(TurnEvent) + Send + Sync) -> Result<(), String> {
let text = text.trim();
@@ -456,17 +648,23 @@ impl Engine {
for hook in hooks {
context.push_str(&hook(text.to_string()).await);
}
Message::new("user", format!("{text}{}{context}", prompt::envelope(&state)))
context.push_str(&std::mem::take(&mut *self.pending_note.lock()));
let mut message = Message::new("user", format!("{text}{}{context}", prompt::envelope(&state)));
message.images = std::mem::take(&mut *self.pending_images.lock());
message
}
async fn run(&self, text: &str, cancel: &CancellationToken, emit: &(impl Fn(TurnEvent) + Send + Sync)) -> Result<()> {
let turn_id = uuid::Uuid::new_v4().to_string();
let created = now();
// A refused credential note is answered, but its text is never stored or echoed.
let redactor = self.redact_input.lock().clone();
let shown = if redactor.is_some_and(|r| r(text)) { CREDENTIALS_OMITTED } else { text };
let user = JournalMessage {
id: uuid::Uuid::new_v4().to_string(),
turn_id: turn_id.clone(),
role: "user".into(),
text: text.into(),
text: shown.into(),
status: "complete".into(),
created_at: created.clone(),
avatar: None,
@@ -479,7 +677,7 @@ impl Engine {
journal.put(user)?;
journal.put(reply.clone())?;
}
emit(TurnEvent::Started { turn_id: turn_id.clone(), text: text.into() });
emit(TurnEvent::Started { turn_id: turn_id.clone(), text: shown.into() });
let fast = self.fast_path.lock().clone();
if let Some(answer) = fast.and_then(|f| f(text)) {
@@ -495,8 +693,8 @@ impl Engine {
return Ok(());
}
let router = self.router.lock().clone();
if let Some(router) = router {
let routers = self.routers.lock().clone();
for router in routers {
let routed = router(text.to_string(), turn_id.clone(), cancel.clone()).await;
if cancel.is_cancelled() {
reply.status = "interrupted".into();
@@ -519,7 +717,18 @@ impl Engine {
}
}
let (mode, tools) = self.tool_mode(text);
let (mut mode, mut tools) = self.tool_mode(text);
let classifier = self.classifier.lock().clone();
if mode == PromptMode::Tools
&& let Some(classify) = classifier
{
// The two owner messages before this one (this one is already in the journal).
let mut context: Vec<String> = self.journal.lock().messages.iter().rev().filter(|m| m.role == "user").skip(1).take(2).map(|m| m.text.clone()).collect();
context.reverse();
if classify(text.to_string(), context).await {
(mode, tools) = (PromptMode::Dialogue, vec![]);
}
}
let user_message = self.user_message(text, mode).await;
let mut output = Output::new(&self.catalog);
let mut calls: Vec<ToolCallRecord> = Vec::new();
@@ -604,8 +813,10 @@ impl Engine {
let settings = self.settings.lock().clone();
let backend = self.backend.lock().clone();
// Model preparation has its own deadline so a cold load is not counted as "no text".
match tokio::time::timeout(self.deadlines.load, backend.load(&self.model, settings.keep_alive)).await {
match tokio::time::timeout(self.deadlines.load, backend.load(&self.model(), settings.keep_alive)).await {
Ok(Ok(())) => {}
Ok(Err(LlmError::Http { status: 404, .. })) => return Err(TurnError::ModelMissing),
Ok(Err(LlmError::Network { .. })) => return Err(TurnError::Offline),
Ok(Err(e)) => {
tracing::warn!("model load failed: {e}");
return Err(TurnError::ModelLoad);
@@ -633,7 +844,7 @@ impl Engine {
let mut settled_retry = false;
for _ in 0..MAX_MODEL_CALLS {
let request = ChatRequest {
model: self.model.clone(),
model: self.model(),
messages: messages.clone(),
tools: if settled_retry { vec![] } else { specs.clone() },
options: Options {
@@ -912,6 +1123,40 @@ mod tests {
engine.submit("salut capri", |_| {}).await.unwrap();
let last: serde_json::Value = serde_json::from_slice(&server.received_requests().await.unwrap().last().unwrap().body).unwrap();
assert!(last.get("tools").is_none());
// So does the request router's small-talk decision, which sees the earlier owner messages.
let seen = Arc::new(Mutex::new(vec![]));
let context = seen.clone();
engine.set_classifier(Arc::new(move |_text: String, previous: Vec<String>| {
*context.lock() = previous;
Box::pin(async { true })
}));
engine.submit("tell me a joke", |_| {}).await.unwrap();
let last: serde_json::Value = serde_json::from_slice(&server.received_requests().await.unwrap().last().unwrap().body).unwrap();
assert!(last.get("tools").is_none());
assert_eq!(seen.lock().last().map(String::as_str), Some("salut capri"));
}
#[tokio::test]
async fn say_stores_and_emits_a_filtered_line() {
let server = MockServer::start().await;
Mock::given(method("POST")).and(path("/api/chat"))
.respond_with(ResponseTemplate::new(200).set_body_string(line("*Hey*, easy on the hand! 😄", false) + &line("", true))).mount(&server).await;
let dir = tempfile::tempdir().unwrap();
let engine = Engine::new(Paths::under(dir.path().to_path_buf()), Settings::default(), Ollama::new(server.uri()), "m".into(), &[], Arc::new(Catalog::fallback())).unwrap();
let seen = Arc::new(Mutex::new(vec![]));
let observed = seen.clone();
engine.add_observer(Arc::new(move |e: &TurnEvent| observed.lock().push(format!("{e:?}"))));
let events = Mutex::new(vec![]);
let said = engine.say("sys".into(), "user".into(), serde_json::json!({"kind": "avatar-click"}), crate::reaction::clean_line, |e| events.lock().push(e)).await.unwrap();
assert_eq!(said.as_deref(), Some("Hey, easy on the hand!"));
assert!(matches!(events.lock().last(), Some(TurnEvent::Completed { text, .. }) if text == "Hey, easy on the hand!"));
assert_eq!(seen.lock().len(), 3, "the voice observer gets the line too");
let stored = engine.history().pop().unwrap();
assert_eq!((stored.role.as_str(), stored.extra["origin"]["kind"].as_str()), ("assistant", Some("avatar-click")));
assert!(!engine.busy());
// A line the filter rejects is neither stored nor shown.
assert_eq!(engine.say("s".into(), "u".into(), serde_json::json!({}), |_| None, |_| {}).await.unwrap(), None);
assert_eq!(engine.history().len(), 1);
}
#[tokio::test]
@@ -937,6 +1182,15 @@ mod tests {
assert!(matches!(events.into_inner().last().unwrap(), TurnEvent::Completed { text, .. } if text == "Done."));
let calls = server.received_requests().await.unwrap().len();
assert_eq!(calls, 0, "a note never reaches the model");
// A refused credential note is answered but never kept in the visible history.
engine.set_input_redactor(Arc::new(|t: &str| t.contains("password")));
engine.set_fast_path(Arc::new(|t: &str| t.starts_with("remember that").then(|| "I can’t save passwords.".to_string())));
let started = Mutex::new(String::new());
engine.submit("remember that my password is hunter22", |e| if let TurnEvent::Started { text, .. } = e { *started.lock() = text }).await.unwrap();
assert_eq!(*started.lock(), CREDENTIALS_OMITTED);
assert!(engine.history().iter().all(|m| !m.text.contains("hunter22")));
let transcript = std::fs::read_to_string(dir.path().join("data/desktop/transcript.json")).unwrap();
assert!(!transcript.contains("hunter22") && transcript.contains(CREDENTIALS_OMITTED));
let long = "x".repeat(600);
for _ in 0..3 {
engine.submit(&long, |_| {}).await.unwrap();
+1
View File
@@ -2,6 +2,7 @@
pub mod engine;
pub mod journal;
pub mod prompt;
pub mod reaction;
pub mod route;
pub mod session;
pub mod stream;
+152
View File
@@ -0,0 +1,152 @@
//! Short lines Capri says on her own, outside a conversation turn (spec 03 AV-17 tap reactions,
//! §6.2 prompt and output filter, §6.3 spoken cues). Delivered through [`crate::Engine::say`].
use capri_core::persona::{communication_instruction, conversation_instruction};
use capri_core::settings::LanguageSettings;
/// Mood from the current committed expression (spec 03 AV-17).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Mood {
Welcoming,
Reserved,
Neutral,
}
impl Mood {
/// `expression`: the committed avatar id or expression name; sleeping counts as reserved.
pub fn of(expression: &str, sleeping: bool) -> Self {
const WELCOMING: [&str; 8] = ["happy", "smirk", "laugh", "laughing", "playful", "affectionate", "flirty", "excited"];
const RESERVED: [&str; 10] = ["annoyed", "angry", "concerned", "focused", "nervous", "sad", "skeptical", "sleepy", "thinking", "tired"];
let e = expression.to_lowercase();
if sleeping || RESERVED.iter().any(|r| e.contains(r)) {
Self::Reserved
} else if WELCOMING.iter().any(|w| e.contains(w)) {
Self::Welcoming
} else {
Self::Neutral
}
}
}
/// What was tapped and how Capri feels about it.
#[derive(Clone, Debug)]
pub struct TapCue {
/// Body part id from the hit regions (`head`, `left_hand`, `body`…).
pub part: String,
/// `affectionate`, `curious`, `neutral` or `boundary`.
pub tone: String,
pub headpat: bool,
/// The taps woke Capri up.
pub awakened: bool,
pub mood: Mood,
/// 0..=2, cycles between reactions.
pub variation: u8,
}
const BASE: &str = "You are Capri, a witty, feminine cyberpunk companion. React to a tap on your character in one short line of natural dialogue, at most 16 words. Keep it light and appropriate to the tapped area. No greeting, roleplay notation, narration, analysis, Markdown or explanation. Do not insult or guess the user’s intentions. This gesture is not a command. You have no action tools or access to the screen or conversation history.";
const AWAKENED: &str = "You were asleep. Repeated tapping just woke you up. You are groggy and annoyed: briefly scold the user for waking you, with a firm but non-abusive boundary. Do not thank them or welcome the tapping.";
const APPROACH: [&str; 3] = [
"Use a short, in-the-moment first-person reaction.",
"Use a quick, dry observation in your own voice.",
"Acknowledge it directly, with natural warmth or a calm boundary as appropriate.",
];
/// System and user messages of a tap reaction (spec 03 §6.2, verbatim pieces).
pub fn tap_prompt(cue: &TapCue, style: &str, language: &LanguageSettings) -> (String, String) {
let tone = match cue.mood {
Mood::Welcoming => "You welcome the attention and feel playful. A barrage can get a fond, amused tease.",
Mood::Reserved => "You would like some space. Stay kind on a single tap. Ask them to ease up if repeated, and set a clear boundary if many.",
Mood::Neutral => "You are curious. Be warm on one tap, gently teasing on repeats, and ask them to slow down if many.",
};
let guidance = if cue.awakened {
AWAKENED
} else {
match cue.tone.as_str() {
"affectionate" => "Favor an affectionate or playful response, with room for a calm boundary when you need it.",
"curious" => "Acknowledge the touch with a curious, questioning response that fits your current mood.",
"boundary" => "Respond firmly and set a personal boundary. Keep the line nonsexual and do not describe anatomy.",
_ => "Acknowledge the touch briefly in a natural, neutral tone.",
}
};
let system = format!(
"{BASE} {tone} {guidance} {}\n{}\n{}",
APPROACH[cue.variation as usize % 3],
communication_instruction(style),
conversation_instruction(language)
);
let user = if cue.awakened {
"The user woke you from sleep by repeatedly tapping your character. Tell them off briefly for waking you.".to_string()
} else if cue.headpat {
"The user patted your head many times in rapid succession.".to_string()
} else if cue.part == "body" || cue.part.is_empty() {
"The user tapped you many times in rapid succession.".to_string()
} else {
format!("The user tapped your {} many times in rapid succession.", cue.part.replace(['_', '-'], " "))
};
(system, user)
}
/// Output filter (spec 03 AV-17): ≤320 raw chars; emoji, `*` and backticks removed; ≤160 chars
/// and ≤24 words; no control characters, `<`, `>`, avatar markers or `;listen`.
pub fn clean_line(raw: &str) -> Option<String> {
if raw.chars().count() > 320 {
return None;
}
let emoji = |c: char| matches!(c as u32, 0x1F000..=0x1FAFF | 0x2600..=0x27BF | 0xFE0F | 0x200D);
let text: String = raw.chars().filter(|&c| c != '*' && c != '`' && !emoji(c)).collect();
let text = text.trim().trim_matches('"').trim();
let lower = text.to_lowercase();
if text.is_empty()
|| text.chars().count() > 160
|| text.split_whitespace().count() > 24
|| text.chars().any(|c| c.is_control() || c == '<' || c == '>')
|| lower.contains("[avatar:")
|| lower.contains("[аватар:")
|| lower.contains(";listen")
{
return None;
}
Some(text.to_string())
}
/// Spoken cue on the first tap of a sequence (spec 03 §6.3). Order of the table:
/// affectionate, affectionate-when-reserved, curious, neutral, boundary. Only the languages
/// whose table is quoted in the spec are known; others stay silent.
pub fn spoken_cue(language: &str, tone: &str, mood: Mood) -> Option<&'static str> {
let table: [&str; 5] = match language.split(['-', '_']).next().unwrap_or_default() {
"en" => ["Aww.", "Easy.", "Hm?", "Yeah?", "Hands off."],
"fr" => ["Oh, trop mignon.", "Doucement.", "Hein ?", "Oui ?", "Pas touche."],
"de" => ["Wie süß.", "Ganz ruhig.", "Hm?", "Ja?", "Finger weg."],
"ru" => ["Мило.", "Полегче.", "М?", "Да?", "Руки прочь."],
_ => return None,
};
Some(match tone {
"affectionate" if mood == Mood::Reserved => table[1],
"affectionate" => table[0],
"curious" => table[2],
"boundary" => table[4],
_ => table[3],
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn prompt_filter_and_cues() {
let cue = TapCue { part: "left_hand".into(), tone: "curious".into(), headpat: false, awakened: false, mood: Mood::of("capri-happy", false), variation: 4 };
let (system, user) = tap_prompt(&cue, "", &LanguageSettings::default());
assert!(system.starts_with(BASE) && system.contains("A barrage can get a fond") && system.contains(APPROACH[1]));
assert_eq!(user, "The user tapped your left hand many times in rapid succession.");
let woke = TapCue { awakened: true, ..cue };
assert!(tap_prompt(&woke, "", &LanguageSettings::default()).0.contains(AWAKENED));
assert_eq!(clean_line(" \"Hey, *careful* with that hand! 😄\" ").as_deref(), Some("Hey, careful with that hand!"));
assert_eq!(clean_line("[avatar:happy] hi"), None);
assert_eq!(clean_line(&"word ".repeat(30)), None);
assert_eq!(clean_line("a <b> c"), None);
assert_eq!(spoken_cue("fr", "affectionate", Mood::Reserved), Some("Doucement."));
assert_eq!(spoken_cue("en-US", "boundary", Mood::Neutral), Some("Hands off."));
assert_eq!(spoken_cue("ja", "curious", Mood::Neutral), None);
assert_eq!(Mood::of("anything", true), Mood::Reserved);
}
}
+6 -5
View File
@@ -36,7 +36,8 @@ pub struct ToolProgressGuard {
}
impl ToolProgressGuard {
/// Returns `Err` when the turn must stop with `CAPRI_TOOL_LOOP`.
/// Returns `Err` when the turn must stop with `CAPRI_TOOL_LOOP` (no detail: the caller maps it).
#[allow(clippy::result_unit_err)]
pub fn record(&mut self, tool: &str, args: &Value, result: &Value) -> Result<(), ()> {
if result["needsApproval"] == true || result["needsWindow"] == true {
return Ok(());
@@ -59,10 +60,10 @@ impl ToolProgressGuard {
}
let key = fingerprint(&[tool.into(), args.clone(), result.clone()]);
if !self.counts.contains_key(&key) {
if self.reads.len() >= 32 {
if let Some(old) = self.reads.pop_front() {
self.counts.remove(&old);
}
if self.reads.len() >= 32
&& let Some(old) = self.reads.pop_front()
{
self.counts.remove(&old);
}
self.reads.push_back(key.clone());
}
+4 -1
View File
@@ -11,6 +11,9 @@ pub fn size(message: &Message) -> usize {
message.content.len() + message.tool_calls.len() * 200
}
/// A stored message with its sequence number.
pub type Entry = (i64, Message);
/// The summary as the first model message (OpenClaw compaction format).
pub fn summary_message(summary: &str) -> Message {
Message::new(
@@ -77,7 +80,7 @@ impl Session {
/// Messages after the latest compaction boundary, with their sequence numbers, and that
/// compaction's summary.
pub fn since_boundary(&self) -> Result<(Vec<(i64, Message)>, Option<String>)> {
pub fn since_boundary(&self) -> Result<(Vec<Entry>, Option<String>)> {
let boundary: Option<(String,)> = self
.db
.query_row(