Chat Scripts (Atmosphere System)

Status: Concept — depends on Trackers for state-driven triggers, Gallery for background images, and the Chat UI redesign for the rendering surface.


Problem

The chat experience today is text-only. Themes set a static visual mood, but nothing in the environment responds to what's happening in the story. When the narrative describes a thunderstorm, the chat background stays the same. When the party descends into a dungeon, nothing changes except the words on screen.

What creators can't do today

All of this is achievable without AI involvement — it's deterministic pattern matching on content the system already has (message text, tracker values).


Core Concept

A script is a named collection of rules. Each rule has one or more triggers and one or more actions. When all triggers on a rule are satisfied, its actions fire.

Script: "Weather Atmosphere"
├── Rule: "Rainy Scene"
│   ├── Triggers:
│   │   └── keyword: ["rain", "rainy", "storm", "downpour", "thunder"]
│   ├── Actions:
│   │   ├── background: gallery image "rainy-street.jpg"
│   │   └── sound: "rain-ambient", loop: true
│   └── Priority: 10
│
├── Rule: "Sunny Scene"
│   ├── Triggers:
│   │   └── keyword: ["sunny", "sunshine", "clear sky", "bright day"]
│   ├── Actions:
│   │   ├── background: gallery image "sunny-park.jpg"
│   │   └── sound: stop
│   └── Priority: 10
│
└── Rule: "Indoor Fallback"
    ├── Triggers:
    │   └── tracker "location" contains: ["tavern", "inn", "house", "castle"]
    ├── Actions:
    │   └── background: gallery image "interior-warm.jpg"
    └── Priority: 5

Creators build rules through a visual editor — picking triggers from a menu, selecting images from their gallery, choosing sounds from a library. The result is a JSON definition the frontend evaluates client-side.


Trigger Types

Triggers answer the question: "did something happen that this rule cares about?"

Keyword (v1)

Scans message text for specific words or phrases. Case-insensitive, word-boundary matching.

Field Type Description
match string[] Words/phrases to look for (OR logic — any match activates)
scope "assistant" | "user" | "both" Which messages to scan. Default: "both"
matchMode "word" | "phrase" | "fuzzy" Word boundary, exact substring, or stem match. Default: "word"

Example:

trigger: keyword
match: ["rain", "rainy", "storm", "downpour"]
scope: "assistant"
matchMode: "word"

"The rain hammered the windows" → activates (word: "rain") "She trained for hours" → does NOT activate (word boundary: "trained" ≠ "rain") "A brainstorm of ideas" → does NOT activate (word boundary: "brainstorm" ≠ "rain")

Limitations: Keyword matching can false-positive on negation. "It didn't rain" still triggers. Good enough for atmosphere — but not for precise state tracking. That's what tracker triggers are for.

Tracker Value (v2 — requires Trackers)

Reacts to tracker state. This is the powerful, reliable trigger — no false positives from ambiguous prose. If the tracker says the location is "Shadowkeep", it's Shadowkeep.

Field Type Description
trackerKey string Which tracker to watch
condition "equals" | "contains" | "gt" | "lt" | "gte" | "lte" | "changed" | "changed_to" Comparison operation
value string | number | string[] Value(s) to compare against

Examples:

# Location-based background
trigger: tracker_value
trackerKey: "location"
condition: "contains"
value: ["dungeon", "cave", "crypt"]

# Low HP warning
trigger: tracker_value
trackerKey: "hp"
condition: "lte"
value: 20

# Time of day changed to night
trigger: tracker_value
trackerKey: "time_of_day"
condition: "changed_to"
value: "night"

# Any location change (regardless of destination)
trigger: tracker_value
trackerKey: "location"
condition: "changed"

Tracker triggers are evaluated against the latest tracker_json on the current message. When trackers aren't active on a conversation, tracker triggers silently don't match — the script degrades to keyword-only rules.

Message Count (v2)

Fire after a specific number of messages. Useful for timed atmosphere shifts.

Field Type Description
count number Fire when message count reaches this threshold
mode "once" | "every" Fire once at that count, or every N messages
# Darken atmosphere after 50 messages (tension builds)
trigger: message_count
count: 50
mode: "once"

# Periodic thunder every 10 messages during storm
trigger: message_count
count: 10
mode: "every"

Conversation Start (v1)

Fire when the conversation begins (first message loads). Useful for setting initial atmosphere before any narrative occurs.

trigger: conversation_start

A rule with only this trigger sets the default atmosphere for the experience.

Compound Triggers

A rule can have multiple triggers. When it does, all triggers must match (AND logic). This enables precise conditions:

Rule: "Dungeon Low-HP Danger"
  Triggers:
    - tracker_value: location contains "dungeon"
    - tracker_value: hp lte 30
  Actions:
    - effect: "danger-pulse"
    - sound: "heartbeat", loop: true

Both conditions must be true simultaneously. The danger atmosphere only activates when the player is in a dungeon AND low on HP — not when low on HP in a tavern, and not when healthy in a dungeon.

AI-Invoked (v3 — experimental)

The AI itself triggers scripts by name. Available scripts are injected into the system prompt, and the AI outputs a small metadata tag alongside its response indicating which atmosphere to activate.

[script:thunderstorm]

This is the most expressive trigger — the AI decides when the mood shifts based on narrative context, not pattern matching. Requires pipeline support to parse the tag from the AI response before it reaches the user.

This is speculative. Keyword and tracker triggers may prove sufficient for most use cases. AI-driven triggers add latency (evaluation call), cost (extra tokens in system prompt), and unpredictability. Phase 3 ships only if phases 1-2 reveal clear limitations that only AI awareness can solve.


Action Types

Actions answer the question: "what happens in the chat UI when this rule fires?"

All actions are drawn from a whitelisted vocabulary. The frontend knows exactly what each action type does and how to render it. Creators pick from a menu — they never write code.

Background

Switch the chat area's background image. Images must come from the creator's gallery — no external URLs.

Field Type Description
galleryImageId uuid Gallery image to use as background
transition "fade" | "crossfade" | "instant" How the background changes. Default: "crossfade"
transitionDuration number Transition time in ms. Default: 1000
opacity number Background opacity (0-1). Default: 0.3
blur number Background blur in px. Default: 4
position "cover" | "contain" | "center" CSS background-size behavior. Default: "cover"

The frontend applies the image as a CSS background on the chat panel, respecting the theme's text contrast requirements — opacity and blur ensure readability over any image.

Sound

Play or stop an audio loop or one-shot sound effect. Sounds come from a platform-curated library (v1) or moderated creator uploads (v2).

Field Type Description
soundId string Sound identifier from the platform sound library
action "play" | "stop" | "crossfade" What to do. Default: "play"
loop boolean Loop continuously or play once. Default: false
volume number Volume level (0-1). Default: 0.5
fadeDuration number Fade in/out duration in ms. Default: 500

Multiple sounds can layer (ambient rain + thunder SFX). The frontend manages an audio mixer with channel limits (max 3 concurrent).

Visual Effect

Visual overlays rendered on top of the chat area.

Field Type Description
effect string Effect identifier from the whitelisted set
intensity number Effect strength (0-1). Default: 0.5
duration number | "sustained" How long the effect lasts in ms, or sustained until another rule cancels it

Whitelisted effects:

Effect What it does
"vignette" Darkened edges, focuses attention on center
"danger-pulse" Subtle red pulse at screen edges
"golden-glow" Warm golden light overlay (achievements, discoveries)
"frost" Frost creeping at edges (cold environments)
"particles-rain" Rain particle overlay
"particles-snow" Snow particle overlay
"particles-embers" Floating ember particles (fire, forges)
"particles-dust" Floating dust motes (old places, ruins)
"shake" Brief screen shake (impacts, explosions)
"flash" Brief white flash (lightning, magic)

Effects are CSS animations and lightweight canvas overlays. They must not interfere with text readability or input interaction. Particle effects use pointer-events: none and stay below a performance budget (target: <2% CPU on mid-range mobile).

prefers-reduced-motion disables all animated effects automatically. Sustained effects resolve to their static equivalent (vignette stays, particles don't animate, shake doesn't fire).

Theme Override (v2)

Temporarily shift theme variables for atmospheric effect.

Field Type Description
overrides object Theme variable overrides: { "colorPrimary": "#1a0a2e", "baseMode": "dark" }
transition number Transition time in ms. Default: 800

Limited to a safe subset of theme variables — colors and base mode only. Typography, spacing, and component-structural variables are not overridable.

When the rule deactivates (triggers no longer match), the theme reverts to the conversation's base theme with the same transition.

Emote (v3 — requires Chat UI v2)

Change the character's displayed expression or pose if the character has multiple sprites/expressions.

Field Type Description
expressionId string ID of the expression variant

Evaluation Model

Scripts are evaluated entirely client-side. The backend stores and serves definitions — it never evaluates triggers or fires actions.

Message arrives (SSE stream completes)
  → Frontend loads active scripts for this conversation
  → For each rule, evaluate all triggers against:
      - Current message text
      - Current tracker state (from tracker_json)
      - Message metadata (role, count, etc.)
  → Collect all matching rules
  → Sort by priority (highest wins per action type)
  → Apply winning actions to chat UI state

Why client-side:

Conflict Resolution

Multiple rules can match simultaneously. When two rules want to set the same action type (e.g., both want to change the background), priority wins. Equal priority on the same action type: the rule defined later in the list wins.

Each action type resolves independently. One rule can win the background while another wins the sound — allowing layering: a location-based background rule and an event-based sound rule coexist without conflicting.

Execution Rules

State Management

Script atmosphere state lives in the chat view store:

interface ScriptAtmosphereState {
  activeBackground: {
    imageUrl: string
    opacity: number
    blur: number
    transition: string
  } | null

  activeSound: {
    soundId: string
    loop: boolean
    volume: number
  } | null

  activeEffects: Array<{
    effect: string
    intensity: number
    duration: number | 'sustained'
  }>

  themeOverrides: Record<string, string> | null

  soundMuted: boolean
  toggleSoundMute: () => void
}

This state is ephemeral — not persisted to the database. Refreshing the page re-evaluates scripts against the latest message and reestablishes the correct atmosphere. Conversation-start rules set the baseline.

Performance Budget

Scripts must not degrade chat performance.

Concern Budget
Trigger evaluation per message < 5ms (keyword scan + tracker comparison)
Background image load Lazy-loaded, thumbnail first, full image async
Particle effects < 2% CPU on mid-range mobile, requestAnimationFrame driven
Sound loading Preloaded on conversation open, streamed if > 500KB
Memory < 10MB total for all active script assets

Package Integration

Scripts are a first-class package component. A package that ships a complete experience bundles:

Package: "The Crystal of Dawn — A Fantasy RPG"
├── Character: Dawn Keeper
├── Mode: Fantasy RPG
├── Lorebooks: World of Aethermoor, Bestiary
├── Trackers: HP, Location, Time of Day, Roster
├── Gallery: Scene Backgrounds (20 images)
├── Scripts:
│   ├── "Location Atmosphere" — tracker-driven backgrounds per area
│   ├── "Combat Tension" — heartbeat + danger pulse on low HP
│   └── "Time of Day" — lighting shift between day/evening/night
└── Theme: Dark Fantasy

The combination of trackers + scripts + gallery + theme transforms a text chat into something that feels like a place. The tracker knows you're in a dungeon. The script shows the dungeon. The theme colors the UI dark. The sound drips water from stone walls.

Scripts can reference:

Scripts cannot reference assets outside their package/character scope.

Lock Behavior

When a package has scripts_locked = TRUE:

When scripts_locked = FALSE (default):


Creator Editor

The script editor is a visual form, not a code editor. Creators don't see JSON — they see a structured rule builder.

┌─ Script: Weather Atmosphere ─────────────────────────────────────┐
│                                                                   │
│  ┌─ Rule 1: Rainy Scene ──────────────────────────── [▲▼] [✕] ─┐│
│  │                                                               ││
│  │  Triggers                                              [+ Add]││
│  │  ┌──────────────────────────────────────────────────────────┐ ││
│  │  │ 🔤 Keyword   "rain, rainy, storm, downpour"             │ ││
│  │  │    Scope: Assistant messages · Match: Word boundary      │ ││
│  │  └──────────────────────────────────────────────────────────┘ ││
│  │                                                               ││
│  │  Actions                                               [+ Add]││
│  │  ┌──────────────────────────────────────────────────────────┐ ││
│  │  │ 🖼 Background  [rainy-street.jpg]  Crossfade 1s         │ ││
│  │  │ 🔊 Sound       Rain Ambient        Loop · Vol 0.5       │ ││
│  │  └──────────────────────────────────────────────────────────┘ ││
│  │                                                               ││
│  │  Priority: [10]   Cooldown: [—]   Revert: [—]                ││
│  └───────────────────────────────────────────────────────────────┘│
│                                                                   │
│  ┌─ Rule 2: Sunny Scene ──────────────────────────── [▲▼] [✕] ─┐│
│  │  ...                                                          ││
│  └───────────────────────────────────────────────────────────────┘│
│                                                                   │
│                                                          [+ Rule] │
│                                                                   │
│  ┌────────────────────────────────────────────── Cancel   Save ─┐│
│  └───────────────────────────────────────────────────────────────┘│
└───────────────────────────────────────────────────────────────────┘

Trigger inputs:

Action inputs:

Live Preview

The editor includes a preview pane that simulates a chat conversation. Creators type sample messages and see their rules fire in real time — backgrounds change, sounds play, effects appear.

The preview uses the same evaluation engine as the actual chat, so what the creator sees is exactly what users experience.


Sound Library

v1: Platform-Curated Library

A set of high-quality ambient sounds and SFX provided by the platform.

Ambient (looping):

SFX (one-shot):

Format: Pre-encoded, served from CDN. Small file sizes for quick loading.

v2: Creator Uploads

Creators can upload custom sounds with:


Security Model

Why Declarative Only

Scripts must be declarative data — never executable code. The attack surface of "creator-defined behavior that runs in other users' browsers" is enormous if actual code execution is allowed.

What scripts can do:

What scripts cannot do:

Input Validation

Scripts are validated on save (backend):

User Controls

Users have full control over their atmosphere experience:

Control Where What it does
Sound mute Chat header icon Mutes all script sounds. Persisted as user preference
Disable effects Chat settings menu Disables visual effects (particles, shake, flash)
Disable backgrounds Chat settings menu Reverts to theme background, ignoring script backgrounds
Disable all scripts Chat settings menu Turns off the entire script system for this conversation
Per-script toggle Right drawer (WHO/WHAT) Enable/disable individual non-required scripts

prefers-reduced-motion at the OS level automatically disables animated effects. prefers-reduced-transparency simplifies background overlays to solid colors.


Limits

Limit Value Notes
Scripts per character 30 Increase for Pro creators if needed
Triggers per script 5 Multiple triggers OR'd together
Actions per script 5 Multiple actions fire simultaneously
Keywords per trigger 100 Word-boundary matched
Concurrent sounds 3 Oldest sound fades out when limit hit
Concurrent effects 3 Oldest effect removed when limit hit
Sound file size 2 MB Creator uploads only
Sound duration 30s loop / 5s SFX Creator uploads only
Cooldown minimum 2 seconds Prevents rapid-fire triggering

Data Model

Script Entity

ChatScript
├── Id                    int (PK)
├── Uuid                  guid (public identifier)
├── Name                  "Weather Atmosphere"
├── Description           "Reacts to weather in the narrative"
├── OwnerId              int (FK to users)
├── IsPublic             boolean
├── Rules                 ChatScriptRule[] (stored as JSONB)
├── CreatedAt            timestamp
└── UpdatedAt            timestamp

ChatScriptRule (within the JSONB rules array)
├── Key                   string (unique within script, e.g. "rainy-scene")
├── Name                  "Rainy Scene"
├── Triggers             trigger[] (AND logic within a rule)
├── Actions              action[]
├── Priority             int (higher wins on conflict)
├── IsEnabled            boolean (quick toggle without deleting)
├── CooldownSeconds      int (min time between re-fires)
└── RevertAfterSeconds   int | null (auto-revert duration)

Scripts are a standalone entity, not embedded in characters or packages. They're linked via binding tables (same pattern as trackers and lorebooks).

Binding Tables

CharacterScriptBinding
├── CharacterId
├── ScriptId
├── SortOrder
└── IsRequired           (locked in package context)

PackageScriptBinding
├── PackageId
├── ScriptId
├── SortOrder
└── IsRequired

Tables

CREATE TABLE IF NOT EXISTS chat_scripts (
    id SERIAL PRIMARY KEY,
    uuid UUID NOT NULL DEFAULT gen_random_uuid() UNIQUE,
    owner_id INTEGER NOT NULL REFERENCES users(id),
    name VARCHAR(100) NOT NULL,
    description VARCHAR(500),
    is_public BOOLEAN NOT NULL DEFAULT false,
    rules JSONB NOT NULL DEFAULT '[]',
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE IF NOT EXISTS character_script_bindings (
    character_id INTEGER NOT NULL REFERENCES characters(id) ON DELETE CASCADE,
    script_id INTEGER NOT NULL REFERENCES chat_scripts(id) ON DELETE CASCADE,
    sort_order INTEGER NOT NULL DEFAULT 0,
    is_required BOOLEAN NOT NULL DEFAULT false,
    PRIMARY KEY (character_id, script_id)
);

CREATE TABLE IF NOT EXISTS package_script_bindings (
    package_id INTEGER NOT NULL REFERENCES packages(id) ON DELETE CASCADE,
    script_id INTEGER NOT NULL REFERENCES chat_scripts(id) ON DELETE CASCADE,
    sort_order INTEGER NOT NULL DEFAULT 0,
    is_required BOOLEAN NOT NULL DEFAULT false,
    PRIMARY KEY (package_id, script_id)
);

-- Platform sound library
CREATE TABLE IF NOT EXISTS script_sounds (
    id VARCHAR(50) PRIMARY KEY,       -- e.g., 'rain-heavy', 'thunder-crack'
    name VARCHAR(100) NOT NULL,
    category VARCHAR(50) NOT NULL,    -- 'ambient', 'sfx'
    subcategory VARCHAR(50),          -- 'weather', 'nature', 'urban'
    duration_ms INTEGER NOT NULL,
    is_loop BOOLEAN NOT NULL DEFAULT false,
    file_url VARCHAR(500) NOT NULL,
    preview_url VARCHAR(500),
    sort_order INTEGER NOT NULL DEFAULT 0
);

-- Creator-uploaded sounds (v2)
CREATE TABLE IF NOT EXISTS creator_sounds (
    id SERIAL PRIMARY KEY,
    uuid UUID NOT NULL DEFAULT gen_random_uuid() UNIQUE,
    owner_id INTEGER NOT NULL REFERENCES users(id),
    name VARCHAR(100) NOT NULL,
    duration_ms INTEGER NOT NULL,
    is_loop BOOLEAN NOT NULL DEFAULT false,
    file_url VARCHAR(500) NOT NULL,
    file_size_bytes INTEGER NOT NULL,
    moderation_status SMALLINT NOT NULL DEFAULT 0,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

API Endpoints

GET    /api/creator/scripts                     — list creator's scripts
POST   /api/creator/scripts                     — create a script
PUT    /api/creator/scripts/{uuid}              — update a script
DELETE /api/creator/scripts/{uuid}              — delete a script
GET    /api/creator/characters/{uuid}/scripts   — list scripts bound to a character
POST   /api/creator/characters/{uuid}/scripts   — bind a script to a character
DELETE /api/creator/characters/{uuid}/scripts/{scriptUuid} — unbind
GET    /api/scripts/sounds                      — list platform sound library
GET    /api/scripts/effects                     — list available effects
POST   /api/creator/sounds                      — upload custom sound (v2)

Dependencies

Dependency Status Required For
Gallery Shipped Background images
Chat UI redesign Planned Rendering surface (center panel, drawers)
Trackers Planned Tracker-value triggers (Phase 2)
Packages In Progress Bundled distribution
Platform sound library New Sound actions
Theme system Shipped Theme override actions

Phasing

Phase 1 — Keywords + Backgrounds + Sound

Ship the core loop with the simplest triggers and the most impactful actions.

No tracker dependency. Validates the concept with zero dependencies on unshipped features.

Phase 2 — Trackers + Theme + Polish

Once trackers ship, the system gets dramatically more powerful.

Phase 3 — AI-Driven Triggers (Exploration)

The most ambitious extension: the AI itself decides when atmosphere shifts.

This is speculative. Keyword and tracker triggers may prove sufficient. AI-driven triggers add latency, cost, and unpredictability. Ships only if phases 1-2 reveal clear limitations.


Scope Boundaries

In scope:

Out of scope (not planned):


Open Questions