Skip to content

Card App Design ​

A card app is a self-contained crescent app (tarball format) that owns its own conversation view, editor, and settings. The platform shell launches it; the app handles all internal navigation.

Status: active design session. Conversation view is roughed out below. Editor and settings views need their own design pass.

Scope: single character. The card app manages one character per conversation. Group chat (multiple characters in one conversation) is a different interaction model and warrants its own app — the platform doesn't dictate how multi-character interactions work. See docs/batteries.md for the group chat app entry.

Conversation view ​

The primary view. Minimal — the right things visible, nothing extra.

Layout ​

  • Messages fill the viewport, scrollable
  • Input row pinned to the bottom
  • No persistent top bar beyond what's strictly necessary

Per-message UI ​

Every message (user and assistant) can have siblings (from edits/regenerations).

Branch indicator — shown when siblings exist. Displays current/total (e.g. 2/3). Always visible on messages with siblings so the user knows they're there.

Gestures (touch):

  • Swipe left on left half of message → previous sibling
  • Swipe right on left half of message → next sibling
  • Swipe left elsewhere on message → reveal actions (edit, delete)

Hover (desktop): actions appear on hover — edit, delete.

Actions are the same for user and assistant messages.

Input row ​

Single-line text field that expands to a max height (~30% of viewport above keyboard) before scrolling internally. Three action buttons alongside it:

  • Send — sends the current input as a user message
  • Continue (hidden by default, configurable in settings) — continues the last assistant message via prefill (passes existing message as assistant turn prefix). Only available when the active LLM supports prefill; dimmed otherwise.
  • Impersonate (hidden by default, configurable in settings) — generates a user-side message using a configurable impersonate prompt. Cannot use prefill (prompt is different). Prompt is configurable in card settings, with a sensible default.

No regenerate button — swipe left on the last assistant message to regenerate.

Keyboard (desktop) ​

  • Enter → send
  • Shift+Enter → newline

Branching model ​

Backed by lib/conversation (vendored into the app tarball). Every regeneration or edit inserts a new branch node; canonical_child_id tracks the active path. Swiping updates canonical_child_id to a sibling. No duplication, no explicit checkpoint concept — the tree IS the history.

Stored in a shared_db cap (see platform-design.md) so cross-card conversation search works from the shell.

Context assembly ​

The card script owns context assembly entirely — it builds the messages array and calls caps.llm.call(messages). The platform has no opinion about what goes in the context.

Block ordering ​

User-reorderable (stored in caps.config). Default order (matching ST):

  1. System prompt (main)
  2. Lorebook "before" entries
  3. User persona
  4. Character description
  5. Character personality
  6. Scenario
  7. Lorebook "after" entries
  8. Dialogue examples
  9. Chat history
  10. Post-history system prompt ("jailbreak")

Extension injections (author's note, summary, etc.) are inserted at absolute positions within the chat history at a specified depth.

Token budget ​

max_context - max_response_tokens. The card declares both; caps.llm exposes count_tokens(text) backed by the backend's tokenizer endpoint.

Trimming strategy (ST parity) ​

  • Fixed blocks (system prompt, persona, description, scenario) — always included, consume budget unconditionally. No trimming.
  • Lorebook — has its own percentage budget (default 25% of max_context). Entries are processed in priority order (sticky first, then by order field descending). Once budget overflows, new entries are skipped unless marked ignoreBudget.
  • Dialogue examples — dropped as whole blocks when over budget. pin_examples option guarantees them at the cost of fewer history messages.
  • Chat history — the only section truly trimmed. Newest-to-oldest iteration; oldest messages drop first when budget runs out.

Lorebook scanning ​

Aho-Corasick (NFA) over all keywords — build the automaton once, scan recent messages in a single pass. Scan depth (how many recent messages to check) is user-configurable.

caps.llm API ​

lua
caps.llm.call(messages)          -- { role, content }[] -> response string
caps.llm.count_tokens(text)      -- -> integer (uses backend tokenizer endpoint)

Lorebook editor ​

Format compatibility ​

Two lorebook formats exist in the wild — both must be supported:

CCv2 (CharacterBook) — embedded in the card's chara PNG chunk alongside character data. Simple format: entries[] array, each entry has keys[], content, enabled, insertion_order, selective?, secondary_keys?, constant?, position? ("before_char"/"after_char"), case_sensitive?, priority?. Detected by presence of extensions field on the book object.

ST lorebook — standalone .json file. entries is a string-keyed object ({"0": {...}, "1": {...}}). Richer format with many ST-specific fields beyond CCv2. Detected by absence of extensions field.

Field mapping (CCv2 → ST):

CCv2ST
keyskey
!enableddisable
insertion_orderorder
case_sensitivecaseSensitive
secondary_keyskeysecondary
position: "before_char"position: 0
position: "after_char"position: 1

ST position integer values:

0 = before          — before character definitions
1 = after           — after character definitions
2 = ANTop           — top of Author's Note
3 = ANBottom        — bottom of Author's Note
4 = atDepth         — injected at specific chat depth (uses `depth` + `role`)
5 = EMTop           — top of Example Messages
6 = EMBottom        — bottom of Example Messages
7 = outlet          — named outlet injection (uses `outletName`)

selectiveLogic values:

0 = AND_ANY  — any secondary key triggers (default)
1 = NOT_ALL  — triggers unless all secondary keys match
2 = NOT_ANY  — triggers unless any secondary key matches
3 = AND_ALL  — all secondary keys must match

role values (used when position = 4 / atDepth):

0 = system
1 = user
2 = assistant

Implementation notes:

  • selective: true is now always set in ST (all entries are selective); selectiveLogic controls the behaviour.
  • ST-specific fields with no CCv2 equivalent: uid, selectiveLogic, vectorized, addMemo, ignoreBudget, excludeRecursion, preventRecursion, probability, useProbability, depth, scanDepth, group, groupOverride, groupWeight, useGroupScoring, sticky, cooldown, delay, triggers, displayIndex, characterFilter, automationId, matchWholeWords, match* flags.
  • When exporting to CCv2: ST-specific fields dropped, extensions set to {}, position integer → string.

Crescent uses ST format as the internal representation. CCv2 lorebooks are converted on import.

Entry structure ​

Each entry has:

  • Name (comment) — the entry's title
  • Keywords (key[]) — primary trigger patterns; supports regex (e.g. /pattern/i)
  • Secondary keywords (keysecondary[]) + selectiveLogic (AND/NOT/AND NOT)
  • Content — prose injected into context when triggered
  • Meta — open key-value object for search/filtering (not in ST format — stored in crescent's extended format, dropped on CCv2 export)
  • Settings — all ST fields: position, depth, order, probability, sticky, cooldown, constant, ignoreBudget, role, group, characterFilter, etc.

List view ​

Entries shown with name + keywords visible at a glance. Sorted by order field by default; sortable by any metric (name, uid, enabled status, etc.). Projectional search over all fields including meta — same search paradigm as the card library, no separate search model to learn.

Entry detail view ​

Full-screen on mobile. Content textarea, keyword chip input (tag-style), meta fields, settings in a collapsible section.

CCv2 card format ​

spec: "chara_card_v2", spec_version: "2.0", stored as base64 JSON in the PNG chara iTXt chunk.

V1 fields (all strings, required):

  • name, description, personality, scenario, first_mes, mes_example

V2 additions:

  • creator_notes: string
  • system_prompt: string
  • post_history_instructions: string
  • alternate_greetings: string[]
  • character_book?: CharacterBook
  • tags: string[]
  • creator: string
  • character_version: string
  • extensions: object — open record for ST extensions: depth_prompt?, talkativeness?, fav?, world?, regex_scripts?

mes_example format: blocks separated by <START>. Each message prefixed with {{char}}: or {{user}}:.

Macro substitution ​

ST uses {{macroName}} syntax (case-insensitive: {{Char}}, {{CHAR}} all work). Legacy aliases <USER>, <BOT>, <CHAR> also replaced.

Most cards only need {{char}} and {{user}} — implement those inline (3 lines), don't vendor the full macro library. Only include the full library if the card actually uses the extended macro set. Legacy angle-bracket syntax (<CHAR>, <USER>, <BOT>) and case-insensitive matching are also simple enough to inline — add them to the same 3-line substitution if the card needs them, no separate library required.

Full macro reference (98 macros, source: https://docs.sillytavern.app/usage/core-concepts/macros/):

Names & participants: {{user}}, {{char}}, {{group}}, {{groupNotMuted}}, {{charIfNotGroup}}, {{notChar}}

Character card & persona: {{description}}, {{personality}}, {{scenario}}, {{persona}}, {{charPrompt}}, {{charInstruction}}, {{charDepthPrompt}}, {{charCreatorNotes}}, {{charVersion}}, {{mesExamples}}, {{mesExamplesRaw}}, {{charFirstMessage}}, {{original}}

Chat history: {{lastMessage}}, {{lastMessageId}}, {{lastUserMessage}}, {{lastCharMessage}}, {{firstIncludedMessageId}}, {{firstDisplayedMessageId}}, {{lastSwipeId}}, {{currentSwipeId}}, {{allChatRange}}, {{summary}}

Time & date: {{time}}, {{time::UTC±offset}}, {{date}}, {{weekday}}, {{isotime}}, {{isodate}}, {{datetimeformat::format}}, {{idleDuration}}, {{timeDiff::left::right}}

Variables (local): {{getvar::name}}, {{setvar::name::value}}, {{addvar::name::value}}, {{incvar::name}}, {{decvar::name}}, {{hasvar::name}}, {{deletevar::name}}

Variables (global): {{getglobalvar::name}}, {{setglobalvar::name::value}}, {{addglobalvar::name::value}}, {{incglobalvar::name}}, {{decglobalvar::name}}, {{hasglobalvar::name}}, {{deleteglobalvar::name}}

Randomization: {{random::a::b::c}} (re-rolls each time), {{pick::a::b::c}} (stable per chat/position), {{roll::1d20}}

Runtime state: {{maxPrompt}}, {{maxContextTokens}}, {{maxResponseTokens}}, {{model}}, {{isMobile}}, {{lastGenerationType}}, {{hasExtension::name}}

Prompt templates: {{systemPrompt}}, {{defaultSystemPrompt}}, {{authorsNote}}, {{charAuthorsNote}}, {{defaultAuthorsNote}}, {{instructUserPrefix}}, {{instructAssistantPrefix}}, {{instructSystemPrefix}}, {{instructSeparator}}, {{instructStop}}, {{instructUserFiller}}, {{instructFirstAssistantPrefix}}, {{instructLastAssistantPrefix}}, {{instructFirstUserPrefix}}, {{instructLastUserPrefix}}, {{instructStoryStringPrefix}}, {{instructStoryStringSuffix}}, {{instructSystemInstructionPrefix}}, {{instructAssistantSuffix}}, {{instructUserSuffix}}, {{instructSystemSuffix}}, {{chatSeparator}}, {{chatStart}}, {{reasoningPrefix}}, {{reasoningSuffix}}, {{reasoningSeparator}}, {{charPrefix}}, {{charNegativePrefix}}, {{outlet::key}}

Utility: {{newline}}, {{newline::count}}, {{space}}, {{space::count}}, {{noop}}, {{trim}}, {{reverse::text}}, {{input}}, {{banned::word}}

Card editor ​

Fields are laid out in context assembly order — the order they appear in the prompt sent to the model. The editor IS the context composition view; there is no separate "context composition" panel. Reordering fields in the editor reorders the context.

Default order (matches default context assembly order):

  1. System prompt (system_prompt)
  2. Character description (description)
  3. Character personality (personality)
  4. Scenario (scenario)
  5. Post-history instructions (post_history_instructions)
  6. First message / alternate greetings (first_mes, alternate_greetings)
  7. Example messages (mes_example)
  8. Metadata (name, creator, character_version, tags, creator_notes)

Most users never reorder — the default order is shown and is already correct. Users who customise see their actual configured order, not a separate panel.

This layout is honest: what you see in the editor is what the model sees, in order. Other frontends (ST, chub, etc.) show fields in CCv2 spec order (a data format order) and maintain a separate context composition panel — disconnected from the editor. We don't.

Each field is a textarea (or appropriate input for metadata fields). {{char}} and {{user}} macros render as styled inline chips while editing, expanding to raw text on focus (same pattern as Notion inline variables).

Cards can have 50+ alternate greetings. Swiping one by one is unusable at that scale. Navigation UI: a preview grid showing all greetings as truncated text previews, with a search/filter bar — type a word to filter previews to matching greetings, tap any preview to jump directly. Same pattern applies to navigating swipes in the conversation view when a message has many branches.

State storage and self-containment ​

Self-containment is non-negotiable ​

A card file is a single, complete, portable artifact. Everything the card needs to function as authored must be embedded in the file. If you copy the PNG to another machine, the card works there — same lore, same field edits, same linked lorebooks, same author's note, and the runtime that plays it. No sidecar files, no external fetches, no implicit dependencies on the sender's environment, no "install the ccv2 app first."

This rules out any "shared asset referenced by URL at runtime" pattern. Shared assets must be vendored into the card at link time (snapshot embedded in the PNG). The reference URL can travel alongside the snapshot for "update available" checks, but the card does not depend on it being reachable.

Import is embedding ​

The ccv2 app's import pipeline's job is simple:

  1. Embed the ccv2 app tarball into the incoming PNG as the lua iTXt chunk (base64(gzip(tar))), plus lua-manifest iTXt. The PNG is now a crescent app in addition to being a CCv2 card.
  2. Write the PNG to the library (~/.crescent/apps/) and index it. The user can now launch it from the library like any other app.

That's the entire operation. There is no "conversion to crescent format" because there is no crescent format (see docs/platform-design.md → "No 'crescent format'").

Implications:

  • The chara iTXt (CCv2 card data) is never altered by import. Plain CCv2 tools (ST, Chub) continue to read the card exactly as before. The embedded app is additive.
  • chara.extensions.* fields that the ccv2 app uses (linked_lorebooks, regex_scripts, depth_prompt*, etc.) can be initialized as empty stubs during import or on first use; not material.
  • The PNG's original source (e.g. the file the user dragged in) is not rewritten. The library copy is the working copy. The source file is the user's; don't touch it.
  • No "pure CCv2 export" mode. The card is already CCv2-readable as it sits; nothing to strip. An "export" in the sense of sharing the card is just copying the PNG.
  • Each PNG's embedded ccv2 app is the app for that PNG. The host's installed ccv2 (if any) is a peer, not a canonical version. Updates to the ccv2 app do not automatically propagate to previously-imported cards; re-importing is the only upgrade path, and it is not automatic.

What is card state vs user state ​

Not everything in the ccv2 app is card state. Card state is "facts about this character and its lore"; user state is "my preferences and my context across all cards". Two different things, two different stores.

BucketScopeStorage
Card fields (name/description/greeting/etc.)cardPNG chara JSON, top-level
Card lorebookcardPNG chara.character_book
Linked lorebooks (vendored)cardPNG chara.extensions.linked_lorebooks
Author's notecardPNG chara.extensions.depth_prompt*
Card-embedded regex scriptscardPNG chara.extensions.regex_scripts
LLM connection/generation settingsusercaps.kv
Personasusercaps.kv
Instruct templatesusercaps.kv
User lorebooks (see below)usercaps.kv
Group chat definitionssessioncaps.kv (conversation-level, not card)
Active session idsessioncaps.kv

Card-state writes require the self_write cap. The app declares self (read) and self_write (write) as separate caps so the operator can grant read-only.

Migration ​

One-pass migration on startup. If kv has card-state keys (lorebook, card_overrides, authors_note, regex_scripts, old world_info), bake them into the PNG via caps.self_write.write_metadata("chara", ...), then delete those keys from kv. Subsequent saves go only to the PNG.

world_info migrates specifically into a single entry of the new user_lorebooks array (see below), named e.g. "Imported" with active: true — preserves the user's existing entries.

Write strategy ​

Card-state writes are debounced (100ms). A single lorebook keystroke does not trigger a full PNG rewrite; a burst of edits coalesces into one write. PNG writes are atomic via self_write.write_metadata, so a crash between debounce and flush loses at most 100ms of edits.

Lorebook scope model ​

Two distinct scopes, both legitimate, both backed by the same data structure:

Card lorebook(s) — scope: this card. Card-creator-defined, travels with the card. Always active when the card is loaded (no user toggle; the card creator decided).

  • Primary: character_book per CCv2 spec. Every card has exactly one.
  • Linked: extensions.linked_lorebooks: [{ source?, name, entries[] }, ...]. Vendored snapshot + optional source reference. The source is informational (lets the editor prompt "v2 available, re-vendor?") — the card never fetches from the source at runtime.

User lorebooks — scope: this user, all conversations. User-maintained library of lorebooks; each has an active toggle. Active lorebooks merge into context for every conversation, regardless of which card.

  • user_lorebooks: [{ id, name, entries[], active }, ...] in caps.kv.
  • Users can add, rename, edit, delete, toggle active.
  • Import UX: paste JSON, upload file, later: paste Chub/ST URL and vendor a snapshot.

Context assembly ​

At context-assembly time, merge all of:

  1. card.character_book.entries
  2. card.extensions.linked_lorebooks[*].entries (all, no toggle)
  3. user_lorebooks[active=true][*].entries

Run the existing keyword/constant matching over the merged set. Ordering, trimming, budget: unchanged.

UI layout ​

One "Lorebooks" panel, two sections:

  • Card Lorebooks — read-only unless self_write is granted. Shows character_book + each linked lorebook. Each item has CRUD on its entries.
  • My Lorebooks — full CRUD. Each book has name + active toggle + entries.

Rationale: scope is the user-visible distinction, so the UI groups by scope. Naming is explicit ("Card Lorebooks" / "My Lorebooks") so a new user isn't guessing what "World Info" means.

Deferred ​

  • Per-card user-toggle overrides — "sci-fi lorebook active only on cyberpunk cards". Additive on top of the current model (a per-card activation override map). Not first pass.
  • Chub/ST URL import with re-vendoring — import UI paste URL, fetch, vendor snapshot in. Data model already supports via source field. Fetch mechanism is follow-up.

Settings ​

Storage ​

Settings use a two-layer override pattern:

  • Global defaults — stored in caps.config (host-owned, shared across all apps)
  • Per-card overrides — stored in caps.kv (scoped to the card)

The card reads caps.kv.get("setting") first; falls back to caps.config.setting if nil; falls back to a hardcoded default if both are nil.

Both caps are declared required: false. Cards must work standalone (headless, MCP entrypoint) without a host UI — caps.config and caps.kv may not be provided. Hardcoded fallbacks are not optional.

LLM presets ​

Named presets stored in caps.config.presets — a map of alias → backend config. Aliases like "smart" or "gemini" resolve at runtime to whatever the user has configured. The card declares which preset it wants; the host resolves it at launch. Changing what "smart" means in global settings propagates to all cards that use it.

Per-card override: caps.kv.get("llm_preset") — either a preset name (resolved via caps.config.presets) or an inline config object. Nil means use the global default.

Settings view ​

Presented as a form within the card's dom entrypoint (internal view, not a separate entrypoint). Writes to caps.kv for per-card values. Links to the shell's global settings for caps.config values.

Fields (not yet fully specced):

  • LLM preset selection (global presets + per-card override)
  • Generation params (temperature, max tokens, etc.) — per-card override
  • Context composition order — per-card override over global default
  • Lorebook budget %
  • Show/hide continue + impersonate buttons (global, stored in caps.config)
  • Impersonate prompt — per-card override
  • UI preferences (theme etc.) — global only, no per-card override