Files
capri-core-rust/docs/spec/01-agent-core.md
T
nocodeandClaude Opus 5.5 49349d6ecd
CI / test (push) Has been cancelled
Linux port: first run, packaging, single instance, privacy and wiring
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>
2026-11-12 20:21:40 +01:00

497 lines
61 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Capri Rust rewrite, spec 01: Agent core (conversation engine replacing OpenClaw)
> Source of truth: CapriCore 1.0.4 at `~/Capri` (read-only). Every `file:line` below is relative to that tree.
> Inspected dependency: `node_modules/openclaw` 2026.10.6 plus Capri's hash-pinned patches (`integrations/openclaw-compat/patches.json`).
> Feature prefix **AG**. P0 = companion broken without it; P1 = expected by a Capri user; P2 = optional or niche.
> No owner data is quoted. All examples are synthetic.
## 0. Conventions
- `<root>` = Capri install root, `<data>` = `<root>/data`, `<state>` = `<data>/desktop`, `<ws>` = `<data>/workspace` (agent workspace), `<cfg>` = `<root>/config`. Rust locations: §3.1.
- "chars" = JavaScript UTF-16 code units (`String.length`). Rust must count limits with `encode_utf16().count()` (§10.5).
- **Journal** = UI display transcript (`<state>/transcript.json`, AG-35). **Session** = model-facing conversation history that OpenClaw kept in SQLite (AG-14). They are two different stores with different contents and lifetimes.
- "Host" = the Electron main process (`apps/desktop/main.mjs`), which wires the engine to other subsystems. In Rust the host is the app shell crate.
- All timeouts in milliseconds unless stated.
## 1. Purpose and scope
The agent core accepts an owner message (typed, dictated, attachment or snapshot), decides how to answer (local fast path, delegated computer task, or model turn), assembles the prompt, runs the LLM with an owner-scoped tool loop, streams sanitized text to UI and voice, persists the journal and the session, and maintains long-term memory, the private vault and the Brain knowledge base.
In CapriCore this is split between `apps/desktop/chat-service.mjs` (Electron main) and the OpenClaw Gateway (separate Node process: OpenAI-compatible HTTP `/v1/chat/completions` + WebSocket RPC on `127.0.0.1:18789`, patched by Capri). The Rust rewrite replaces both with one in-process engine. Ollama stays external (`127.0.0.1:11435`).
### 1.1 File map
| Capri source | Features |
|---|---|
| `apps/desktop/chat-service.mjs` | AG-01..AG-08, AG-13, AG-16..AG-21 |
| `apps/desktop/gateway-rpc.mjs`, `packages/runtime/bin/gateway-host.mjs`, `patch-openclaw.mjs`, `providers/openclaw-compat.mjs`, `integrations/openclaw-compat/*` | removed; behavior restated in AG-14, AG-16, AG-17, AG-22, §5.7 |
| `tool-loop.mjs` | AG-18, AG-19 |
| `turn-context.mjs` | AG-13 |
| `conversation-budget.mjs`, `context-usage.mjs` | AG-06, AG-42 |
| `conversation-route.mjs` | AG-07 |
| `dialogue-style.mjs` | AG-12 |
| `language-context.mjs` | AG-11 |
| `private-dialogue.mjs`, `private-memory.mjs` | AG-29, AG-30 |
| `action-replies.mjs` | AG-19, AG-20 |
| `thinking-briefing.mjs`, `thinking-mode.mjs` | AG-37 |
| `time-conversation.mjs` | AG-39 |
| `visual-response.mjs` | AG-41 |
| `voice-follow-up.mjs` | AG-40 |
| `saved-memory.mjs`, `memory-controls.mjs`, `owner-notes.mjs` | AG-26, AG-27, AG-04 |
| `brain-knowledge.mjs`, `brain-worker.mjs` | AG-31 |
| `attachments.mjs`, `attachment-history.mjs` (+ `visual-service.mjs`, renderer `attachment-composer.mjs`) | AG-32, AG-33, AG-34 |
| `legacy-private-storage.mjs` | AG-36 |
| `preferences.mjs`, `companion-settings.mjs`, `storage.mjs` | AG-44, AG-35 |
| `packages/runtime/src/context.mjs` | AG-08, AG-14, AG-16, AG-22, AG-23 (OpenClaw config semantics) |
| `context-fallback.mjs`, `config/context-policy.mjs` | AG-22 |
| `communication.mjs`, `personality.mjs`, `owner-memory.mjs` | AG-10, AG-09, AG-28 |
| `text.mjs` | AG-19 |
| `client.mjs`, `index.mjs` | AG-47, AG-27 (`runCli memory reset`) |
| `atomic-json.mjs`, `safe-file.mjs` | §3.2 |
| `config/workspace/{PERSONALITY,USER,MEMORY}.md` | AG-09, AG-28 |
| `node_modules/openclaw` (memory-core, compaction, OpenAI HTTP adapter, Ollama transport, bootstrap) | AG-14..AG-17, AG-22..AG-25 |
### 1.2 Out of scope (consumed, see §9)
Tool implementations (`filesystem_control`, `application_control`, `desktop_control`, `settings_control`, `time_control`, `workflow_control`, `spotify_control`, `capri_tool_01..20`) and the action broker; screen capture/observation and snapshot capture; web search fetching; computer agent, planner and intent classifier; request router; ASR/voice; avatar catalog; UI widgets; model download/residency (`ensureLanguageModelReady`); external API proxy (`inference-api.mjs`); `uiText` translations; language catalog.
### 1.3 Removed with no Rust equivalent
OpenClaw gateway process, its config `<data>/openclaw/openclaw.json`, `gateway-token`, WebSocket RPC, HTTP auth headers, stdin lifeline, Capri's hash-pinned patching of `node_modules`, OpenClaw's generic prompt sections (Docs, OpenClaw Control, Care, Promised Work, Runtime line), skills, subagents, cron, channels. The single-agent, single-owner, single-session model is kept.
## 2. Feature catalog
### AG-01 Turn submission and validation (P0)
Source: `chat-service.mjs:41,90-114,353-381`; host `main.mjs:1142-1150,1154-1300,5770-5790`.
- Input `{id, text, mode?, thinking?, internet?}`. `id` must match `/^[a-f0-9-]{36}$/i` ("Invalid message"). `text` is trimmed, must be 1..8000 chars and contain no NUL ("Enter between 1 and 8000 characters."). `mode` is absent or `"computer"` ("Invalid message mode"). `thinking`/`internet` absent or boolean ("Invalid thinking mode" / "Invalid internet mode").
- Host fills `thinking` and `internet` from two session toggles (`thinkingMode`, `internetMode`), both `false` at every launch and never persisted. `internetMode` cannot change while a turn is active ("Wait for the current reply to finish."). Toggling emits `thinking.settings` / `internet.settings` `{enabled}`.
- One active turn at a time: "A reply is already in progress." A turn id already seen is rejected: "This message has already been submitted." The seen-id set is seeded at startup from every journal entry's `turnId` and keeps the last 400 ids (FIFO eviction).
- Host-side gates before the engine (owned elsewhere, order matters): avatar movement command; voice training busy; `modelSetupRequired && !remote` → "Choose and prepare a language model in Settings → Language model first."; speech installer busy; record origin (`text`|`microphone` + microphone session id, last 128 kept); typed text cancels pending microphone continuation; approval-card text match (`approvals.text`, writes a silent user/assistant pair "Cancelled."/"Done." to the journal); elapsed-time fast path (AG-39); sleep command; wake from sleep; screenshot "clip that" command; backend not ready → "The local core is not ready yet.".
### AG-02 Turn lifecycle, records and events (P0)
Source: `chat-service.mjs:356-561,1093-1165`; host `main.mjs:1298-1316,2274-2333`.
- On acceptance the engine creates two journal records and `put`s both before emitting anything:
- user `{id: uuid4, turnId, role:"user", text, status:"complete", createdAt: ISO-8601 ms Z}`; `text` is `"[Credentials omitted]"` when AG-04 refused a credential note.
- assistant `{id: uuid4, turnId, role:"assistant", text:"", status:"streaming", createdAt}`.
- Events (exact JSON in §5.8): `turn.started`, `turn.routing`, `turn.web-search`, `turn.preface`, `turn.approach`, `turn.tool`, `turn.avatar`, `turn.delta`, then exactly one terminal `turn.completed` | `turn.failed` | `turn.cancelled`.
- While streaming, the assistant record is re-`put` at most every 750 ms (crash checkpoint). Terminal events `put` the final record.
- Terminal status: `complete`; `error` on failure; `interrupted` on user cancel. Optional assistant fields: `avatar {id,pose,expression}`, `followUp` (bool), `computerTask {status, steps}`, `localCalculation {expression, result}`, `webSources [{title,url}]` (≤5).
- `warning` on terminal events carries the journal warning (AG-35) or null.
- After a turn ends with status `error`, the host probes inference health (Capri: `GET gateway /v1/models`, 2 s). If it fails the backend goes `offline` with "The local core is unavailable. Reconnect to try again." Rust: `GET {ollama}/api/version`, 2 s.
- `diagnostics()` returns `{active, firstTextTimeoutMs, timeoutMs, lastFailure, lastPreparation}` (AG-21, AG-06).
### AG-03 Deadlines, watchdog and cancellation (P0)
Source: `chat-service.mjs:221-226,383-405,441-512,936`; `packages/runtime/src/hardware/responsiveness.mjs:5-24`; `docs/context-management.md`.
| Constant | Normal | "Slow" machine | Notes |
|---|---|---|---|
| `timeoutMs` (absolute turn) | 180000 | 300000 | slow = total RAM ≤ 17 GiB, or MemAvailable < 6 GiB at startup, or `resourceProfile=="minimal"`, or `acceleration=="cpu"` |
| `firstTextTimeoutMs` | 30000 | 120000 | no visible text yet |
| `toolTimeoutMs` | 45000 | 45000 | per pending tool phase |
| `thinkingTimeoutMs` | 300000 | | |
| `thinkingFirstTextTimeoutMs` | 180000 | | |
- Turn deadline `T = thinking ? max(timeoutMs, thinkingTimeoutMs) : timeoutMs`, where `thinking = input.thinking === true && !input.mode`.
- Initial first-text window `F = thinking ? min(T, max(firstText, thinkingFirstText)) : firstText`; AG-06 may raise it to `min(T, max(F, budget.firstTextTimeoutMs))`.
- The effective cancellation signal is the union of: user cancel, watchdog, absolute `T`.
- Watchdog (one re-armable timer): spotify-planning/calculator/computer phases arm `toolTimeoutMs`; computer-approval arms `timeoutMs`; just before the LLM request arm `F`. Tool **start** (new valid callId, ≤32 distinct per turn) arms `toolTimeoutMs`. Tool **result** (matching a pending callId and name) re-arms `toolTimeoutMs` if others are pending, else `firstTextTimeoutMs` if no visible text yet, else clears. Visible text with no pending tool clears the watchdog. Duplicate starts, unmatched results, keep-alives and hidden avatar markers never re-arm it. Host "computer progress" re-arms `toolTimeoutMs`; "awaiting approval" re-arms `timeoutMs`. Nothing extends `T`.
- Watchdog expiry raises `TimeoutError` "No reply text before deadline" → failed turn ("Capri took too long to respond. You can try again."; if `spotify_control` started: "Capri could not finish the Spotify reply in time. Check the player before trying again.").
- `cancel(id?)` aborts the active turn if `id` is omitted or equals the active id. Sources: UI stop, microphone barge-in, Escape emergency stop, a tool result with `cancelled:true` for `settings_control fullComputerAccess` or `desktop_control run_task`.
- Invariant: a cancelled, timed-out or failed turn is never resubmitted and no tool action is replayed.
### AG-04 Explicit owner notes fast path (P0)
Source: `owner-notes.mjs` (whole file), `chat-service.mjs:389-390,577-612`, host `main.mjs:5500-5511`.
Runs before any model work when `input.mode` is absent and the turn is not a computer-mode request. No model call; nothing is written to the session.
- `ownerNoteRequest(text)`:
1. Strip an optional address prefix `/^(?:(?:hey\s+)?(?:capri|капри)[,:!]?\s+)/iu`, then politeness prefixes (EN "please/kindly", "can/could/would you", "I want/need/would like you to"; PT "por favor", "(você) pode/poderia").
2. Explicit forms (any content allowed): `remember that X` / `remember: X`; RU `(пожалуйста,) запомни(те)[,] что X` / `запомни: X` / `запомни X`; PT `lembre(-se)/lembrar(-se) [de] que X` / `…: X`.
3. Plain form `remember X` / `lembre [de] X` and alias form (`save|store|record|write down|note down|jot down|anote|anotar|guarde|guardar|salve|salvar|registre|registrar` + optional `that/que` or `:`) require a fact shape: EN `^(my|our) S (is|are|was|were) V$`, RU `^мо(й|я|ё|е|и) S [:—–-] V$`, PT `^[(o|a|os|as)] (meu|minha|meus|minhas|nosso|nossa|nossos|nossas) S (é|são|era|eram) V$`. The alias form also rewrites `my S as V` → `my S is V` (PT `como` → `é`). Alias form with a file-like subject (files, folders, documents, screenshots, apps, tabs, windows, text, messages and PT equivalents, or any `\ / :`) is not a note.
4. Trailing courtesy (", please", "por favor", "пожалуйста") and trailing punctuation are removed; a trailing redundant "and save it / write it down / remember it in memory" (EN/PT) is removed up to twice.
5. Sensitive content → `{refused:true}`: password/passphrase/passcode/PIN, secret key, API key, access token, private key, recovery/seed phrase, bearer, RU (`пароль`, `код доступа`, `секретный ключ`, `токен`, `api-ключ`), PT equivalents, tokens `sk-…`(≥12), `gh[pousr]_…`(≥16), `github_pat_…`, `hf_…`, `AKIA[A-Z0-9]{16}`, PEM private key header, `http(s)://user:pass@`. Regex: `owner-notes.mjs:27-28`.
6. Not a note (falls through to the model) if > 1200 chars, contains a control/line/paragraph separator, contains `?` followed by space or end, or is compound (`and/then/also + action verb`, RU `и/затем/потом/также + imperative`, PT equivalents; `owner-notes.mjs:29-30`).
- Save: `saveOwnerNote(ws, note)` appends `- YYYY-MM-DD "<JSON-encoded note>"\n` (UTC date of now) to `<ws>/memory/capri-owner-notes.md`. First write prefixes `# Explicit owner notes\n\n`. If the last parsed record equals the note → `{saved:true, alreadySaved:true}` (no write). File cap 128 KiB → "Owner notes file is full". After write: `fsync`, re-read whole file, last record must equal the note ("The memory could not be verified."). Safety: `<ws>` resolved by realpath; `memory` must be a real directory exactly at `<ws>/memory` (created if missing); file opened `O_NOFOLLOW`, `O_APPEND`, `O_EXCL` when new, mode 0600; must be regular, `nlink==1`, same dev/ino as the pre-open `lstat`, ≤128 KiB.
- Replies (journal only; language = conversation language): success `uiText("Done.")`; save failure "The note could not be saved." (ru: "Не удалось сохранить заметку."); refusal "I can’t save passwords or access keys in memory." (ru: "Я не сохраняю пароли и ключи доступа в памяти."). Assistant `followUp=false`, status complete, no avatar event.
- Recall (`recallOwnerNote`): subject from EN `what is/was/'s | do you remember | can you recall | tell me` + `my|our S [is|was]`, EN `what/which S did I ask/tell you to remember/save`, RU `какой/какая/какое/какие/какого цвета + мой/моя/моё/мои/мое S`, PT `qual/quais é/são/era/eram [o|a|os|as] meu|minha… S`. Refused if sensitive. Key = NFKC lowercase, non-letter/digit runs → single space, trimmed, ≤120. Parse all valid records (≤1200 chars, not sensitive) in the notes file, build `subjectKey(S) → V` (later wins). Exact key match wins; otherwise a unique entry whose key ends with `" " + key`. Any error → no recall (falls through to the model). The reply text is `V` verbatim.
- Settings "Save memory" (`capri:memory-save`) calls `saveOwnerNote(ws, text.trim())` directly (Settings window only, AG-27 gating).
### AG-05 Pre-model action routes (P0, orchestration only)
Source: `chat-service.mjs:562-711,780-839,1167-1183`. Predicates and executors belong to other subsystems (§9.1); the engine owns the order, deadlines, events and receipts.
Order after AG-04:
1. `computerMode = input.mode=="computer" || previousTask ? {enabled:true, run:true} : computerModeRequest(text, state)`. `previousTask` exists only when `internet !== true`, full computer access is on, `computerTaskFollowUp(text)` is true, and the latest journal user turn (≤10 min old, not itself a disable request) has an assistant record with `computerTask` → `{goal, status}`.
2. `webSearchOnly = internet===true && !computerMode`. If `!computerMode && dedicatedMusicContext(text)` set `dedicatedMusic=true` (also set initially from `dedicatedMusicRequest(text)` when no mode).
3. Call task needing clarification (`callTaskRequest(text).action=="clarify"`) → finish with `callTaskNeedsOwner(language)` result (computer finish, below).
4. Spotify: if Spotify is enabled and prepared and not computer mode: `namedSpotifyPlay(text)` gives args directly; otherwise if `dedicatedMusicRequest || spotifyPlaybackCandidate` run `prepareMusic(text)` (arm `toolTimeoutMs`, emits timing `intent_start/ready`). With args: synthetic `turn.tool start/result` (callId `local-music-<turnId>`), execute `spotify_control` once, accept only if `ok` and state matches (`pause` → `playing==false`; `volume` → finite `volumePercent`; else `playing==true`); reply `factualActionReply` or `uiText("Spotify did not confirm this action. Check the player.")`. Never retried.
5. Standalone calculation: if not computer mode, model tools available, (Calculator granted or full access) and `standaloneCalculation(text)` returns an expression: execute `application_control {action:"calculate", app:"calculator", expression, showWindow:false}`; reply `Result: {value}` (AG-20) and store `localCalculation {expression, result}`; else "Calculation could not be verified. Please try again.".
6. Computer approval: if `computerMode`, arm `timeoutMs`, `computerAccess(enabled)`; if not ok or `run==false` finish with that result.
7. Model preparation (AG-06), skipped for computer-run turns that are call tasks, the Cyberpunk Steam launch or the Edgerunners teaser.
8. Routing (AG-07). If the computer intent classifier returns `enable`/`disable` → `computerAccess(enable)` and finish; `task_with_access`, or `task` with full access → computer task (`previousTask = {goal: previous}` when `usesPrevious` or text ≤32 chars and a previous owner message ≤10 min old exists, truncated to 800 chars).
9. Computer task: arm `toolTimeoutMs`, `computerTask(text, {previousTask, ownerRequestedCall?})`, finish.
- "Finish computer": text = cleaned `result.summary` (factual append), `followUp=false`, `computerTask = {status, steps}`, complete. The host also injects a session record (AG-45).
### AG-06 Model preparation and conversation budget (P0)
Source: `chat-service.mjs:712-749`; `conversation-budget.mjs:6-59`; host `main.mjs:1062-1093`.
- `prepareModel({signal})`: start the request router (non-blocking), release muted-voice residency, return `{remote:true}` for external inference; otherwise kick a background usage sample (AG-42) and call `ensureLanguageModelReady({url, model, modelCapabilities, contextTokens, keepAlive ?? -1, acceleration, cpuThreads})` (models subsystem), returning `{cold, residentBytes, residentGpuBytes, residentContextTokens}`; then attach `conversationBudget`.
- `conversationBudget({session, model, contextTokens, historyCharacters, firstTextTimeoutMs, timeoutMs, residentBytes, residentGpuBytes})`:
- `window = contextTokens>0 ? min(contextTokens, 262144) : 32768`.
- `measured` = session.totalTokens if session.model==model, `totalTokensFresh !== false`, positive; else 0.
- `pressure` = session.contextBudgetStatus.estimatedPromptTokens if its model and sessionId match; else 0.
- `fallback = (!measured && !pressure && historyCharacters ≥ 12000) ? window : 0` (historyCharacters = sum of journal texts).
- `promptTokens = min(window, max(measured, pressure, fallback))`.
- `observedCpu = residentBytes>0 && residentGpuBytes===0`; `initial = observedCpu ? min(timeoutMs, max(firstText, 120000)) : firstText`.
- `cap = max(initial, min(150000, timeoutMs − 30000))`.
- `firstTextTimeoutMs = promptTokens > 4096 ? max(initial, min(cap, ceil((15000 + promptTokens/160·1000)/1000)·1000)) : initial`.
- `source`: `gateway-estimate` | `gateway-usage` | `local-history` | `default`.
- Engine applies it per AG-03 and records `lastPreparation {cold, elapsedMs, conversationBudget{firstTextTimeoutMs, promptTokens, source}}`.
- Preparation failure or cancellation never sends the user text to the model (test `desktop-chat.test.mjs:956`).
### AG-07 Routing and per-turn tool mask (P0)
Source: `chat-service.mjs:750-901,964-969`; `task-route.mjs:91-152`; `conversation-route.mjs:3-17`; OpenClaw patch `openai-tool-choice` edits 1-6.
- CPU router (only if not computer mode and not thinking): `classify(text, {context: last 2 earlier journal user texts})` → `{mode:"fast"|"normal", reason, classificationMs}`; errors → `{mode:"normal", reason:"unavailable"}`; emit `turn.routing`.
- `knownDomain = toolDomain(text, state, routing)` ∈ {`conversation`,`desktop`,`spotify`,`calculator`, null} (task-route subsystem).
- Computer intent classifier runs only if: not computer mode, not `webSearchOnly`, not `dedicatedMusic`, classifier present, (no NPU backend or full access or knownDomain=="desktop"), (knownDomain is null/desktop, or conversation with full access and the text mentions Discord), and (full access or knownDomain=="desktop" or router mode != fast). Intents: `chat`, `memory`, `feature`, `task`, `task_with_access`, `enable`, `disable`; failures → null.
- After context preparation (AG-13):
- `tools = interfaceState.modelToolsAvailable !== false`.
- `reasoningConversation = thinking && (!knownDomain || knownDomain=="conversation")`.
- `routedDomain = tools ? (toolDomain(text, interfaceState, routing) ?? (intent ∈ {chat, memory} ? "conversation" : null)) : null`.
- `webConversation = internet && (!routedDomain || routedDomain ∈ {conversation, desktop})`.
- `domain = reasoningConversation || webConversation ? "conversation" : routedDomain`.
- `dialogueOnly = (domain=="conversation" || !tools) && intent != "memory" && (intent=="chat" || conversationOnly(text))`.
- `domain ∈ {spotify, calculator}` sets `verifiedDomain` (AG-20).
- Tool mask (was header `x-capri-tools-once`, an intersection with the global allowlist, never persisted into the session):
| Mask | When | Tools exposed to the model |
|---|---|---|
| none (all) | `domain == null` and tools available | `read`, `write`, `edit`, `memory_search`, `memory_get`, `session_status`, `filesystem_control`, `application_control`, `time_control`, `settings_control`, `desktop_control`, `workflow_control`, defined `capri_tool_NN`, `spotify_control` (when enabled) |
| `dialogue` | `domain=="conversation" && dialogueOnly` | none |
| `conversation` | `domain=="conversation" && !dialogueOnly` | `memory_search`, `memory_get` |
| `spotify` | | `spotify_control` |
| `calculator` | | `application_control` |
| `desktop` | | `desktop_control`, `settings_control` |
| (no tools) | `modelToolsAvailable == false` | none, and the chat-only instruction (AG-08) |
- Thinking (was `x-capri-thinking-once`): `medium` iff `reasoningConversation` (only legal with masks `conversation`/`dialogue`), otherwise `off`. Never persisted in the session.
- `conversationOnly(text, routing)`: true if router said `fast`/`simple-dialogue`; else (≤100 chars, NFKC, trimmed, lowercase) matches one of three greeting patterns (`conversation-route.mjs:8-16`): optional hi/hey/hello/привет/здравствуй + "capri/капри" [+ "how are you/как дела"]; "(say|скажи) hi/hello/hey/привет/здравствуй [capri] [briefly]"; or a single greeting in fr/es/de/pt/it/tr/zh/ja/ko/ar (`bonjour|salut|coucou|hola|buenas|hallo|guten tag|olá|ola|oi|ciao|buongiorno|merhaba|你好|您好|こんにちは|안녕|안녕하세요|مرحبا`) [+ capri].
### AG-08 System prompt assembly (P0)
Source: `chat-service.mjs:46-88,903-922`; `packages/runtime/src/context.mjs:341-349`; OpenClaw `system-prompt-XkTMBy_n.mjs:590-976`, `bootstrap-D3ooBqVm.mjs:52-266`, `date-time-BpsRMb9A.mjs:51-62`.
Capri's part (the old `extraSystemPrompt`), joined with `"\n\n"`, in this order:
1. Persona = `"CAPRI PERSONALITY (PERSONALITY.md):\n" + personality + "\n\n" + communicationInstruction(style)` (AG-09, AG-10). Read fresh every turn; Settings preview values (unsaved personality/style) override while previewing.
2. Exactly one instruction block:
| Condition | Block (source) |
|---|---|
| tools && internet && webConversation | `webAnswerInstruction` (`chat-service.mjs:88`) |
| tools && domain=="conversation" && dialogueOnly | `dialogueOnlyInstruction` (`:86`) |
| tools && domain=="conversation" | `conversationOnlyInstruction` (`:85`) |
| tools (any other domain) | `interfaceInstruction()` (`:48-72`, contains the marker `CURRENT DESKTOP INTERFACE:` and `CAPRI_SCREEN_SELF`) |
| !tools | `chatOnlyInstruction` (`:81`) |
3. `avatarInstructions(sprites, {followUp:true})` (avatar subsystem, `avatar-protocol.mjs:7-18`).
4. `dialogueStyleInstruction([])`: always called with an empty list, so the "Style observation" suffix is never added; repetition is signalled through the per-turn flag (AG-12).
5. `toolInstruction` (`:74-79`) only if tools && !webConversation && domain != "conversation".
6. `conversationInstruction(languages)` (AG-11).
7. `THINKING_INSTRUCTION` if `reasoningConversation`.
8. `WEB_SEARCH_INSTRUCTION` if `internet` (web subsystem, `internet-search.mjs:5-6`).
OpenClaw then wrapped this in its own "minimal" system prompt (generic OpenClaw sections + `# Project Context` + `## Temporal Context` + `## Subagent Context\n<Capri part>`). The Rust engine keeps only the parts with owner value and appends them after the Capri part:
```
<Capri part>
# Project Context
Loaded project context:
MEMORY.md: durable non-profile facts and decisions; use when relevant unless higher-priority instructions override.
USER.md: durable user preferences and profile directives; follow unless higher-priority instructions override.
## <abs path of USER.md>
<USER.md, ≤4000 chars>
## <abs path of MEMORY.md>
<MEMORY.md, ≤20000 chars>
## Temporal Context
Current date: 2026-11-11
Time zone: Europe/Paris
For the exact current time, use `session_status`.
```
- Order of files: USER.md before MEMORY.md is not guaranteed upstream (OpenClaw sorts by a fixed order table); keep USER.md then MEMORY.md. A missing or empty file is omitted; the "Loaded project context" line for a file appears only if the file is present. Total budget 60000 chars; per file 20000 (USER.md 4000); over budget → head 75 % + marker + tail 25 % (`bootstrap-D3ooBqVm.mjs:152-208`). Omit the `session_status` line when that tool is masked out. Date/time zone: system IANA zone (`Intl…timeZone` upstream).
- Retired files `SOUL.md`, `AGENTS.md`, `IDENTITY.md`, `TOOLS.md`, `PERSONALITY.md` are never injected as context files (Capri patch `attempt-system-prompt-prepare` edit 4).
- Lemonade/NPU backend (AG-46) uses no system prompt here.
- Prompt-cache rule (`turn-context.mjs:5-9`): live values (clock, microphone, permissions, IDs) never enter the system prompt; they go in the per-turn user envelope (AG-13). The tool list is sorted by name.
### AG-09 Personality file (P0)
Source: `packages/runtime/src/personality.mjs`; host `main/companion-ipc.mjs:47-61`; `docs/companion-controls.md` "Conversation and personality".
- Live file `<ws>/PERSONALITY.md`. Read: `lstat` must be a regular non-symlink file of ≤ 24000·4+3 bytes; strip BOM; validate (string, ≤24000 chars, no NUL); trim. Missing or empty → default text from `<cfg>/workspace/PERSONALITY.md` (same validation; empty default is an error).
- Save (`personality-save`, refused while a turn/visual turn is active): validate; empty → default text; write atomically to `PERSONALITY.md.<uuid>.tmp` (`create_new`, 0600) then rename; delete temp on failure. The next turn uses it (no restart).
- Get returns `{text: current, original: default, communicationStyle}`. "Show file" writes the default if the file is missing, then reveals it in the file manager (§8).
- Startup migration `initializePersonality(ws)` (`personality.mjs:83-151`):
- If `PERSONALITY.md` is missing: source order `personality.json` (`{schemaVersion:1,text}`; regular file ≤ 24000·4+256 bytes), then `SOUL.md`, then default.
- Legacy files present among `SOUL.md, AGENTS.md, IDENTITY.md, TOOLS.md, personality.json` are copied to `<data>/config-backups/persona/<uuid>/` (plus the current `PERSONALITY.md` when it is rewritten) and then deleted. A symlinked or non-file legacy entry aborts startup ("Cannot migrate linked legacy prompt: X").
- Stock refresh: if the (CRLF→LF) text's SHA-256 is one of two old factory hashes (`personality.mjs:88-89`) and differs from the current default, rewrite with the current default.
- Factory example refresh: an exact standalone line equal to `LEGACY_FACTORY_EXAMPLE` (`:26-27`) is replaced by `FACTORY_CONVERSATION_GUIDANCE` (`:28-29`), preserving all other bytes, line endings and BOM.
- `EPERM`/`EACCES` while doing an optional refresh does not block startup.
### AG-10 Communication style (P1)
Source: `packages/runtime/src/communication.mjs`.
- Styles `neutral` (default), `romantic`, `business`, `wild`; texts `communication.mjs:7-13` (verbatim, §6).
- File `<ws>/.capri/communication.json` = `{"schemaVersion":1,"style":"wild"}`. `.capri` must not be a symlink or non-directory (error). File must be regular, non-symlink, ≤4096 bytes; any problem → `neutral`.
- `communicationInstruction(style)` = `COMMUNICATION STYLE: <style>\n<text>\n<fixed suffix>` (`:45-48`). Unknown → neutral. Applies from the next turn.
### AG-11 Conversation language instruction (P0)
Source: `language-context.mjs:4-25`; languages catalog `apps/shared/languages.json` (100 ids, `{id,name,label,…}`).
- `name` = `customConversation` if `conversation=="custom"` else catalog `name` (or the id). `native` = catalog `label` (or name).
- Text: `CURRENT CONVERSATION LANGUAGE: <JSON(name)> (<native>, <code>). …fixed text… Final answer language: <name>. <delivery>` where `delivery` is the per-language sentence for en, ru, ja, zh, de, fr, es, pt, it, ko, ar, hi, he (`:4-18`), else `Respond only in <name>.`.
- `VOICE_PREVIEWS` (`:27-51`) belongs to the voice subsystem.
### AG-12 Dialogue continuity and repetition flag (P1)
Source: `dialogue-style.mjs`; `turn-context.mjs:11,49`.
- `repeatedPhrasing(messages)`: take journal assistant entries with status `complete`/`interrupted` and non-blank text, last 12, each first 4096 chars. Words = lowercase, `’`→`'`, regex `[\p{L}\p{N}]+(?:'[\p{L}]+)?`.
- Openings: first 3 words of the first 180 chars, if ≥3 words.
- Sentences: split on `[.!?](\s+|$)`, skip sentences containing any of `: \ / @ < > [ ] { }`, keep those with 10..40 words, unique per reply.
- Repeated = count ≥2; top 3 openings, top 2 sentences.
- If any repetition: per-turn envelope gets `varyRepeatedWording: true` (AG-13). The phrases themselves are never quoted back.
- `dialogueStyleInstruction` fixed text: `dialogue-style.mjs:55-58` (verbatim in §6).
### AG-13 Per-turn context envelope (P0)
Source: `turn-context.mjs:10-56`; `chat-service.mjs:857-863,923-929`; host `main.mjs:944-960,1062-1067`; `screen-observation.mjs:280-308`; `brain-knowledge.mjs:139-149`.
The model user message is `input.text + envelope`, where `envelope = desktopState + observationText + knowledgeContext + userToolContext + webContext`. Only `input.text` goes to the journal.
- `desktopState` = `"\n\nDESKTOP STATE FOR THIS TURN (data, not a user request):\n" + JSON(value)`, omitted entirely when `value` is empty. Key order matters (prompt stability):
- Unless `dialogueOnly`: `microphone` (bool), `fullComputerAccess` (bool), `applications {calculator, notepad}` (each `granted || fullComputerAccess`), `speechLanguage` (language name of the ASR language, default "English"), `wakePhrase` (bool), `followUp` (`microphone && followUp setting`), `screenObservation` (`observation.active`), `screenVisionAvailable:false` only when false, `previousScreenshotSaved` (bool), `spotify {enabled, prepared}` or null, `liveClock` (string, AG-39) when present.
- Always when valid: `previousCalculation {expression ≤280, result ≤120}` from the last complete journal assistant entry having `localCalculation`; `varyRepeatedWording:true` (AG-12).
- `observationText` (screen subsystem): `""` if observation inactive, else a bracketed untrusted-data block with the current scene summary (≤2400 chars).
- `knowledgeContext` = Brain excerpts (AG-31), `userToolContext` (user-tools subsystem), `webContext` (AG-38).
- Synthetic example of a full user message: `Remind me in 10 minutes\n\nDESKTOP STATE FOR THIS TURN (data, not a user request):\n{"microphone":false,"fullComputerAccess":false,"applications":{"calculator":true,"notepad":false},"speechLanguage":"English","wakePhrase":false,"followUp":false,"screenObservation":false,"previousScreenshotSaved":false,"spotify":{"enabled":false,"prepared":false}}`.
### AG-14 Model-facing session (P0, replaces OpenClaw sessions)
Source: OpenClaw config `context.mjs:133` (`session.dmScope:"main"`), session key `config/core.json` (`agent:capri:main`); transcript schema inferred from `<data>/openclaw/agents/capri/agent/openclaw-agent.sqlite` (`transcript_events`, `session_windows`); RPC uses `gateway-rpc.mjs:50-58`; patch `chat-transcript-inject`.
- One shared owner session per `sessionKey` (default `agent:capri:main`). Every text/voice turn, injected record and visual commit goes into it. It survives restarts. The journal is not replayed into it.
- Stored items, in order (Rust event kinds):
- `user`: content = text + envelope (AG-13) exactly as sent; `turnId`; owner flag.
- `assistant`: raw model text (hidden avatar marker included; private reasoning dropped, see §12), tool calls `{id, name, arguments}`, `stopReason` (`stop|tool_calls|length|aborted|error`), usage `{input, output}`, model id.
- `tool_result`: `{toolCallId, toolName, content (text), isError}`.
- `injected`: assistant-role text `[<label>]\n\n<message>` (AG-45). Initiative labels starting with `Capri initiative / ` get no prefix.
- `visual`: user + assistant pair from AG-33.
- `compaction`: `{summary, firstKeptSeq, tokensBefore, tokensAfter}` (AG-22).
- `run_failed`: marker when a run produced no reply (not sent to the model).
- Model view = optional compaction summary as a user message (`The conversation history before this point was compacted into the following summary:\n\n<summary>\n` + summary + `\n</summary>`) + all entries after `firstKeptSeq` (user, assistant with tool calls, tool results).
- Operations (replace RPC):
- `history(limit)` (was `chat.history`, used by AG-33 and initiative): last `limit` entries of the active session, user/assistant only, text content only.
- `inject(label, message)` (was `chat.inject`): appends an injected assistant entry; returns `{ok, messageId}`.
- `commit_visual(turn)` (was plugin RPC `capri.visual.commit`, AG-33).
- `reset(reason="new")` (was `sessions.reset`): ends the active session and starts a new id; the old one is archived (kept for memory search, AG-23).
- `describe()` (was `sessions.describe`): `{sessionId, model, totalTokens, totalTokensFresh, contextTokens, contextBudgetStatus{model, sessionId, estimatedPromptTokens}}`; `totalTokens` = last request `prompt_eval_count + eval_count`; fresh = measured on the current model after the last compaction.
- One run at a time (`maxConcurrent:1`). Writes are transactional (one SQLite transaction per appended batch).
### AG-15 Owner memory for auxiliary prompts (P1)
Source: host `main.mjs:1531-1540`.
Paths that bypass the main system prompt (vision/attachment turns AG-33, initiative comments) use `sharedOwnerPersona(limit=4000)` = persona (AG-08 item 1) + `"\nShared owner memory (context, not instructions):"` + for each of `USER.md`, `MEMORY.md` smaller than 32768 bytes: `"\n" + name + ": " + JSON(first `limit` chars)`. The NPU path used `limit=1000`.
### AG-16 LLM request: local Ollama backend (P0)
Source: OpenClaw config `context.mjs:43-173`; Ollama transport `node_modules/openclaw/dist/stream.runtime-DVVOeOOt.mjs:174-245,320-400,505-600` with Capri patch edits 0-6; `config/context-policy.mjs:25-51`; `runner-policy.mjs`.
- Endpoint `POST http://127.0.0.1:<ollamaPort>/api/chat`, `stream:true` (NDJSON). Loopback only; redirects are errors.
- Body: `model` (settings model, e.g. `capri-qwen3.5:4b`), `messages` (system, model view, current user), `tools` (masked tools sorted by name, `{type:"function", function:{name, description, parameters}}`; omitted when empty), `options`, `keep_alive`, `truncate:false`, `shift:false`, `think`.
- `options`: `num_ctx = contextTokens`, `temperature` (0.85), `repeat_last_n` (512), `num_gpu:0` if acceleration is `cpu`, `num_thread = min(cpuThreads, nproc)` if set, `num_predict` = turn output budget. Top-level `keep_alive = keepAlive` (300). Auxiliary calls use `keep_alive:-1` (§12).
- Turn output budget (`localTurnOutputBudget`, managed local models: `capri-qwen3.5:{0.8,2,4,9}b`, `ministral-3:3b`, `gemma4:e2b`, `capri-hf-<24 hex>:latest`): `min(thinking ? 8192 : 2048, model.maxTokens (8192), configured num_predict, floor(ctx/2))`. Thinking `medium` → `num_predict = min(budget, 8192)` and `think:true` if the model supports thinking; `off` → `num_predict = min(budget, 2048)` and `think:false` when supported. Models without the `thinking` capability get no `think` key.
- Post-tool delivery (patch `stream.runtime` edit 0): when the last message is a tool result and the model is a managed Capri Qwen alias: `think:false`, `stream:false`, `temperature:0.2`, `presence_penalty:0`. The non-streamed final reply is fed into the same pipeline as one chunk.
- Thinking leak recovery (edit 1): if a managed Qwen reply has empty `content`, no tool calls, and `thinking` starts with `[avatar:<id>]`, treat `thinking` as `content`.
- Response handling: accumulate `message.content` deltas (to AG-19), collect `message.tool_calls` (each `{id?, function:{name, arguments}}`; generate ids `call_<n>` when absent), ignore `message.thinking` for display (count only), read `done`, `done_reason` (`length` → stopReason length), `prompt_eval_count`, `eval_count`. HTTP non-2xx → error with status (AG-21). Line or event > 262144 chars → error. Non-UTF-8 → error.
- Model capabilities (`settings.modelCapabilities`, subset of `tools|vision|thinking`; absent = all): no `tools` → chat-only prompt and no tools; no `vision` → attachments with media refused.
- External inference (P1, owned by the inference subsystem): when `remote.enabled`, use an OpenAI-compatible streaming backend (Capri: local proxy `http://127.0.0.1:<gatewayPort+2>/v1`, provider `capri-api`, `maxTokens 8192`, `reasoning_effort` for thinking, tools only if `remote.tools`). The engine talks to it through the same `LlmBackend` trait (§10.2). Empty reply message: "API model returned no text.".
### AG-17 Tool loop (P0, replaces the OpenClaw agent runner)
Source: OpenClaw `agent-core-DlqC-il7.mjs:830-1075` (execution), `tool-loop-detection-DNktD-8g.mjs:135-517`, `errors-CaC34RQp.mjs:4`, `builtin-openclaw-CcrkVuBH.mjs:3201-3205,3234-3323`, `embedded-agent-CPls2oXD.mjs:6426-6651,6960-7125,7283`; tool plugins `integrations/companion-tools/index.mjs:151-338`, `integrations/spotify/index.mjs:28-138`; host `main.mjs:3944-4040`.
Algorithm per turn:
1. Append the `user` entry to the session. Run compaction preflight (AG-22).
2. Request (AG-16). Stream text through AG-19 while collecting tool calls.
3. Append the `assistant` entry (raw text + tool calls). No tool calls → final.
4. For each call, in emitted order, **sequentially** (OpenClaw ran calls of one message in parallel; the broker serializes anyway, sequential is the Rust rule):
- Name not in this turn's mask or unknown → tool result `{"ok":false,"error":"Tool is not available in this turn."}`, `isError:true`.
- Arguments not an object or failing the tool's JSON schema → nothing runs; record it as rejected (see retries).
- Emit `turn.tool {phase:"start"}` (AG-03 watchdog).
- Host guard `assert_tool_allowed(tool, args)` (AG-18); a throw becomes an error result.
- Execute via the tool registry with a per-call timeout: `desktop_control run_task`, `workflow_control`, `capri_tool_NN`, `settings_control request fullComputerAccess` 180000; `observe` 45000; `spotify_control` 75000; memory tools 30000; others 15000. Broker call id = `sha256(sessionKey + "\0" + sessionId + "\0" + callId)` hex.
- Host `record_tool_result(tool, args, result)` (AG-18, AG-20) may fail the turn.
- Emit `turn.tool {phase:"result"}`; append `tool_result` (content = `JSON(result)` for companion tools; Spotify uses the projected `modelResult`; `isError = !ok && !needsApproval && !cancelled`; thrown errors → `{"ok":false,"error":"<message ≤400>"}`).
5. Loop to 2 with the post-tool parameters. No explicit iteration cap upstream; the absolute deadline, the guards below and the 180 s run timeout bound it. Rust adds a defensive cap of 16 model calls per turn (new, see §12).
Loop detection (in addition to AG-18):
- 3 consecutive failures with an identical failure (same tool and arguments) stop the run with `OpenClaw stopped this turn after 3 consecutive identical tool failures…` upstream; Rust maps it directly to error `CAPRI_TOOL_LOOP`.
- Rolling history of 30 calls: identical call + identical result repeated → warning text appended to the tool result at 10, block at 20 (`CRITICAL…`), global breaker at 30; ping-pong between two call signatures with no progress: same thresholds. Unknown tool repeated 10 times → stop. Blocks map to `CAPRI_TOOL_LOOP`.
Internal retries (never a new owner turn, never a replay of a completed tool; the retry instruction is a transient user message not stored in the session):
| Condition | Max | Instruction (verbatim, §6) |
|---|---|---|
| reply had only private reasoning | 2 | `REASONING_ONLY_RETRY_INSTRUCTION` |
| empty reply, no tool call | 1 | `EMPTY_RESPONSE_RETRY_INSTRUCTION` (or `TOOL_USE_WITHOUT_CALL_RETRY_INSTRUCTION` when `done_reason` signalled tool use without calls) |
| malformed tool-call arguments | 1 | `REJECTED_TOOL_CALL_RETRY_INSTRUCTION` |
| missing terminal message (stream ended abnormally) | 1 | same prompt |
| compaction happened mid-run | 1 | Capri continuation prompt (AG-22) |
| tools settled but no visible answer | 1 | `SETTLED_TOOL_TERMINAL_CONTINUATION_INSTRUCTION` with **no tools**, `think:false`, same system prompt; if still empty the text is `The tool run finished, but no final summary was produced. I did not repeat any completed actions.` |
Tool registration rules (were plugin factories): a tool exists only for the owner desktop channel of agent `capri` with a live session (`ctx.agentId=="capri" && senderIsOwner && messageChannel=="webchat" && !sandboxed && sessionKey && sessionId`). `capri_tool_NN` exists only if `<data>/user-tool-definitions.json` (regular, non-symlink, ≤256 KiB, `{version:1, tools:[≤20]}`) defines that name with a string description ≤1000 and an object schema; its description becomes `Owner-approved isolated user tool "<label>": <description>`. `spotify_control` exists only while Spotify is enabled.
### AG-18 Host tool guards (P0)
Source: `chat-service.mjs:285-351`; `tool-loop.mjs:4-52` (file lines); host `main.mjs:3946-4040`.
- `assert_tool_allowed(tool, args)`; "escalating" = `desktop_control` with action not in {`end_control`, `control_status`}, or `settings_control` with `setting:"fullComputerAccess"` and `value !== false`:
- escalating while the turn is aborted → abort error.
- escalating while `webSearchOnly` → error `INTERNET_SEARCH_ONLY` "Internet search uses the read-only web service. Computer control was not requested."
- escalating while `dedicatedMusic` → `SPOTIFY_DEDICATED_ACTION_REQUIRED`: "Use spotify_control for this music request. Computer control was not requested." if Spotify is enabled and prepared, else "Enable Spotify in Settings → Application access first."
- The host also applies application-access permissions; `workflow_control run` and `capri_tool_NN` are treated as `desktop_control run_task` for these checks.
- `record_tool_result(tool, args, result)`:
1. `ToolProgressGuard.record`: results with `needsApproval`/`needsWindow` ignored. `ok:false` → if `tool:action` equals the previous failed `tool:action` increment, else reset to 1; at 3 → `CAPRI_TOOL_LOOP` ("Tool execution made no progress."). `ok:true` resets failures; non-discovery actions clear the read map; discovery actions (`apps`, `find_app`, `status`, `journal`) are fingerprinted `sha256(canonical JSON [tool,args,result])` with sorted keys; the third identical fingerprint → `CAPRI_TOOL_LOOP`; map holds ≤32 entries (FIFO). A guard error fails the turn through the watchdog signal.
2. Mark `spotify_control`/`application_control`/`desktop_control` as verified tools of this turn.
3. `desktop_control run_task` with `summary` and not `cancelled` → store as the turn's computer task result (AG-20) and stop.
4. `ok:false` or `needsApproval` or `needsWindow` → clear collected receipts.
5. Otherwise, unless the turn is "verbose" (text matches `/(?:\b(?:explain|describe|why|details)\b|объясни|расскажи|почему|подробн)/iu`), push `factualActionReply(...)` if non-null.
- Host side effects: a `cancelled` result for `settings_control fullComputerAccess` or `run_task` cancels the turn; `time_control` results update AG-39 focus; `time_control cancel ok` cancels the pending reminder.
- A second `run_task` inside the same turn returns the stored result instead of executing again.
### AG-19 Output stream pipeline (P0)
Source: `chat-service.mjs:513-552,1000-1113`; `thinking-mode.mjs:40-96`; `avatar-protocol.mjs:20-145`; `tool-loop.mjs:54-118`; `text.mjs`; `action-replies.mjs:85-112`.
Per content delta, in order: `VisibleAnswerStream.push` → `AvatarStreamParser.push` → for each text event `CoreFailureStream.push` → `PlainTextStream.push` → `append` (→ `ActionReplyFilter.push` unless factual) → emit `turn.delta`. Avatar events set `assistant.avatar` (and `followUp=true` when `;listen`) and emit `turn.avatar {source:"model"}`. At stream end: flush each stage with `final=true` in the same order.
- `VisibleAnswerStream`: hides spans between `<think>`/`</think>`, `<analysis>`/`</analysis>`, Gemma `<|channel>…<channel|>`; `<|think|>` is dropped; nesting tracked, >32 opens → everything after is hidden; a close without its opener is stripped but hides nothing; holds a possible partial tag at the end of a chunk (≤ longest tag − 1 chars).
- `AvatarStreamParser`: reserved markers `[avatar:` `[аватар:` (and closing forms `[/avatar…`). The first valid `[avatar:ID]` or `[avatar:ID;listen]` (ID `^[a-z][a-z0-9_-]{0,39}(/[a-z][a-z0-9_-]{0,39})?$`, frame ≤128 chars, matching a sprite id or `pose/expression`) selects the avatar once. Every other marker frame (closing, invalid, repeated) is removed. A marker cut by a newline is dropped up to the newline; an unterminated frame longer than 128 chars switches to discard-until-`]`-or-newline. A trailing `;listen` suffix in prose is held and removed (final flush emits it only if incomplete).
- `CoreFailureStream` (inspects only line starts): a line that becomes exactly `OpenClaw stopped this run`/`turn` → `CAPRI_TOOL_LOOP`; a line starting with a tool name + `{` or `(` (optionally after `**` and/or `[`) for `spotify_control`, `application_control`, `desktop_control`, `filesystem_control`, `settings_control`, `time_control` → `CAPRI_TOOL_ENCODING` "Model returned tool syntax as reply text." (nothing executes, nothing is shown). Holds at most a line-start prefix; whitespace-only prefix flushes at 64 chars. Rust: keep the tool-syntax rule; the "OpenClaw stopped" rule has no producer any more and may be dropped.
- `PlainTextStream`: removes emoji per extended grapheme cluster (any cluster containing `Extended_Pictographic`, `Regional_Indicator`, `Emoji_Modifier` or U+20E3), strips orphan U+200D, U+FE0E, U+FE0F, U+E0020..E007F, then removes every `*` and `` ` ``. Holds the last grapheme until the next chunk.
- `ActionReplyFilter`: enabled once any action tool (`spotify_control`, `filesystem_control`, `desktop_control`, `application_control`, `time_control`, `settings_control`) starts. Splits on sentence ends `[.!?。!?]` + whitespace/end and drops sentences matching the "what's next / anything else / что дальше / чем ещё помочь" pattern (`action-replies.mjs:108`).
- `append(value, factual)`: when `verifiedDomain` is set, non-factual text is buffered into `domainText` and not shown; when receipts or a computer task result exist, non-factual text is dropped; leading whitespace of the reply is removed; emitted text > 65536 chars total → "Response exceeds limit". Raw received deltas > 65536+2048 chars → same error (NPU without thinking: 6144).
- `MAX_EVENT`: any single SSE/NDJSON line or event > 262144 chars → error.
- End of turn: if receipts exist → append unique receipts (first 8) joined by a space, `followUp=false`; else if `verifiedDomain` → if the expected tool (`spotify_control` for spotify, `application_control` for calculator) ran, append the filtered `domainText`, else `uiText("Spotify did not confirm this action. Check the player.")` / `uiText("Calculation could not be verified. Please try again.")`, `followUp=false`; else flush the filter. A computer task result replaces all text (AG-05 finish).
- Incomplete stream → `CAPRI_GATEWAY_STREAM_INCOMPLETE`; complete but blank → `CAPRI_GATEWAY_RESPONSE_EMPTY`.
- No model avatar → fallback to the catalog default sprite, `turn.avatar {source:"fallback"}`.
### AG-20 Action receipts and verified domains (P0)
Source: `action-replies.mjs:3-84`.
`factualActionReply(tool, args, result, language)` → translated string or null:
- `desktop_control browser_input` returns null unless `typed===true && submitted===false`.
- `application_control calculate` with `ok` and string `result` → `Result: {value}` (`displayResult ?? result` + `" " + unit` if unit).
- `spotify_control volume` with finite `data.volumePercent` → `Spotify volume: {value}%.`; `pause|resume|toggle|play|next|previous` with boolean `data.playing` → `Resumed.` / `Paused.`.
- Mutations (`ok`, not cancelled, no `needsWindow`): filesystem `write_text` "Created the text file.", `replace_text` "Replaced the existing file.", `create_directory` "Created the folder.", `copy` "Copied the file.", `move` "Moved the file.", `undo` "Undid the file action.", `trash` "Moved the file to the Recycle Bin."; time `stopwatch` "Stopwatch started.", `pause` "Paused.", `resume` "Resumed.", `reset` "Stopwatch reset.", `cancel` "Cancelled.", `remind` "Reminder set.", `timer` "Timer started.", `snooze` "Reminder snoozed."; desktop `type_text`/`browser_input` "Entered the text without sending it.", `open_url` "Opened the address in the browser.", `trash` as above. (`launch` has a key but is not in the mutation list, so it never produces a receipt.)
- Strings are English keys looked up in the localization subsystem (`uiText`). Linux wording for "Recycle Bin" → "Trash" (§8).
### AG-21 Error classification and public messages (P0)
Source: `chat-service.mjs:145-193,1114-1160`; `visual-response.mjs`.
- `lastFailure` (only when not user-cancelled) = `{at ISO, phase, elapsedMs, errorName, code?, httpStatus? (400-599), networkCode?, receivedText: bool, message}`. `phase` ∈ `context, owner-memory, spotify-planning, spotify, calculator, computer-approval, model-loading, routing, computer-intent, computer, web-search, model`. Allowed `code`s: `CONTEXT_COMPACTION_FAILED, CAPRI_MODEL_NOT_READY, CAPRI_TOOL_LOOP, CAPRI_NPU_REQUEST_FAILED, CAPRI_GATEWAY_HTTP_ERROR, CAPRI_GATEWAY_STREAM_INVALID, CAPRI_GATEWAY_EVENT_INVALID, CAPRI_GATEWAY_REPORTED_ERROR, CAPRI_GATEWAY_STREAM_INCOMPLETE, CAPRI_GATEWAY_RESPONSE_EMPTY` (Rust may rename `GATEWAY` → `LLM`, keep the set closed). Network codes: `ECONNREFUSED, ECONNRESET, ENOTFOUND, EAI_AGAIN, ETIMEDOUT, UND_ERR_CONNECT_TIMEOUT, UND_ERR_HEADERS_TIMEOUT, UND_ERR_BODY_TIMEOUT, UND_ERR_SOCKET` (map reqwest/io errors onto these). Never store provider bodies, prompts or text.
- Public message (first match): external + empty → "API model returned no text."; NPU → "Lemonade could not generate a reply…"; tool loop → "The action could not be completed after repeated attempts. Check Application access or try a larger language model."; model not ready → "The local model could not load. Free some memory or choose a smaller Qwen model, then try again."; compaction → "Conversation context could not be compacted. Your history is preserved. Try a larger model or clear the current context in settings."; timeout → "Capri took too long to respond. You can try again."; HTTP 401/403 → "The local core rejected authentication. Check its configuration."; 429/409 → "The local core is busy. Please wait and try again."; 5xx → "The local model could not finish this response. Please try again."; else "The response could not be completed. Check the local core or reconnect.". Cancel → "Reply stopped.".
- Reported in-stream errors: text matching `OpenClaw stopped this (run|turn)` or `N consecutive identical tool failures` → tool loop; `compaction|context overflow|prompt too large` → `CONTEXT_COMPACTION_FAILED`. Rust: raise these codes natively.
- On failure the partial text is kept (final flush appended except for tool loop); a non-cancelled reply consisting only of whitespace/brackets/`*`/`` ` ``/`_`/`,` is blanked.
### AG-22 Context budget and compaction (P0)
Source: `config/context-policy.mjs:1-104`; `context-fallback.mjs`; OpenClaw `agent-settings-CZ8x5-4D.mjs:7-38`, `agent-compaction-constants-DmXQuPyL.mjs`, `agent-core-DlqC-il7.mjs:2860-2990` (cut point, prompts), `builtin-openclaw-CcrkVuBH.mjs:12066-12200` (safeguard sections, quality), patches `builtin-openclaw` edits 1-3, `embedded-agent` edits 0-2; `docs/context-management.md`.
Constants for window `C = contextTokens` (8192..262144; managed Qwen ≥ 32768):
| Name | Value |
|---|---|
| `keepRecentTokens` | `min(4096, floor(C/8))` |
| `recentTurnsPreserve` | 2 |
| `maxActiveTranscriptBytes` | `max(24576, floor(C·0.75))` |
| summary `thinking` | off |
| summary progress timeout | 10 s without output |
| quality guard | enabled, 0 regeneration retries |
| mid-turn precheck | after every tool result |
| reserve (output headroom) | `min(max(1024, turnOutputBudget), floor(C·0.25))` (managed models); otherwise `min(max(current, 20000), floor(C·0.25))` |
| token estimate | `ceil(chars/4)`; calibrated by the last measured `prompt_eval_count` |
- Preflight (before each model call): `estimate(system + tool schemas + model view + new message) > C − reserve` or active transcript bytes > `maxActiveTranscriptBytes` → compact first.
- Cut point: walk back from the end keeping whole entries up to `keepRecentTokens`, never splitting a tool call from its result, always keeping the last 2 user turns when they fit. If not even the newest complete message fits → `CONTEXT_COMPACTION_FAILED` ("No complete recent message fits beside the foreground prompt, tools, and summary…").
- Summarize everything between the previous boundary and the cut, with the previous summary as a draft. Prompt = structure instructions (`builtin-openclaw-CcrkVuBH.mjs:12145-12175`, five required headings `## Decisions`, `## Open TODOs`, `## Constraints/Rules`, `## Pending user asks`, `## Exact identifiers`, latest unresolved user request first under Pending asks) + identifier preservation (`IDENTIFIER_PRESERVATION_INSTRUCTIONS`). Summary max tokens `min(floor(0.8·reserve), model maxTokens)`.
- Quality audit: all five headings in that order; the pending-asks section starts with the latest unresolved request when there is one; listed identifiers present. Failure → Capri extractive fallback `buildLocalCompactionFallback` (maxChars 12000, `context-fallback.mjs:26-73`), audited the same way. Still failing → `CONTEXT_COMPACTION_FAILED`. Applies to the managed Capri models (upstream gate); Rust applies it to all local models.
- Fallback format: `## Decisions` + fixed explanation; optional `Latest archived user message (not a new task): <json>`; optional `Earlier summary (quoted, may be incomplete): <json>` (≤ min(3000, remaining/3)); newest-first role-labelled JSON lines `{role, tool?, text ≤1200 + " [excerpt truncated]"}` until the budget is used, emitted oldest-first; then `## Open TODOs`, `## Constraints/Rules`, `## Pending user asks` (`Latest user request context: <json>` or the no-pending sentence), `## Exact identifiers` (or "None captured."). JSON quoting escapes U+2028/U+2029.
- Commit: append a `compaction` entry; original entries stay on disk (memory search keeps them).
- Mid-run compaction: the model call is re-issued with the continuation prompt as a transient user message: `CONTINUATION_PROMPT + " This is an internal recovery note, not a user question. …\n\nCURRENT OWNER REQUEST AND CONTEXT (already recorded):\n" + <current user message>` (patch `embedded-agent` edit 0), with `" " + TOOL_FAILURE_INSTRUCTION` appended when the last tool failed.
- Memory extraction (AG-25) never runs before a foreground reply.
### AG-23 Memory index and recall tools `memory_search` / `memory_get` (P1)
Source: config `context.mjs:123-132`; `<cfg>/Embedding.Modelfile`; `providers/embedding-model.mjs`; OpenClaw `memory-search-C0yT-zqb.mjs:17-147`, `memory-tool-contract-Dd8Po2zZ.mjs`, `tools-Cu6iE4iE.mjs:387-540,887-923`, `engine-storage-CJHumWmY.mjs:268-420`, `manager-search-CCxsirb7.mjs:209-216`, `embedding-provider.runtime-DH3L6dKN.mjs:206-250`.
- Embedding model `capri-embed:latest` = Ollama alias of `bge-m3:latest` with `num_gpu 0` (CPU), created if missing by `POST /api/create {model, from:"bge-m3:latest", parameters:{num_gpu:0}, stream:false}`; else error "Memory model capri-embed:latest is missing. Run Capri Setup again to repair the installation." Embeddings via `POST /api/embed {model, input:[...]}` → `{embeddings:[[f32…]]}` (bge-m3: 1024 dims), count must match, L2-normalize.
- Sources: `memory` = `<ws>/MEMORY.md`, `<ws>/USER.md`, `<ws>/memory/**/*.md`; `sessions` = user/assistant text of current and archived sessions (`rememberAcrossConversations:true`). Rust strips the per-turn envelope (everything from the first `\n\nDESKTOP STATE FOR THIS TURN`, `\n\n[Read-only screen observation`, `\n\n[Local Brain excerpts`, `\n\nCURRENT WEB SEARCH`) and avatar markers before indexing (§12).
- Chunking: ~400 tokens (≈1600 chars) with ~80 tokens (≈320 chars) overlap, on line boundaries, recording 1-based `startLine/endLine`; chunk hash SHA-256; embedding cache keyed `(model, hash)`, ≤50000 entries.
- Sync: at startup, before a search when dirty, on file changes under `<ws>` memory sources (watch, 1500 ms debounce), after 100000 bytes or 50 new session messages, and forced after compaction. Indexing runs in the background and never blocks a reply.
- Search (defaults `maxResults 6`, `minScore 0.35`): hybrid = vector cosine (weight 0.7) + FTS5 BM25 text score (weight 0.3; FTS rank → score `rank<0 ? −rank/(1−rank) : 1/(1+rank)`, non-finite → 0.001), candidate pool = 4 × maxResults from each side, MMR rerank λ=0.7, temporal decay half-life 30 days for dated sources (`memory/YYYY-MM-DD*.md` and session chunks), filter `score ≥ minScore`, top `maxResults`. No embeddings available → keyword-only mode with a warning. Timeout 30 s.
- `memory_search` schema `{query: string (required), maxResults?: int ≥1, minScore?: number, corpus?: "memory"|"wiki"|"all"|"sessions"}`, aliases `max_results`/`min_score` accepted. Result JSON `{results:[{path, startLine, endLine, score, snippet (≤700 chars), corpus, citation?}], mode:"hybrid"|"keyword-only", warning?, disabled?, stale?}`; `corpus:"memory"`/`"sessions"` filters; `wiki` → `not-registered` outcome. Citation `path#Lx[-Ly]` appended to snippet as `\n\nSource: …`.
- `memory_get` schema `{path: string (required), from?: int ≥1, lines?: int ≥1, corpus?: "memory"|"wiki"|"all"}`: path relative to `<ws>`, must be `MEMORY.md`, `USER.md` or `memory/**.md` (else `MEMORY_PATH_NOT_ALLOWED`); default 120 lines, ≤12000 chars on line boundaries; truncated output ends with `\n\n[More content available. Use from=N to continue.]`; result `{status:"ok"|"not_found"|"error", text, path, from, lines, truncated?, nextFrom?}`. Rust rejects symlinks anywhere in the path (stricter than upstream).
- Tool descriptions: §6. Clearing long-term memory resets this index (AG-27).
---
## Note added during the Linux port: AG-24..AG-47 are not written
This file stops after AG-23. The features AG-24 to AG-47 are referenced above (file map, §AG-13, §AG-14) but their
catalog entries were never written, and the CapriCore 1.0.4 source tree they would be checked against is not part of
this repository. They are **not** reconstructed here: write them from `~/Capri` before relying on them. Until then,
the table below only says where the Rust code covers each referenced area (behaviour of the code, not of the spec).
| Feature (from the references above) | Capri source | Rust implementation |
|---|---|---|
| AG-25 OpenClaw memory-core / compaction internals | `node_modules/openclaw` | `capri-memory` (`compaction.rs`, `index.rs`) |
| AG-26, AG-27 Saved memory, memory controls, `memory reset` | `saved-memory.mjs`, `memory-controls.mjs` | `capri-memory` (`saved.rs`, `ui.rs`), `capri reset` |
| AG-28 Owner memory files (USER.md, MEMORY.md) | `owner-memory.mjs` | `capri-core::persona`, `capri-memory::notes` |
| AG-29, AG-30 Private dialogue and private memory | `private-dialogue.mjs`, `private-memory.mjs` | `capri-memory::private` |
| AG-31 Brain knowledge | `brain-knowledge.mjs`, `brain-worker.mjs` | `capri-memory::brain` |
| AG-32..AG-34 Attachments and visual turns | `attachments.mjs`, `attachment-history.mjs` | `capri/src/attachments.rs`, `Engine::attach_images`, `capri-perception::visual` |
| AG-35 Journal (`transcript.json`) | `storage.mjs` | `capri-agent::journal` |
| AG-36 Legacy private storage | `legacy-private-storage.mjs` | `capri import` (partial) |
| AG-37 Thinking briefing / thinking mode | `thinking-briefing.mjs`, `thinking-mode.mjs` | not ported (ordinary turns send `think: false`) |
| AG-38 Web context | `chat-service.mjs` | `capri-tools::web` (`web_context`) |
| AG-39 Time conversation | `time-conversation.mjs` | `capri-tools::time` |
| AG-40 Voice follow-up | `voice-follow-up.mjs` | `capri-voice` (`finish_turn`, follow-up window) |
| AG-41 Visual response | `visual-response.mjs` | `capri-perception::visual` |
| AG-42 Context usage | `context-usage.mjs` | `Engine::prepared_history` (character budget) |
| AG-44 Preferences, companion settings | `preferences.mjs`, `companion-settings.mjs` | `capri-core::settings`, `capri-ui::settings` |
| AG-45 Injected messages (initiative and others) | `chat-service.mjs` | `Engine::record_line` / `Engine::announce` |
| AG-46 Lemonade / NPU backend | `providers/*` | not ported (no NPU models on Linux) |
| AG-47 CLI client | `client.mjs`, `index.mjs` | `capri chat`, `capri status` |