# Automation & custom scripts guide

> Decide between no-code Rules and custom Scripts, let an AI write and test scripts using Studio's Copy AI prompt and Test run tools, and browse the complete events and card API reference.

Most LoreHat stories need zero code — point-and-click **Rules** handle counters, scene cues, mood switches, and variable updates cleanly. When you want custom mechanics that a dropdown form can't express (such as RPG dice rolls, inventory capacity caps, keyword triggers, or clickable panel actions), **Scripts** give you full JavaScript control inside **Advanced → Script** — and Studio's built-in **Copy AI prompt** button lets an AI write the code for you.

New to automations? Start with [Automating your story with rules](/en/creator/workers-for-beginners/) first.

![Studio Advanced Rules screen — start with Rules for everyday automation, and reach for Scripts only when custom logic is needed](/illustrations/studio-systems/studio-rules.webp)

## Rules vs. Scripts: Which one fits your scenario?

| What you want to build | Use Rules or a Script? | Why |
| :-- | :-- | :-- |
| **Add +1 to a turn counter, flip a flag on scene entry, or cue a writing style at `trust >= 60`** | **Rules** (up to 32) | Faster to build, zero syntax mistakes, checked visually by Studio |
| **Notice specific words in what the player types** _(e.g., if they mention "password" or "knock", whisper a cue to the AI)_ | **Script** (up to 10) | Scripts can inspect the player's message text directly |
| **Roll dice, calculate RPG damage/stamina, or clamp numbers between 0 and 100** | **Script** | Handles math, formulas, and custom bounds cleanly |
| **Power an interactive panel's buttons** _(save clues to a board, check max inventory slots, buy an item only if `gold >= price`)_ | **Script** | Handles `component.action` clicks with exact validation |
| **Give the AI a brand-new custom tool** _(such as `roll_dice` or `check_lock`)_ | **Script** | Scripts can declare custom model tools the AI calls mid-turn |

**How Rules and Scripts work together:** On every chat event, LoreHat evaluates your **Rules** first and then runs your **Scripts** against the same snapshot of the story state, applying all resulting updates together cleanly. If a script ever hits an error or runs too long, LoreHat safely skips that event's changes so the player's chat never crashes.

## Don't write code? Let an AI write & test your Script in 5 steps

You never need to memorize the API reference below to add a custom script:

1. **Declare your variables first:** Open **Work variables** and create every variable the script will read or update (with clear names like `trust`, `gold`, `clues`, or `visits`).
2. **Create a Script:** Open **Advanced → Script** and add a new script.
3. **Click `Copy AI prompt`:** Studio automatically copies a tailored prompt containing your work's exact variable names, types, initial values, current code, and a link to this reference page.
4. **Paste into ChatGPT, Claude, or Gemini — plus your plain-English wish:** Paste Studio's prompt, then add 2–4 plain sentences describing what you want (see the ready-to-paste examples below!). Paste the returned JavaScript block right back into Studio.
5. **Check it immediately with `Test run` and `Preview chat`:**
   - Open **Test run** inside the Script editor to verify the script before even starting a chat. For example, with the `knock` script below:
     1. First make sure you declared a **Number** variable named `visits` with initial value `0` under **Work variables**.
     2. Open **Test run**, set **Event** to `message.sent`, enter `"I knock softly on the door."` in **Message text**, and click **Run**.
     3. Confirm the output shows `visits` changing from `0` to `1` and the prompt hint `"Describe footsteps behind the door before the reply."` queued up.
     4. Click **Reset state** whenever you want to test again from initial values.
   - If Studio highlights a warning or error in the editor, copy the message along with **Copy AI prompt** (which includes your current script and variables), ask your AI to fix it, paste the updated script back into Studio, and **re-run `Test run` and `Preview chat → Restart`** to confirm the fix works cleanly.

### Three plain-English requests you can add after Studio's `Copy AI prompt`

Copy any of these right below the prompt Studio copied for you, then swap the bracketed details for your own story:

**1. Secret keyword reaction (Mystery / Horror)**

```text
My request:
Whenever the player sends a message that mentions "knock", "basement", or "cellar" (case-insensitive), add 1 to `suspicion` (max 10) and add a one-turn AI hint: "The character freezes briefly and glances toward the cellar door before answering." Do not trigger twice on the same turn.
```

**2. Shop / inventory purchase with server-side price table (RPG / Cozy Sim)**

```text
My request:
Handle component action "shop.buy" where the component sends only { itemId } (never trust a price from the component payload). Define a canonical item price table right inside the script (for example: { lantern: 15, harbor_map: 25, warm_cloak: 40 }). In one atomic check: verify `itemId` exists in the catalog, confirm `inventory` doesn't already include `itemId`, and confirm `gold >= price`. If valid, subtract `price` from `gold`, add `itemId` to `inventory`, and add a short AI hint saying the player just bought that item. If `gold` is too low or the item is already owned, make no balance change and add an AI hint explaining why the shopkeeper declined.
```

**3. Relationship milestone + mood auto-sync (Romance / Drama)**

```text
My request:
Whenever variables change and `trust` crosses from below 50 to 50 or above, set `trust_milestone_reached` to true, apply the writing style "warm-candid", and add a one-turn hint: "The character realizes they genuinely trust the player now; let this show subtly in body language." Never fire again once `trust_milestone_reached` is true.
```

### A quick peek at how clean a Script looks

```js
card.on('message.sent', (event) => {
  card.vars.add('visits', 1);

  if (/knock/i.test(event.message.text)) {
    card.prompt.note('Describe footsteps behind the door before the reply.', 70);
  }
});
```

---

## Reference for AI assistants & script authors

The tables below are generated directly from LoreHat's live contract so event names, state fields, effects, and helper functions always match what Studio and the server accept. Studio's **Copy AI prompt** links your AI straight to this section automatically.

### 1. Events

| Event | When it occurs | Common use |
| :-- | :-- | :-- |
| `chat.started` | A new conversation is created | One-time initial setup or opening notes |
| `chat.resumed` | An existing conversation resumes | Lightweight resume notes |
| `message.sent` | The player sends a message | Counters, keyword reactions, notes for this turn |
| `message.received` | The character's reply lands | Updating state for the next turn |
| `scene.entered` | A story node transition completes | Scene flags, appearance switches, writing style |
| `choice.selected` | A story choice is accepted | Route and consequence tracking |
| `variables.changed` | Variable values actually change | Derived-state reactions (cascades 1 level) |
| `component.action` | A component calls `card.emit` | Inventory, clue boards, shops, custom buttons |

Payload of each event:

- `chat.started` — no payload
- `chat.resumed` — no payload
- `message.sent`
  - `message`: object
- `message.received`
  - `message`: object
- `scene.entered`
  - `sceneId`: string — Stable identifier, unique across the whole card (all entity types share one namespace). 1-128 chars: letters, digits, "." "_" ":" "-", starting with a letter or digit. Examples: "character-su-wanzhao", "quiet-seat", "affinity". Never reuse an id for a different entity; rename = delete + create.
- `choice.selected`
  - `choiceId`: string
  - `sceneId`: string — Stable identifier, unique across the whole card (all entity types share one namespace). 1-128 chars: letters, digits, "." "_" ":" "-", starting with a letter or digit. Examples: "character-su-wanzhao", "quiet-seat", "affinity". Never reuse an id for a different entity; rename = delete + create.
- `variables.changed`
  - `changed`: string[] — Ids of the variables whose value really changed.
  - `previous`: object — Values before the change, by variable id.
- `component.action`
  - `action`: string
  - `componentId`: string — Stable identifier, unique across the whole card (all entity types share one namespace). 1-128 chars: letters, digits, "." "_" ":" "-", starting with a letter or digit. Examples: "character-su-wanzhao", "quiet-seat", "affinity". Never reuse an id for a different entity; rename = delete + create.
  - `payload`: object (optional)

- `component.action` only notifies rules and scripts and never sends a chat message; a component that wants to speak as the player calls `card.send(text)`, which raises `message.sent`.

### 2. State (`card.vars`, `card.props`, `card.system`)

Scripts read the current state through `card.vars.<id>` and `card.system` (`turn`, `scene: { id, name, visited }`, `isFirstTurn`, `locale`, `personaName`). In scripts, state is read-only — use `card.*` functions to record updates. Rule conditions read the same snapshot using `turnNumber`, `isFirstTurn`, `currentSceneId`, and `visitedScenes`. `locale` and `personaName` are available to scripts and components; `colorScheme` and `accentColor` are only for components, not rule conditions.

- `props`: object
- `system`: object
  - `isFirstTurn`: boolean
  - `locale`: string (optional)
  - `personaName`: string (optional)
  - `scene`: object
  - `turn`: integer
- `vars`: object

### 3. Effects

Rules list effects in Studio's form; scripts call `card.*` functions directly inside a `card.on(event, handler)` callback and never return values. Every effect from one handler is validated and committed together atomically — one invalid variable, node, or writing style rejects the whole batch so state never ends up half-updated.

- `var.set` — Write a variable. Available in: `component`, `rule`, `script`.
  - `id`: string — Name (id) of a declared variable. Call card_outline to list valid names.
  - `value`: JSON — New value, native JSON matching the variable type. null removes the current value.
- `var.add` — Add to a number variable. Available in: `component`, `rule`, `script`.
  - `by`: number — Amount to add; negative subtracts.
  - `id`: string — Name (id) of a declared variable. Call card_outline to list valid names.
- `scene.go` — Move the story to a scene. Available in: `component`, `rule`, `script`.
  - `sceneId`: string — Id of an existing scene entity. Call card_outline to list valid ids.
- `card.suggest` — Suggest the model read readable card entries this turn. Available in: `component`, `rule`, `script`.
  - `ids`: string[] — Readable entry ids, at most 20.
  - `reason`: string (optional) — Why the model should read them, at most 240 chars.
- `writingStyle.use` — Apply a style this turn, whatever its activation mode, while its when-condition holds. Available in: `component`, `rule`, `script`.
  - `writingStyleId`: string — Id of an existing writingStyle entity. Call card_outline to list valid ids.
- `prompt.note` — Inject a one-off note into the next model turn. Available in: `component`, `rule`, `script`.
  - `priority`: integer (optional) — Ordering weight 0-100 among injected notes; higher first.
  - `text`: string — Note text, 1-1000 chars.
- `prompt.rewrite` — Replace the player message of this turn (scripts, message.sent only). Available in: `script`.
  - `text`: string — Replacement player message, 1-8000 chars.
- `look.theme` — Change the chat theme mode and density. Available in: `component`, `script`.
  - `density`: "compact" | "cozy" | "comfortable" | "cinematic" (optional) — Spacing density of the chat. Omit to keep the current one.
  - `themeMode`: "dark" | "light" (optional) — Color mode of the chat. Omit to keep the current one.
- `look.slot` — Style one UI slot. Give at least one style field. Available in: `component`, `script`.
  - `accent`: string | enum (optional) — Accent color (links, highlights).
  - `background`: object (optional) — Background of the slot.
  - `borderColor`: string | enum (optional) — Border color.
  - `fontFamily`: "body" | "display" | "mono" | "serif" (optional) — Font family.
  - `opacity`: number (optional) — Opacity 0.35-1; the floor keeps text readable.
  - `shadow`: "none" | "base" | "floating" | "overlay" (optional) — Shadow level.
  - `slot`: enum — UI slot to style, for example "canvas", "assistantBubble", "userBubble", "titleBarTitle".
  - `surface`: string | enum (optional) — Slot surface color.
  - `text`: string | enum (optional) — Text color.
- `look.reset` — Restore the card default appearance. Available in: `component`, `script`.

- Effects from `message.sent`, `choice.selected`, and `scene.entered` apply before the character writes that turn's reply; effects from `message.received` apply for the next turn.
- `card.prompt.rewrite` replaces the player's message for the current turn (only valid in `message.sent`, and shown to the player with a clear notice; unavailable in Rules).

### 4. Script contract & `card` functions

A handler receives only `event`; `card` is global. Keep handlers synchronous, fast, and deterministic (no network calls, timers, storage, or dynamic `eval`). Source is limited to 65536 characters.

| Call | Effect | Scripts | Components |
| --- | --- | :-: | :-: |
| `card.vars.set(id, value)` | `var.set` | ✓ | ✓ |
| `card.vars.add(id, by)` | `var.add` | ✓ | ✓ |
| `card.scene.go(sceneId)` | `scene.go` | ✓ | ✓ |
| `card.suggest(ids, reason?)` | `card.suggest` | ✓ | ✓ |
| `card.writingStyle.use(writingStyleId)` | `writingStyle.use` | ✓ | ✓ |
| `card.prompt.note(text, priority?)` | `prompt.note` | ✓ | ✓ |
| `card.prompt.rewrite(text)` | `prompt.rewrite` | ✓ | – |
| `card.look.theme(options)` | `look.theme` | ✓ | ✓ |
| `card.look.slot(slot, style)` | `look.slot` | ✓ | ✓ |
| `card.look.reset()` | `look.reset` | ✓ | ✓ |

- Use `card.vars.set(id, value)` to replace a value and `card.vars.add(id, by)` to add or subtract safely. `set` and `add` are reserved variable names.
- Besides the effect functions above, scripts have `card.on(event, handler)` and `card.tool.result(data)`. Optional parameters are marked `name?`.

### 5. Custom model tools declared by a script

A script can declare up to 8 custom tools (metadata declared in the script's **Tools** settings; total platform + script tools per turn cannot exceed 16). Implement a tool by handling `'tool.<tool_name>'` and calling `card.tool.result(data)`:

```js
card.on('tool.roll_dice', (event) => {
  const { rolls } = event.input;
  card.vars.set(
    'last_roll',
    rolls.reduce((sum, n) => sum + n, 0),
  );
  card.tool.result({ rolls });
});
```

Keep tool handlers deterministic (based only on `event.input` and `card.vars`) and fast (tools must finish within 3 seconds).

### 6. Built-in model tools

The AI also has four built-in tools managed automatically by LoreHat:

| Tool | What it does |
| :-- | :-- |
| `read_card` | Lists or reads eligible character profiles, World Lore, unlocked secrets, and current/visited scenes |
| `set_variables` | Updates declared variables that have **Allow AI to adjust** enabled |
| `go_to_scene` | Advances the story along an eligible choice |
| `retrieve_memory` | Searches earlier parts of the conversation |

### 7. Runtime limits

| Limit                                               | Value                                |
| :-------------------------------------------------- | :----------------------------------- |
| Rules per work                                      | 32                      |
| Scripts per work                                    | 10                    |
| Script source length                                | 65536 characters    |
| One script run                                      | 250 ms             |
| Host timeout guard                                  | 1200 ms             |
| Effects per batch (Rules max 8) | 32            |
| `variables.changed` cascade depth                   | 1 level |
| Model tool steps per turn                           | 20             |
| Non-gesture component writes in a row               | 3        |

### 8. Quick troubleshooting checklist

If a script doesn't seem to fire in **Test run** or **Preview chat → Restart**, check three things:

1. **Trigger mismatch:** Does the event name, story node ID, or component action match your current work?
2. **Invalid target:** Is every variable declared with the right type, and does every referenced story node or writing style exist? (Remember: one invalid effect rejects the entire batch so nothing is half-applied.)
3. **Syntax or rule issue:** Check the red/yellow markers in Studio's code editor, copy the error note together with **Copy AI prompt** to ask your AI for a fix, paste the updated script back in, and verify it again in **Test run** and **Preview chat → Restart**.

Next: explore [Interactive panels & overlays guide](/en/creator/components-reference/) or [Test, review, publish, and update a work](/en/creator/publish/).

### Optional: editing cards from a coding assistant

Most creators work directly in LoreHat Studio and can skip this box. If you already use a coding assistant like **Codex** or **Claude Code** and want it to read and edit your cards directly, copy the setup prompt below:
