From 4767061748e68f76c7c6217e3e8badbc96c411e2 Mon Sep 17 00:00:00 2001 From: fkDead Date: Wed, 11 Nov 2026 20:20:49 +0100 Subject: [PATCH] docs: add spec 01-agent-core --- docs/spec/01-agent-core.md | 466 +++++++++++++++++++++++++++++++++++++ 1 file changed, 466 insertions(+) create mode 100644 docs/spec/01-agent-core.md diff --git a/docs/spec/01-agent-core.md b/docs/spec/01-agent-core.md new file mode 100644 index 0000000..47c32ae --- /dev/null +++ b/docs/spec/01-agent-core.md @@ -0,0 +1,466 @@ +# 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 + +- `` = Capri install root, `` = `/data`, `` = `/desktop`, `` = `/workspace` (agent workspace), `` = `/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 (`/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 `/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 ""\n` (UTC date of now) to `/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: `` resolved by realpath; `memory` must be a real directory exactly at `/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-`), 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`). The Rust engine keeps only the parts with owner value and appends them after the 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. + +## + + + +## + + + +## 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 `/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 `/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..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 `/config-backups/persona//` (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 `/.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: