BlueGit

timfa questward

Files

questward / docs / SCRIPTS.md

SCRIPTS.md

SCRIPTS.md 39.8 KiB Download Raw

Player scripts (AFK / offline)

Status: not implemented (design only) Related: tile_mmo_server_technical_design_v0.6.md §18 (controller abstraction, offline entity, sandbox rules)

Scripts are a sandboxed language interpreted on the server. They never mutate world state directly; they emit the same player intents as a human client (moveTo, gather, craft, attack, shop, equip, …). The server validates every step.

This document is the product + language spec for implementation.

---

1. Goals

  • Automate simple loops: gather → bank/craft → fight → recover.
  • Run while online (watch + stop bar), while AFK (idle 30+ minutes), or while offline (character stays in the world, max 1 hour).
  • Keep the language small, readable, and hard to misuse.
  • Fail loudly: toast (online) or pigeon letter (offline), with line + operation + reason.

---

2. Player UI

2.1 Scripts button

  • HUD control Scripts opens the Scripts panel.
  • Panel lists the player’s saved scripts (name + badges for Offline / AFK flags).
  • Actions per script: Edit, Delete, Run (online).
  • New script creates an empty script and opens the editor.

2.2 Script editor

  • Name field.
  • Text area with syntax highlighting (keywords, strings, numbers, comments, labels, @ vars).
  • Flags (mutually independent; at most one script should be marked for each role — marking one clears that flag on others):
  • Run this while offline — eligible on logout confirmation.
  • Run while AFK — auto-starts after 30 minutes with no player actions.
  • Live world coordinates at the bottom of the editor (player’s current tile, e.g. Position: (5, 18)), updating as the character moves while the panel is open — so authors can copy values into set @waypoint (5, 18).
  • Optional: a small Copy control that copies set @here (x, y) (or just (x, y)) to the clipboard.
  • Save / Cancel.

2.3 Online run bar

When a script is running (started manually, AFK auto-start, or resumed after re-login onto an offline script):

  • Fixed bar at the bottom of the screen.
  • Shows: script name, current line (number + source text), Stop.
  • Manual player intents (move, attack, gather, …) stop the script (treat as cancel), except pure camera/UI (open bag, zoom, settings).

2.4 Logout confirmation

On logout while in the world:

1. Modal: Are you sure you want to log out?

  • No — stay.
  • Yes — log out.
  • Checkbox (default unchecked): Run offline script
  • Enabled only if the player has a script marked Run this while offline.

2. If the checkbox is checked, show an extra red line: Running a script means your character remains in the world and can still be attacked! 3. Confirming with the checkbox checked starts/continues the offline script on that character (see §4).

---

3. Modes

ModeHow it startsCharacter in worldClient
OnlineScripts panel → RunYesConnected; run bar visible
AFKNo gameplay intents for 30 minutes, and an AFK-marked script existsYesStill connected; run bar appears when script starts
OfflineLogout with offline checkboxYes (no NetworkIdentity; keeps ChunkLoader)Disconnected

AFK timer: reset on any gameplay intent sent by the player (move, attack, gather, craft, shop, equip, cast, pickup, talk, …). Opening UI / scrolling chat does not reset AFK if those are not intents; prefer resetting on any outbound play command for simplicity.

Offline duration: max 1 hour from offline-script start (or remaining time after restart rehydrate). Then: stop script, despawn character, persist as a normal logout.

Re-login during offline script: attach the client to the existing entity; keep the script running; show the run bar so the player can Stop.

---

4. Errors

4.1 Message shape

Always:

Line <n>: <operation> — <reason>

Example:

Line 12: mine — No reachable iron ore nearby.

4.2 Online / AFK (client connected)

  • Stop the script.
  • Show a persistent toast (stays until the player dismisses it) with the error message.

4.3 Offline (no client)

  • Stop the script.
  • Remove the character from the world (normal offline persist).
  • Queue a pigeon letter:
  • Author display name: Frederick
  • Role flavour: manager of Idle Gaming (author line / signature as other system letters do)
  • Body:

Unfortunately, your script encountered an error. then a blank line, then the error message from §4.1.

---

5. Language overview

  • Line-oriented, case-insensitive keywords.
  • One statement per line (blank lines and comments allowed).
  • Comments: # ... to end of line.
  • Strings: "double quotes" (names of blocks, mobs, items).
  • Name matching is exact (full display name), case-insensitive, never fuzzy / substring / “closest spelling”. "Tin" does not match "Tin ore".
  • Numbers: integers (10, 100).
  • Labels: label name_here — name is letters, digits, underscore.
  • Variables: @name (letters, digits, underscore after @). Set with set (§5.2). Hold a target, a tile coordinate, or (later) a number if needed.
  • Implicit targets (block / mob / ground) still exist alongside @ vars.
  • No user-defined functions in v1.
  • Sandbox: not JavaScript; custom interpreter only (§18.7 design doc).

5.1 Implicit targets

The script keeps three optional targets (cleared when a new target of that kind is set, or on error/stop):

TargetSet byUsed by
Blockfind block "..."go, mine, chop, harvest, craft, in range block
Mobfind mob "..."go, attack, buy, sell, in range mob
Groundfind ground "..."go, take, use, in range ground

go without a kind uses the most recently set target. Prefer explicit forms when ambiguous: go block, go mob, go ground.

5.2 Variables (@ + set)

StatementMeaning
set @tree targetCopy the most recently set implicit target (block / mob / ground) into @tree.
set @tree block / set @tree mob / set @tree groundCopy that specific implicit target kind into @tree.
set @furnace hereStore the player’s current tile as coordinates in @furnace.
set @waypoint (5, 18)Store absolute tile coordinates (5, 18) in @waypoint. Preferred literal form.
set @furnace 512 128Same as (512, 128) — space-separated form also accepted.
go @furnacePath to the stored coords or to the stored target (same rules as go).
go block @treeIf @tree holds a block target, path to it (explicit kind).

Rules:

  • Soft cap: 32 variables per running script.
  • Variables live in runtime state (persisted across offline rehydrate / re-login for that run). They are not saved with the script source.
  • Using an unset @name → error (go — @furnace is not set.).
  • Storing a target keeps enough identity to re-resolve (tile + kind + name / entityId). If the world object is gone when used → error (go — Target is gone.).

Waypoints: because go only works within 2 chunks (§6.2), authors manually chain coordinate variables for long trips (e.g. mine → mid → furnace).

---

6. Statements (v1)

6.1 Targeting

StatementMeaning
find block "Iron ore"Closest reachable block whose display name equals (case-insensitive). Search = visible chunk neighbourhood only (player’s chunk + 8 surrounding = Chebyshev chunk distance ≤ 1, same as VISIBLE_CHUNK_RADIUS). Sets block target. Fails if none.
find mob "Shopkeeper"Closest living mob/NPC with exact name match in that same 3×3 chunk window. Sets mob target. Fails if none.
find ground "Log"Closest ground item with exact name match in that same 3×3 chunk window. Sets ground target. Fails if none.

“Closest” = Chebyshev tile distance, then path-reachable. Unreachable candidates are skipped. Multiple exact name matches → closest wins. Scripts must not see farther than a connected player would for entity/block discovery — never scan the full 2-chunk map ring.

6.2 Movement

StatementMeaning
goPath to the last set target (block / mob / ground). Blocks until arrived or fails.
go block / go mob / go groundSame, explicit target kind.
go @namePath to a variable (coords or stored target).
run on / run offToggle run gait (same rules as player: needs stamina).

Range hard rule: the destination tile (target or @ coords) must lie within 2 chunks of the player (Chebyshev chunk distance ≤ 2; with CHUNK_SIZE 16 that is ≤ 32 tiles in chunk metric). Otherwise the op fails immediately:

go — Too far away.

There is no automatic multi-hop pathing across the world. Use coordinate waypoints (set @mid … / go @mid / go @furnace) for longer trips.

Arrival = standing on the tile (ground item / interactable) or adjacent where the game requires adjacency (stations, melee, gather nodes).

6.3 Gathering & world interact

StatementMeaning
mineGather/mine the targeted block (ore boulder, etc.). Blocks until finished or fails.
chopFell the targeted tree block. Blocks until finished.
harvestPick/harvest the targeted plant/herb/flower/cotton block. Blocks until finished.
takePick up the targeted ground item into the bag.
useInteract with the targeted ground item if it has a use (e.g. light a log).

Exact gather verb must match what the block supports; wrong verb → error (chop — That is not a tree.).

6.4 Crafting stations & alchemy

Principle: script steps mirror what a player does in the UI. No free shortcuts that skip materials, skill, adjacency, or recipe knowledge.

Station state hard rule: cauldron / furnace / anvil / every craft station progress is per player, never shared on the tile. Many characters may use the “same” station block at once without interfering. Scripts and the UI obey the same rule — this applies to all current and future crafting stations.

Inventory hard rule (stations — script and player): an item is never committed into a station. Slots in craft/brew UIs are a view / reservation over the bag only — materials do not leave the inventory when placed in a station slot. Even when it looks like something sits in the cauldron or bench, it is still in the bag. Therefore:

  • Closing the station UI, cancelling, cauldron clear, script stop/error, logout, or death mid-craft / mid-brew must leave the bag unchanged for those materials (or immediately show them back — there was nothing to return from the station itself).
  • Item loss due to closed UI or death while using a station is impossible.
  • Materials are consumed only when the craft/brew successfully completes (same moment the product is created), never earlier.

This is a gameplay rule for humans and scripts alike (also .cursor/rules/station-inventory.mdc); the script layer must not invent a different consume-on-insert path.

Crafting stations (furnace, anvil, woodworking, bench, spinning wheel, loom, tailor, leatherworking, …)

StatementMeaning
craft "Bronze bar"At the targeted station block, start the same craft the player would (one product). Blocks until finished or fails (not at station, unknown recipe, missing mats, skill too low). Mats stay in the bag until success (§6.4).
craft "Cotton sweater" dyeTailor only: craft with dyeing on. Uses a random dye charge from the bag (no colour picker). Fails if dyeing is requested and the bag has no dye uses left.
craft "Cotton sweater"Tailor (or other station) without dyeing.

Alchemy cauldron — manual steps (1:1 with UI)

Require adjacency to a cauldron block (find + go), same as opening the cauldron as a player. Brew progress is this character’s cauldron state only.

StatementMeaning
cauldron insert "Thyme"Select/reserve that ingredient from the bag for the brew UI (does not remove it from inventory — §6.4 inventory hard rule).
cauldron heatHeat.
cauldron stirStir.
cauldron coolCool.
cauldron bottleBottle into an empty glass bottle. Blocks until done. On success, reserved mats + bottle are consumed and the potion is granted.
cauldron clearClear/abandon the brew UI selection; bag unchanged.

Step order and outcomes match humans: correct sequence → potion (with Alchemy skill roll); wrong sequence → unstable brew. Scripts get no easier success path.

Example (same steps a player would click):

find block "Cauldron"
go block
cauldron insert "Thyme"
cauldron heat
cauldron insert "Mint"
cauldron stir
cauldron bottle

Named brew — only with a recipe paper in the bag

StatementMeaning
brew "Lesser health tonic"Allowed only if the inventory contains a recipe paper for that potion. Then run that paper’s recorded steps and bottle (skill checks as usual). Mats are reserved until success, then consumed with the bottle — never lost on interrupt. Fails immediately if no matching recipe is in the bag (brew — No recipe for that in your bag.).

Without a recipe item, authors must write the cauldron … steps themselves. brew is “follow this paper,” not free knowledge of the recipe.

Dyes (flower list, same as dye tab)

StatementMeaning
cauldron dye ["White flower", "Yellow flower", "Yellow flower"]Make dye from that multiset of flowers (here: 1 white + 2 yellow). List order = insert order; repeat a name for more of the same flower. Flowers are reserved from the bag until the dye brew completes successfully; colour/yield rules match the normal dye UI. Fails if flowers missing, not at cauldron, or bottling not possible.

List syntax: [ "...", "..." ]. Exact flower display names only.

6.5 Dry-run: can before any action

can prefixes any action statement and returns whether that exact line would succeed right now, without mutating world state (no path start, no craft start, no item move).

Forms:

  • Standalone is not used — always in conditions: if can … / while can … / wait until can … or N
  • Syntax: can + the same tokens as the action line (including args and @ vars)

Examples:

ConditionTrue when…
can craft "Bronze bar"At station, recipe known, mats + skill OK
can mineBlock target set, in gather range, tool/skill OK, node still there
can go / can go @furnaceDestination set/resolvable, ≤ 2 chunks, path exists
can bank deposit "Tin ore" 20At bank, at least 1 Tin ore movable (qty overflow rules still apply)
can buy "Feather" 10Shop mob targeted, in range, stock + coins OK
can cast "Spark" on mobSpell known, valid target, not on CD, in approach range or pathable within 2 chunks
can brew "Lesser health tonic"Matching recipe paper in bag, at cauldron, mats OK
can find block "Tin ore"Exact name exists in the visible 3×3 chunk window (and reachable if find requires it)
can cauldron bottlePer-player brew ready to bottle + empty bottle

Not actions (no can): pure control (label, goto, if, end, for, while, wait, stop, set, run on/off). find is an action for can find block "Tin ore" (true if such a find would succeed).

Implementation: share the same validation path as the real command; skip the mutate/apply step.

6.6 Combat & shops

StatementMeaning
attackAttack the targeted mob (player Attack intent). Does not wait for the kill by itself — use wait until target dead or 60 (§6.13).
stop attackCancel the current attack engage (player cancel-attack).
buy "Feather" 10Buy quantity from targeted shop mob. Fails if no shop, not in range, can’t afford, or not stocked.
sell "Soft leather" 5Sell quantity to targeted shop mob (if it buys).

Follow is intentionally not supported.

6.7 Inventory, gear & vitals

StatementMeaning
equip "Bronze pickaxe"Equip a matching item from the bag into its proper slot. Fails if missing or not equippable.
unequip weaponClear that equipment slot into the bag. Slots: head, chest, legs, boots, weapon, offhand (same as game). Fails if the bag has no free space.
drink "Lesser health tonic"Drink a matching consumable from the bag.
eat "Apple"Eat a matching food from the bag.
drop "Tin ore" 5Drop quantity from the bag onto the ground.
read "Spark spellbook"Read a spellbook from the bag to learn its spell (same as player). Fails if missing, already known, or requirements not met.
if health below 30 …See control flow.
if stamina below 5 …See control flow.

6.8 Range checks & queries

StatementMeaning
if in range block "Furnace"True if a matching block exists in the visible 3×3 chunk window (same as find) and is within interaction/path rules.
if in range mob "Deer"True if a matching living mob is within 15 tiles Chebyshev and inside the visible 3×3 chunk window.
if in range ground "Bones"True if a matching ground item is within 15 tiles and inside the visible 3×3 chunk window.
if in range item "Bronze bar"True if the bag contains that item (quantity ≥ 1).
if bag has "Tin ore" at least 10Bag quantity check.
if bag has "Tin ore" below 10Bag quantity check.
if target health below 20Targeted mob current HP below N. Fails the condition (false) if no mob target; does not hard-error.
if target deadTargeted mob is gone or at 0 HP.

6.9 Bank, cheques, market, social economy

Requires being at / having path-interacted with the right block where the game requires it (bank counter, bounty office, marketplace).

StatementMeaning
bank deposit "Tin ore" 20Move quantity from bag → vault.
bank withdraw "Tin ore" 20Move quantity from vault → bag.
write cheque "Tin ore" 50Write a cheque reserving that item+qty from the bank (vault). Fails if the vault lacks enough.
redeem chequeRedeem a written cheque from the bag at a bank (goods → vault), same as player.
market sell "Tin ore" 10 for 8Place sell order (qty, min unit price). Escrows goods + listing fee like the UI.
market buy "Tin ore" 10 for 12Place buy order (qty, max unit price). Escrows coins like the UI.
market cancel sell / market cancel buyCancel the character’s open order of that side (or nearest matching — prefer cancelling by item name if multiple: market cancel sell "Tin ore").
raise bounty on "Ada Worker" 100Raise bounty (near bounty office, pays from bag).
send pigeon to bankCourier cargo to own bank (same rules as UI).
send pigeon to "Ada Worker"Courier to that character; payload prefers a written letter, else a cheque (§13).
write letter "..."Write body onto a blank letter in the bag (fails if none); does not send.
say "hello"Local chat say.

6.10 Spells

StatementMeaning
cast "Light"Cast on the targeted block tile (tile-target spells). Approaches into range if needed (same as player cast). Blocks until cast attempt resolves; fizzle is not an error (line completes). Approach still obeys the 2-chunk go limit.
cast "Spark" on mobCast entity-target spell on the mob target.
cast "Light" on blockExplicit tile target = targeted block’s tile.

Fails if unknown spell, not learned, on cooldown, out of range with no path, or wrong target kind.

6.11 Labels & jumps

StatementMeaning
label campDeclare label camp.
goto campJump to that label.

Forward and backward jumps allowed. Jumping into/out of loops is disallowed (error if attempted).

6.12 Control flow

if health below 30
  goto heal
end

if stamina below 5
  run off
end

if can craft "Bronze bar"
  craft "Bronze bar"
end

if can go @furnace
  go @furnace
end

if in range item "Bronze pickaxe"
  equip "Bronze pickaxe"
end

for 10
  find block "Tin ore"
  go block
  mine
end

while in range mob "Rat"
  find mob "Rat"
  go mob
  attack
  wait until target dead or 60
end

Rules:

  • Blocks end with end.
  • if body runs when the condition is true; no else (use a second if / goto).
  • for N — repeat body N times (N ≥ 1, max 1000).
  • while <condition> — repeat while condition true; max 1000 iterations per while then error (while — Too many repeats.).
  • Conditions:

health below N · stamina below N · can <action…> (§6.5) · in range block|mob|ground|item "..." · bag has "..." at least|below N · target health below N · target dead

6.13 Waiting (wait / wait until)

StatementMeaning
wait 2Pause 2 seconds (server time). Max 60 per wait.
wait until arrived or 30Block until the current path finishes (usually redundant after go, which already waits).
wait until gathered or 120Block until the active mine/chop/harvest completes.
wait until crafted or 120Block until the active station craft / brew / cauldron bottle completes.
wait until target dead or 60Block until the mob target is dead or despawned. Fails if no mob target.
wait until health at least 50 or 120Block until own HP ≥ N.
wait until stamina at least 5 or 60Block until stamina ≥ N.
wait until in range item "Bronze bar" or 60Block until bag has that item.
wait until in range mob "Deer" or 30Block until such a mob is in range.
wait until bag has "Tin ore" at least 10 or 300Block until quantity met.
wait until can craft "Bronze bar" or 60Block until that dry-run would succeed.
wait until can go @furnace or 60Block until the destination is ≤ 2 chunks and pathable (e.g. after walking a midpoint waypoint).

Principle: every boolean condition usable in if / while is also valid after wait until. Extend this set whenever new conditions ship. can <action> is valid anywhere a condition is.

Timeout is mandatory: every wait until must end with or <seconds> (1–300). Bare wait until … without or N is a parse error. On timeout → script error (wait until — Timed out.).

go / gather / craft / brew already block like a built-in wait for their own completion (they have natural end conditions; no separate or N on those verbs).

6.14 Utility

StatementMeaning
stopEnd the script successfully (no error letter).

---

7. Death while a script is running

If the character dies for any reason while a script is active (online, AFK, or offline):

1. Stop the script immediately (not an “error letter” unless death was caused mid-op failure — death itself is a clean stop). 2. Cancel any in-progress station/cauldron UI state for that player; bag contents for reserved station mats are unchanged (§6.4 inventory hard rule). 3. Fully log the instance out of the world (despawn entity, persist dead flag / position as normal death logout). 4. When the player next connects, they see the normal respawn screen — no auto-respawn from scripts.

There is no respawn script command.

---

8. Example scripts

8.1 Tin loop with panic flee

# Tin loop with panic flee
label start
equip "Bronze pickaxe"
run on

for 20
  if health below 25
    goto flee
  end
  find block "Tin ore"
  go block
  mine
  if in range ground "Tin ore"
    find ground "Tin ore"
    go ground
    take
  end
end
stop

label flee
run on
drink "Lesser health tonic"
stop attack
find block "Bank"
go block
bank deposit "Tin ore" 999
stop

8.2 Bronze mining bot (equal tin/copper → smelt → bank)

Furnace is ~4 chunks from the mine (beyond the 2-chunk go limit), so the author pre-saves waypoints by standing on tiles and using set @… here, or by writing coordinates. Bank is near the furnace here; bronze goes to the vault via bank deposit (or send pigeon to bank if preferred).

Smelting consumes tin and copper in pairs, so the loop mines whichever ore is missing first — stock stays balanced.

# Waypoints (edit coords to your world; mid is ~2 chunks from mine toward furnace)
# Tip: open the script editor and read Position: (x, y) at the bottom while standing on each tile
set @mine (800, 400)
set @mid (800, 432)
set @furnace (800, 464)
set @bank (804, 464)

equip "Bronze pickaxe"
run on

label loop
# Equal ores: mine whichever is missing; smelting consumes pairs so stock stays balanced
if bag has "Tin ore" below 1
  goto mine_tin
end
if bag has "Copper ore" below 1
  goto mine_copper
end
goto smelt

label mine_tin
go @mid
go @mine
find block "Tin ore"
if can go block
  go block
  mine
end
if in range ground "Tin ore"
  find ground "Tin ore"
  go ground
  take
end
goto loop

label mine_copper
go @mid
go @mine
find block "Copper ore"
if can go block
  go block
  mine
end
if in range ground "Copper ore"
  find ground "Copper ore"
  go ground
  take
end
goto loop

label smelt
go @mid
go @furnace
find block "Furnace"
go block
while can craft "Bronze bar"
  craft "Bronze bar"
end
go @bank
find block "Bank"
go block
bank deposit "Bronze bar" 999
goto loop

---

9. Syntax highlighting (editor)

Highlight at least:

ClassExamples
Keywordfind, go, mine, chop, harvest, craft, brew, cauldron, attack, buy, sell, equip, unequip, drink, eat, drop, read, cast, bank, market, write, redeem, raise, send, say, label, goto, if, end, for, while, wait, stop, run, take, use, can, set
Subkeywordblock, mob, ground, item, health, stamina, below, at, least, in, range, on, off, until, or, arrived, gathered, crafted, target, dead, here, deposit, withdraw, cheque, pigeon, bounty, sell, buy, cancel, insert, heat, stir, cool, bottle, clear, dye
String"..."
List[ "...", "..." ] (flower lists for cauldron dye)
Number10, 30
Comment# ...
Label nameafter label / goto
Slot nameafter unequip (weapon, head, …)

| Variable | @furnace, @mid | | Coord pair | (5, 18) or 512 128 after set @name |

Invalid lines can be marked with a subtle error underline on Save (optional v1).

---

10. Persistence & limits

  • Scripts stored per character in state DB (name, source text, flags, updatedAt).
  • Soft caps (suggested): 20 scripts / character, 200 lines / script, 4 KB source.
  • Offline script runtime state: program counter, targets, @ variables, loop stack, offlineUntil timestamp — rehydrated on server restart (§18.6).
  • Instruction budget: small per simulation tick (at most one blocking wait/path/gather/craft at a time; non-blocking lines burst with a low cap).

---

11. Authority & safety (implementation notes)

  • Interpreter runs only on the server.
  • Every gameplay effect goes through existing command handlers.
  • No filesystem, network, eval, or shared mutable globals across characters.
  • Name matching uses the same display names players see in tooltips / shops — exact, case-insensitive, never fuzzy.
  • Script controller and client controller: only one produces intents at a time; any manual gameplay intent stops the script.
  • Offline say / pigeon / bounty: same validation as players; add rate limits if abused.

---

12. Implementation plan (phased)

1. Data + UI shell — CRUD scripts, flags, editor with highlighting + live position readout, no execution. 2. Online runner — interpreter + run bar + stop; find / go (blocking, 2-chunk cap) / set / @ vars / wait / wait until / label / goto / stop / universal can. 3. Gather + gear + vitals — mine / chop / harvest / equip / unequip / drink / eat / if health|stamina. 4. Combat + shops + craft/alchemy — stations via craft (tailor dye flag); cauldron via step verbs + recipe-gated brew + cauldron dye [...]; per-player station state. 5. Loops + range + bag/target queries. 6. Bank, cheques, market, spells, pigeon, chat, bounty, spellbooks. 7. AFK auto-start — 30-minute idle. 8. Offline logout flow — modal, entity retention, 1-hour cap, re-login attach, error pigeon, death → full logout.

---

13. Open choices (resolve during implementation)

Resolved defaults (change only with a good reason):

TopicDecision
in range mob/ground radius15 tiles Chebyshev
AFK timer vs Scripts panelOpening the panel does not reset idle
Name matchingExact display name, case-insensitive; never fuzzy. Multiple exact matches → closest in the visible 3×3 chunk window
find / nearest searchPlayer chunk + 8 neighbours only (VISIBLE_CHUNK_RADIUS = 1) — what a real player would see
go max distanceDestination must be within 2 chunks or fail Too far away.
AFK idle duration30 minutes
wait until timeoutRequired form: wait until <cond> or <seconds> (max 300). Bare wait until without or N is a parse error so offline scripts cannot hang forever
cast fizzleNot a script error — line completes; use if / skill checks if you care
Quantity overflow (bank deposit "Tin ore" 999 with only 5)Deposit/withdraw/sell/buy as many as possible up to N; error only if zero moved
redeem cheque with several chequesRedeem the first written cheque in bag order
market cancel sell "Tin ore"Cancel the oldest open sell order for that item name
send pigeon to "Name"Payload = one selected bag item: prefer a written letter if present, else a cheque, else fail asking for a letter/cheque (send pigeon — Carry a letter or cheque to send.)
write letter "..."Writes onto a blank letter in the bag (fails if none); does not send
Editing a script while it runsSave applies next Run only; running copy is a snapshot
AFK start while a script already runsDo not start a second script
Offline logout while a script already runs onlineOffline flag continues that run (same PC); do not restart from line 1
Station inventoryMats never leave the bag until craft/brew succeeds; death/UI close cannot destroy them

Still soft:

  • Flower display names in cauldron dye must match item defs exactly (document in editor autocomplete later).

---

14. Out of scope

AreaReason
FollowNot needed for scripts
FriendsSocial; low AFK value
Barber / hairCosmetics
Inspect / social panelNot needed for AFK
Graphics settingsClient-only
World editorAdmin
respawn commandDeath always full-logout; player uses respawn UI on next login
User-defined functionsv1 stays line+label+@ vars only

Script steps should stay aligned with player UI actions; never add a verb that skips a check the human UI enforces (recipe paper for brew, random dye only for tailor, etc.).

Still fine to add later if play gains new intents

Inheritance claim, blank-cheque get/return — add a matching verb when useful.

When a new player-facing intent ships, add a matching script statement in the same feature commit.

---

15. Runtime edge cases (resolved in plan)

15.1 Targeting & names

  • find uses exact display names (case-insensitive). Ore nodes, trees, and dyed clothing must match tooltips character-for-character aside from case.
  • find / in range world searches only the visible 3×3 chunks (current + 8 surrounding). go may still path up to 2 chunks; farther → Too far away. Use @ coordinate waypoints for long trips.
  • After find, if the world changes (ore depleted, mob died, item picked up) before go/mine completes → fail that op with a clear reason (mine — Target is gone.).
  • Block vs ground vs bag: verbs decide the namespace (mine always uses block target; take uses ground; in range item uses bag).
  • @ vars holding targets re-resolve on use; gone → error. Coords always valid geometrically but still need path + 2-chunk proximity at go time.

15.2 Blocking ops interrupted

  • If the player is shoved, loses the gather, or combat cancels a path while go/mine/… is blocking → treat as script error for that line (not silent continue).
  • run on with 0 stamina: gait falls back to walk (same as player); not an error.
  • Full bag on take / gather loot / unequip → error for that line.

15.3 Combat & waits

  • wait until target dead or 60: success when target entity is despawned or HP ≤ 0; if the script never had a mob target → immediate error.
  • attack then wait until target dead while the mob flees out of chase range: wait hits timeout → error (script must re-find).
  • Town guards / retaliation killing the character → §7 death logout (clean stop, no Frederick letter).

15.4 Stations & cauldron

  • craft / brew / cauldron * require adjacency to the targeted station block like the UI.
  • Station / cauldron progress is per player — never tile-global. Concurrent users at the same block do not share or corrupt each other’s brew/craft.
  • Materials in station slots are never removed from the bag until a craft/brew succeeds; close UI / clear / death / script stop cannot destroy those items (§6.4).
  • brew with a recipe paper: if this player’s cauldron already has leftover steps, fail (brew — Cauldron is busy.) unless cleared. Prefer: scripts cauldron clear before brew (clear is safe — bag unchanged).
  • cauldron dye [...] fails if this player’s alchemy brew is mid-potion.
  • Unstable potion from wrong manual steps is success of bottling, not a script error (player can get unstable too) — only then are reserved mats consumed.

15.5 Mode switches

  • Disconnect while online script running without offline checkbox → stop script + normal logout (entity despawn).
  • Disconnect with offline already running → keep offline run.
  • Re-login onto offline script: restore run bar; PC unchanged.
  • Server restart: persist PC, targets (by tile + name + entityId if still valid), wait deadline, offlineUntil; invalid target after rehydrate → error letter.

15.6 Safety / abuse

  • Rate-limit offline say and pigeon sends (e.g. max 1 say / 10s, max 3 pigeons / hour) — same spirit as anti-spam, documented in implementation.
  • Cap concurrent offline-scripting characters per server (suggested 50 initially) to protect ChunkLoader cost; further logouts with offline checked fail with toast if at cap.

---

16. Known weaknesses & open problems

Issues that remain hard or only partly specified — fix in implementation or revisit the design:

1. Display-name fragility — renames in item/block defs break scripts (exact match). Mitigation: editor autocomplete from live defs; optional stable ids later. 2. Manual waypoints — long trips need author-maintained @ coords; wrong midpoints → Too far away. Mitigation: document hop spacing (≤ 2 chunks); later optional go via @a @b @c sugar. 3. Equal ore without bag-vs-bag compare — scripts approximate balance with thresholds (below 5), not true Tin < Copper. Mitigation: add if bag "Tin ore" below bag "Copper ore" later if needed. 4. Recipe paper ↔ brew "Name" matching — papers may store potion keys/hashes, not display strings. Must define a canonical match (displayName on the paper instance). If ambiguous, fail. 5. Pigeon cargo model — real UI may allow more than letter/cheque; script support may lag the UI until cargo selection is unified. 6. Marketplace disambiguation — multiple sell orders same item at different prices; “oldest” may surprise players. Acceptable v1; later allow market cancel sell "Tin ore" for 8. 7. Tailor random dye — non-deterministic scripts (harder to test). Intentional per design; document it. 8. goto vs loops — statically forbidding jump into/out of for/while needs a clear compiler pass; easy to get wrong with nested if. Must implement a block-stack checker at save/run. 9. Offline ChunkLoader cost — many offline miners keep regions hot; the concurrency cap helps but economy/world load can still spike. Needs live metrics after ship. 10. Partial command surface — any new play feature without a script verb creates parity drift (§14 reminder). Process discipline, not a technical guarantee. 11. Universal can cost — dry-running every action (esp. pathfinding) each while can tick must be cheap or cached. Must budget path checks. 12. AFK false positives — idle 30 minutes in a menu reading skills still starts AFK script. Acceptable; players can Stop or unmark AFK.

---

17. Feasibility & stability (assessment)

Feasibility: high for a phased build; medium-high for “full parity.” The architecture already assumes a script controller emitting the same intents (§18). Online runner + gather/go/wait until is straightforward. Offline + ChunkLoader + re-login + restart rehydrate is the hard part but is sketched in the design doc. Full verb parity (market, cauldron, pigeons) is mostly glue once the interpreter and blocking scheduler exist — estimate several milestones, not one dump.

Stability in use: good if timeouts and fail-loud rules hold; fragile if name-matching and waits are sloppy.

AreaOutlook
Online scriptsStable: same validation as players; run bar + Stop; manual intent cancels script
AFK auto-startStable with clear Stop; occasional surprise starts (§16.12)
Offline hourStable for gameplay; ops risk on region load — needs caps + metrics
Long wait untilStable only with mandatory or N timeouts
Economy botsWill exist (shops/market/gather); rate limits and normal game costs are the balance knobs
Player trustDeath→logout and Frederick letters are clear; station mats cannot be lost on death/UI close (§6.4)

Bottom line: the concept is implementable and can be sturdy for gather/bank/fight loops. Treat exact name matching, visible-only find (3×3 chunks), the 2-chunk go cap, mandatory wait timeouts, offline concurrency caps, per-player station state, non-committing station inventory, and recipe matching as non-negotiable for stability. Full “every button in the game” parity is achievable over phases, not day one — the plan is strongest when each new UI action ships with its script verb in the same commit.

Source
1# Player scripts (AFK / offline)
2
3**Status:** not implemented (design only)
4**Related:** `tile_mmo_server_technical_design_v0.6.md` §18 (controller abstraction, offline entity, sandbox rules)
5
6Scripts are a **sandboxed language** interpreted on the **server**. They never mutate world state directly; they emit the same player **intents** as a human client (`moveTo`, gather, craft, attack, shop, equip, …). The server validates every step.
7
8This document is the product + language spec for implementation.
9
10---
11
12## 1. Goals
13
14- Automate simple loops: gather → bank/craft → fight → recover.
15- Run **while online** (watch + stop bar), **while AFK** (idle 30+ minutes), or **while offline** (character stays in the world, max 1 hour).
16- Keep the language **small**, readable, and hard to misuse.
17- Fail loudly: toast (online) or pigeon letter (offline), with line + operation + reason.
18
19---
20
21## 2. Player UI
22
23### 2.1 Scripts button
24
25- HUD control **Scripts** opens the Scripts panel.
26- Panel lists the player’s saved scripts (name + badges for Offline / AFK flags).
27- Actions per script: **Edit**, **Delete**, **Run** (online).
28- **New script** creates an empty script and opens the editor.
29
30### 2.2 Script editor
31
32- Name field.
33- Text area with **syntax highlighting** (keywords, strings, numbers, comments, labels, `@` vars).
34- Flags (mutually independent; at most one script should be marked for each role — marking one clears that flag on others):
35 - **Run this while offline** — eligible on logout confirmation.
36 - **Run while AFK** — auto-starts after **30 minutes** with no player actions.
37- **Live world coordinates** at the **bottom** of the editor (player’s current tile, e.g. `Position: (5, 18)`), updating as the character moves while the panel is open — so authors can copy values into `set @waypoint (5, 18)`.
38- Optional: a small **Copy** control that copies `set @here (x, y)` (or just `(x, y)`) to the clipboard.
39- **Save** / **Cancel**.
40
41### 2.3 Online run bar
42
43When a script is running (started manually, AFK auto-start, or resumed after re-login onto an offline script):
44
45- Fixed bar at the **bottom** of the screen.
46- Shows: script name, **current line** (number + source text), **Stop**.
47- Manual player intents (move, attack, gather, …) **stop** the script (treat as cancel), except pure camera/UI (open bag, zoom, settings).
48
49### 2.4 Logout confirmation
50
51On logout while in the world:
52
531. Modal: **Are you sure you want to log out?**
54 - **No** — stay.
55 - **Yes** — log out.
56 - Checkbox (default **unchecked**): **Run offline script**
57 - Enabled only if the player has a script marked **Run this while offline**.
582. If the checkbox is checked, show an extra **red** line:
59 **Running a script means your character remains in the world and can still be attacked!**
603. Confirming with the checkbox checked starts/continues the offline script on that character (see §4).
61
62---
63
64## 3. Modes
65
66| Mode | How it starts | Character in world | Client |
67|------|---------------|--------------------|--------|
68| **Online** | Scripts panel → Run | Yes | Connected; run bar visible |
69| **AFK** | No gameplay intents for **30 minutes**, and an AFK-marked script exists | Yes | Still connected; run bar appears when script starts |
70| **Offline** | Logout with offline checkbox | Yes (no NetworkIdentity; keeps ChunkLoader) | Disconnected |
71
72**AFK timer:** reset on any **gameplay intent** sent by the player (move, attack, gather, craft, shop, equip, cast, pickup, talk, …). Opening UI / scrolling chat does not reset AFK if those are not intents; prefer resetting on any outbound play command for simplicity.
73
74**Offline duration:** max **1 hour** from offline-script start (or remaining time after restart rehydrate). Then: stop script, despawn character, persist as a normal logout.
75
76**Re-login during offline script:** attach the client to the existing entity; keep the script running; show the run bar so the player can Stop.
77
78---
79
80## 4. Errors
81
82### 4.1 Message shape
83
84Always:
85
86```text
87Line <n>: <operation> — <reason>
88```
89
90Example:
91
92```text
93Line 12: mine — No reachable iron ore nearby.
94```
95
96### 4.2 Online / AFK (client connected)
97
98- Stop the script.
99- Show a **persistent toast** (stays until the player dismisses it) with the error message.
100
101### 4.3 Offline (no client)
102
103- Stop the script.
104- Remove the character from the world (normal offline persist).
105- Queue a **pigeon letter**:
106 - Author display name: **Frederick**
107 - Role flavour: manager of Idle Gaming (author line / signature as other system letters do)
108 - Body:
109 `Unfortunately, your script encountered an error.`
110 then a blank line, then the error message from §4.1.
111
112---
113
114## 5. Language overview
115
116- Line-oriented, case-insensitive **keywords**.
117- One statement per line (blank lines and comments allowed).
118- Comments: `# ...` to end of line.
119- Strings: `"double quotes"` (names of blocks, mobs, items).
120- **Name matching is exact** (full display name), **case-insensitive**, never fuzzy / substring / “closest spelling”. `"Tin"` does **not** match `"Tin ore"`.
121- Numbers: integers (`10`, `100`).
122- Labels: `label name_here` — name is letters, digits, underscore.
123- **Variables:** `@name` (letters, digits, underscore after `@`). Set with `set` (§5.2). Hold a **target**, a **tile coordinate**, or (later) a number if needed.
124- Implicit targets (block / mob / ground) still exist alongside `@` vars.
125- No user-defined functions in v1.
126- Sandbox: **not** JavaScript; custom interpreter only (§18.7 design doc).
127
128### 5.1 Implicit targets
129
130The script keeps three optional targets (cleared when a new target of that kind is set, or on error/stop):
131
132| Target | Set by | Used by |
133|--------|--------|---------|
134| **Block** | `find block "..."` | `go`, `mine`, `chop`, `harvest`, `craft`, `in range block` |
135| **Mob** | `find mob "..."` | `go`, `attack`, `buy`, `sell`, `in range mob` |
136| **Ground** | `find ground "..."` | `go`, `take`, `use`, `in range ground` |
137
138`go` without a kind uses the **most recently set** target. Prefer explicit forms when ambiguous: `go block`, `go mob`, `go ground`.
139
140### 5.2 Variables (`@` + `set`)
141
142| Statement | Meaning |
143|-----------|---------|
144| `set @tree target` | Copy the **most recently set** implicit target (block / mob / ground) into `@tree`. |
145| `set @tree block` / `set @tree mob` / `set @tree ground` | Copy that specific implicit target kind into `@tree`. |
146| `set @furnace here` | Store the player’s **current tile** as coordinates in `@furnace`. |
147| `set @waypoint (5, 18)` | Store absolute tile coordinates `(5, 18)` in `@waypoint`. Preferred literal form. |
148| `set @furnace 512 128` | Same as `(512, 128)` — space-separated form also accepted. |
149| `go @furnace` | Path to the stored **coords** or to the stored **target** (same rules as `go`). |
150| `go block @tree` | If `@tree` holds a block target, path to it (explicit kind). |
151
152Rules:
153
154- Soft cap: **32** variables per running script.
155- Variables live in **runtime state** (persisted across offline rehydrate / re-login for that run). They are **not** saved with the script source.
156- Using an unset `@name` → error (`go — @furnace is not set.`).
157- Storing a target keeps enough identity to re-resolve (tile + kind + name / entityId). If the world object is gone when used → error (`go — Target is gone.`).
158
159Waypoints: because `go` only works within **2 chunks** (§6.2), authors manually chain coordinate variables for long trips (e.g. mine → mid → furnace).
160
161---
162
163## 6. Statements (v1)
164
165### 6.1 Targeting
166
167| Statement | Meaning |
168|-----------|---------|
169| `find block "Iron ore"` | Closest **reachable** block whose display name equals (case-insensitive). Search = **visible chunk neighbourhood only** (player’s chunk + **8** surrounding = Chebyshev chunk distance ≤ **1**, same as `VISIBLE_CHUNK_RADIUS`). Sets block target. Fails if none. |
170| `find mob "Shopkeeper"` | Closest living mob/NPC with exact name match in that same **3×3** chunk window. Sets mob target. Fails if none. |
171| `find ground "Log"` | Closest ground item with exact name match in that same **3×3** chunk window. Sets ground target. Fails if none. |
172
173“Closest” = Chebyshev tile distance, then path-reachable. Unreachable candidates are skipped. Multiple exact name matches → closest wins. Scripts must **not** see farther than a connected player would for entity/block discovery — never scan the full 2-chunk map ring.
174
175### 6.2 Movement
176
177| Statement | Meaning |
178|-----------|---------|
179| `go` | Path to the last set target (block / mob / ground). **Blocks** until arrived or fails. |
180| `go block` / `go mob` / `go ground` | Same, explicit target kind. |
181| `go @name` | Path to a variable (coords or stored target). |
182| `run on` / `run off` | Toggle run gait (same rules as player: needs stamina). |
183
184**Range hard rule:** the destination tile (target or `@` coords) must lie within **2 chunks** of the player (Chebyshev chunk distance ≤ 2; with `CHUNK_SIZE` 16 that is ≤ **32** tiles in chunk metric). Otherwise the op fails immediately:
185
186```text
187go — Too far away.
188```
189
190There is **no** automatic multi-hop pathing across the world. Use coordinate waypoints (`set @mid …` / `go @mid` / `go @furnace`) for longer trips.
191
192Arrival = standing on the tile (ground item / interactable) or adjacent where the game requires adjacency (stations, melee, gather nodes).
193
194### 6.3 Gathering & world interact
195
196| Statement | Meaning |
197|-----------|---------|
198| `mine` | Gather/mine the targeted **block** (ore boulder, etc.). **Blocks** until finished or fails. |
199| `chop` | Fell the targeted tree block. **Blocks** until finished. |
200| `harvest` | Pick/harvest the targeted plant/herb/flower/cotton block. **Blocks** until finished. |
201| `take` | Pick up the targeted **ground** item into the bag. |
202| `use` | Interact with the targeted **ground** item if it has a use (e.g. light a log). |
203
204Exact gather verb must match what the block supports; wrong verb → error (`chop — That is not a tree.`).
205
206### 6.4 Crafting stations & alchemy
207
208**Principle:** script steps mirror what a player does in the UI. No free shortcuts that skip materials, skill, adjacency, or recipe knowledge.
209
210**Station state hard rule:** cauldron / furnace / anvil / every craft station progress is **per player**, never shared on the tile. Many characters may use the “same” station block at once without interfering. Scripts and the UI obey the same rule — this applies to **all current and future** crafting stations.
211
212**Inventory hard rule (stations — script and player):** an item is **never committed** into a station. Slots in craft/brew UIs are a **view / reservation** over the bag only — materials do not leave the inventory when placed in a station slot. Even when it *looks* like something sits in the cauldron or bench, it is still in the bag. Therefore:
213
214- Closing the station UI, cancelling, `cauldron clear`, script stop/error, logout, or **death mid-craft / mid-brew** must leave the bag unchanged for those materials (or immediately show them back — there was nothing to return from the station itself).
215- Item loss due to closed UI or death while using a station is **impossible**.
216- Materials are consumed only when the craft/brew **successfully completes** (same moment the product is created), never earlier.
217
218This is a gameplay rule for humans and scripts alike (also `.cursor/rules/station-inventory.mdc`); the script layer must not invent a different consume-on-insert path.
219
220#### Crafting stations (furnace, anvil, woodworking, bench, spinning wheel, loom, tailor, leatherworking, …)
221
222| Statement | Meaning |
223|-----------|---------|
224| `craft "Bronze bar"` | At the targeted station **block**, start the same craft the player would (one product). **Blocks** until finished or fails (not at station, unknown recipe, missing mats, skill too low). Mats stay in the bag until success (§6.4). |
225| `craft "Cotton sweater" dye` | **Tailor only:** craft with dyeing on. Uses a **random** dye charge from the bag (no colour picker). **Fails** if dyeing is requested and the bag has no dye uses left. |
226| `craft "Cotton sweater"` | Tailor (or other station) **without** dyeing. |
227
228#### Alchemy cauldron — manual steps (1:1 with UI)
229
230Require adjacency to a cauldron block (find + go), same as opening the cauldron as a player. Brew progress is **this character’s** cauldron state only.
231
232| Statement | Meaning |
233|-----------|---------|
234| `cauldron insert "Thyme"` | Select/reserve that ingredient from the bag for the brew UI (does **not** remove it from inventory — §6.4 inventory hard rule). |
235| `cauldron heat` | Heat. |
236| `cauldron stir` | Stir. |
237| `cauldron cool` | Cool. |
238| `cauldron bottle` | Bottle into an empty glass bottle. **Blocks** until done. On success, reserved mats + bottle are consumed and the potion is granted. |
239| `cauldron clear` | Clear/abandon the brew UI selection; bag unchanged. |
240
241Step order and outcomes match humans: correct sequence → potion (with Alchemy skill roll); wrong sequence → unstable brew. Scripts get **no** easier success path.
242
243Example (same steps a player would click):
244
245```text
246find block "Cauldron"
247go block
248cauldron insert "Thyme"
249cauldron heat
250cauldron insert "Mint"
251cauldron stir
252cauldron bottle
253```
254
255#### Named `brew` — only with a recipe paper in the bag
256
257| Statement | Meaning |
258|-----------|---------|
259| `brew "Lesser health tonic"` | Allowed **only** if the inventory contains a **recipe paper** for that potion. Then run that paper’s recorded steps and bottle (skill checks as usual). Mats are reserved until success, then consumed with the bottle — never lost on interrupt. **Fails immediately** if no matching recipe is in the bag (`brew — No recipe for that in your bag.`). |
260
261Without a recipe item, authors must write the `cauldron …` steps themselves. `brew` is “follow this paper,” not free knowledge of the recipe.
262
263#### Dyes (flower list, same as dye tab)
264
265| Statement | Meaning |
266|-----------|---------|
267| `cauldron dye ["White flower", "Yellow flower", "Yellow flower"]` | Make dye from that multiset of flowers (here: 1 white + 2 yellow). List order = insert order; repeat a name for more of the same flower. Flowers are reserved from the bag until the dye brew completes successfully; colour/yield rules match the normal dye UI. Fails if flowers missing, not at cauldron, or bottling not possible. |
268
269List syntax: `[ "...", "..." ]`. Exact flower display names only.
270
271### 6.5 Dry-run: `can` before any action
272
273`can` prefixes **any action statement** and returns whether that exact line would succeed **right now**, without mutating world state (no path start, no craft start, no item move).
274
275Forms:
276
277- Standalone is not used — always in conditions: `if can …` / `while can …` / `wait until can … or N`
278- Syntax: `can` + the same tokens as the action line (including args and `@` vars)
279
280Examples:
281
282| Condition | True when… |
283|-----------|------------|
284| `can craft "Bronze bar"` | At station, recipe known, mats + skill OK |
285| `can mine` | Block target set, in gather range, tool/skill OK, node still there |
286| `can go` / `can go @furnace` | Destination set/resolvable, **≤ 2 chunks**, path exists |
287| `can bank deposit "Tin ore" 20` | At bank, at least 1 Tin ore movable (qty overflow rules still apply) |
288| `can buy "Feather" 10` | Shop mob targeted, in range, stock + coins OK |
289| `can cast "Spark" on mob` | Spell known, valid target, not on CD, in approach range or pathable within 2 chunks |
290| `can brew "Lesser health tonic"` | Matching recipe paper in bag, at cauldron, mats OK |
291| `can find block "Tin ore"` | Exact name exists in the visible **3×3** chunk window (and reachable if `find` requires it) |
292| `can cauldron bottle` | Per-player brew ready to bottle + empty bottle |
293
294**Not** actions (no `can`): pure control (`label`, `goto`, `if`, `end`, `for`, `while`, `wait`, `stop`, `set`, `run on`/`off`). `find` **is** an action for `can find block "Tin ore"` (true if such a find would succeed).
295
296Implementation: share the same validation path as the real command; skip the mutate/apply step.
297
298### 6.6 Combat & shops
299
300| Statement | Meaning |
301|-----------|---------|
302| `attack` | Attack the targeted mob (player Attack intent). Does **not** wait for the kill by itself — use `wait until target dead or 60` (§6.13). |
303| `stop attack` | Cancel the current attack engage (player cancel-attack). |
304| `buy "Feather" 10` | Buy quantity from targeted shop mob. Fails if no shop, not in range, can’t afford, or not stocked. |
305| `sell "Soft leather" 5` | Sell quantity to targeted shop mob (if it buys). |
306
307**Follow** is intentionally **not** supported.
308
309### 6.7 Inventory, gear & vitals
310
311| Statement | Meaning |
312|-----------|---------|
313| `equip "Bronze pickaxe"` | Equip a matching item from the bag into its proper slot. Fails if missing or not equippable. |
314| `unequip weapon` | Clear that equipment **slot** into the bag. Slots: `head`, `chest`, `legs`, `boots`, `weapon`, `offhand` (same as game). **Fails if the bag has no free space.** |
315| `drink "Lesser health tonic"` | Drink a matching consumable from the bag. |
316| `eat "Apple"` | Eat a matching food from the bag. |
317| `drop "Tin ore" 5` | Drop quantity from the bag onto the ground. |
318| `read "Spark spellbook"` | Read a spellbook from the bag to learn its spell (same as player). Fails if missing, already known, or requirements not met. |
319| `if health below 30` … | See control flow. |
320| `if stamina below 5` … | See control flow. |
321
322### 6.8 Range checks & queries
323
324| Statement | Meaning |
325|-----------|---------|
326| `if in range block "Furnace"` | True if a matching block exists in the **visible 3×3** chunk window (same as `find`) and is within interaction/path rules. |
327| `if in range mob "Deer"` | True if a matching living mob is within **15 tiles** Chebyshev **and** inside the visible 3×3 chunk window. |
328| `if in range ground "Bones"` | True if a matching ground item is within **15 tiles** **and** inside the visible 3×3 chunk window. |
329| `if in range item "Bronze bar"` | True if the bag contains that item (quantity ≥ 1). |
330| `if bag has "Tin ore" at least 10` | Bag quantity check. |
331| `if bag has "Tin ore" below 10` | Bag quantity check. |
332| `if target health below 20` | Targeted **mob** current HP below N. Fails the condition (false) if no mob target; does not hard-error. |
333| `if target dead` | Targeted mob is gone or at 0 HP. |
334
335### 6.9 Bank, cheques, market, social economy
336
337Requires being at / having path-interacted with the right block where the game requires it (bank counter, bounty office, marketplace).
338
339| Statement | Meaning |
340|-----------|---------|
341| `bank deposit "Tin ore" 20` | Move quantity from bag → vault. |
342| `bank withdraw "Tin ore" 20` | Move quantity from vault → bag. |
343| `write cheque "Tin ore" 50` | Write a cheque reserving that item+qty from the **bank (vault)**. Fails if the vault lacks enough. |
344| `redeem cheque` | Redeem a written cheque from the bag at a bank (goods → vault), same as player. |
345| `market sell "Tin ore" 10 for 8` | Place sell order (qty, min unit price). Escrows goods + listing fee like the UI. |
346| `market buy "Tin ore" 10 for 12` | Place buy order (qty, max unit price). Escrows coins like the UI. |
347| `market cancel sell` / `market cancel buy` | Cancel the character’s open order of that side (or nearest matching — prefer cancelling by item name if multiple: `market cancel sell "Tin ore"`). |
348| `raise bounty on "Ada Worker" 100` | Raise bounty (near bounty office, pays from bag). |
349| `send pigeon to bank` | Courier cargo to own bank (same rules as UI). |
350| `send pigeon to "Ada Worker"` | Courier to that character; payload prefers a written letter, else a cheque (§13). |
351| `write letter "..."` | Write body onto a **blank letter** in the bag (fails if none); does not send. |
352| `say "hello"` | Local chat say. |
353
354### 6.10 Spells
355
356| Statement | Meaning |
357|-----------|---------|
358| `cast "Light"` | Cast on the targeted **block** tile (tile-target spells). Approaches into range if needed (same as player cast). **Blocks** until cast attempt resolves; **fizzle is not an error** (line completes). Approach still obeys the **2-chunk** `go` limit. |
359| `cast "Spark" on mob` | Cast entity-target spell on the mob target. |
360| `cast "Light" on block` | Explicit tile target = targeted block’s tile. |
361
362Fails if unknown spell, not learned, on cooldown, out of range with no path, or wrong target kind.
363
364### 6.11 Labels & jumps
365
366| Statement | Meaning |
367|-----------|---------|
368| `label camp` | Declare label `camp`. |
369| `goto camp` | Jump to that label. |
370
371Forward and backward jumps allowed. Jumping into/out of loops is **disallowed** (error if attempted).
372
373### 6.12 Control flow
374
375```text
376if health below 30
377 goto heal
378end
379
380if stamina below 5
381 run off
382end
383
384if can craft "Bronze bar"
385 craft "Bronze bar"
386end
387
388if can go @furnace
389 go @furnace
390end
391
392if in range item "Bronze pickaxe"
393 equip "Bronze pickaxe"
394end
395
396for 10
397 find block "Tin ore"
398 go block
399 mine
400end
401
402while in range mob "Rat"
403 find mob "Rat"
404 go mob
405 attack
406 wait until target dead or 60
407end
408```
409
410Rules:
411
412- Blocks end with `end`.
413- `if` body runs when the condition is true; no `else` (use a second `if` / `goto`).
414- `for N` — repeat body **N** times (N ≥ 1, max **1000**).
415- `while <condition>` — repeat while condition true; **max 1000** iterations per `while` then error (`while — Too many repeats.`).
416- Conditions:
417 `health below N` · `stamina below N` · `can <action…>` (§6.5) · `in range block|mob|ground|item "..."` · `bag has "..." at least|below N` · `target health below N` · `target dead`
418
419### 6.13 Waiting (`wait` / `wait until`)
420
421| Statement | Meaning |
422|-----------|---------|
423| `wait 2` | Pause **2 seconds** (server time). Max **60** per wait. |
424| `wait until arrived or 30` | Block until the current path finishes (usually redundant after `go`, which already waits). |
425| `wait until gathered or 120` | Block until the active mine/chop/harvest completes. |
426| `wait until crafted or 120` | Block until the active station craft / `brew` / `cauldron bottle` completes. |
427| `wait until target dead or 60` | Block until the mob target is dead or despawned. Fails if no mob target. |
428| `wait until health at least 50 or 120` | Block until own HP ≥ N. |
429| `wait until stamina at least 5 or 60` | Block until stamina ≥ N. |
430| `wait until in range item "Bronze bar" or 60` | Block until bag has that item. |
431| `wait until in range mob "Deer" or 30` | Block until such a mob is in range. |
432| `wait until bag has "Tin ore" at least 10 or 300` | Block until quantity met. |
433| `wait until can craft "Bronze bar" or 60` | Block until that dry-run would succeed. |
434| `wait until can go @furnace or 60` | Block until the destination is ≤ 2 chunks and pathable (e.g. after walking a midpoint waypoint). |
435
436**Principle:** every boolean condition usable in `if` / `while` is also valid after `wait until`. Extend this set whenever new conditions ship. `can <action>` is valid anywhere a condition is.
437
438**Timeout is mandatory:** every `wait until` must end with `or <seconds>` (1–300). Bare `wait until …` without `or N` is a **parse error**. On timeout → script error (`wait until — Timed out.`).
439
440`go` / gather / `craft` / `brew` already **block** like a built-in wait for their own completion (they have natural end conditions; no separate `or N` on those verbs).
441
442### 6.14 Utility
443
444| Statement | Meaning |
445|-----------|---------|
446| `stop` | End the script successfully (no error letter). |
447
448---
449
450## 7. Death while a script is running
451
452If the character **dies** for any reason while a script is active (online, AFK, or offline):
453
4541. **Stop** the script immediately (not an “error letter” unless death was caused mid-op failure — death itself is a clean stop).
4552. Cancel any in-progress station/cauldron UI state for that player; **bag contents for reserved station mats are unchanged** (§6.4 inventory hard rule).
4563. **Fully log the instance out** of the world (despawn entity, persist dead flag / position as normal death logout).
4574. When the player next connects, they see the normal **respawn** screen — no auto-respawn from scripts.
458
459There is **no** `respawn` script command.
460
461---
462
463## 8. Example scripts
464
465### 8.1 Tin loop with panic flee
466
467```text
468# Tin loop with panic flee
469label start
470equip "Bronze pickaxe"
471run on
472
473for 20
474 if health below 25
475 goto flee
476 end
477 find block "Tin ore"
478 go block
479 mine
480 if in range ground "Tin ore"
481 find ground "Tin ore"
482 go ground
483 take
484 end
485end
486stop
487
488label flee
489run on
490drink "Lesser health tonic"
491stop attack
492find block "Bank"
493go block
494bank deposit "Tin ore" 999
495stop
496```
497
498### 8.2 Bronze mining bot (equal tin/copper → smelt → bank)
499
500Furnace is ~4 chunks from the mine (beyond the 2-chunk `go` limit), so the author pre-saves waypoints by standing on tiles and using `set @… here`, or by writing coordinates. Bank is near the furnace here; bronze goes to the vault via `bank deposit` (or `send pigeon to bank` if preferred).
501
502Smelting consumes tin and copper in pairs, so the loop mines whichever ore is missing first — stock stays balanced.
503
504```text
505# Waypoints (edit coords to your world; mid is ~2 chunks from mine toward furnace)
506# Tip: open the script editor and read Position: (x, y) at the bottom while standing on each tile
507set @mine (800, 400)
508set @mid (800, 432)
509set @furnace (800, 464)
510set @bank (804, 464)
511
512equip "Bronze pickaxe"
513run on
514
515label loop
516# Equal ores: mine whichever is missing; smelting consumes pairs so stock stays balanced
517if bag has "Tin ore" below 1
518 goto mine_tin
519end
520if bag has "Copper ore" below 1
521 goto mine_copper
522end
523goto smelt
524
525label mine_tin
526go @mid
527go @mine
528find block "Tin ore"
529if can go block
530 go block
531 mine
532end
533if in range ground "Tin ore"
534 find ground "Tin ore"
535 go ground
536 take
537end
538goto loop
539
540label mine_copper
541go @mid
542go @mine
543find block "Copper ore"
544if can go block
545 go block
546 mine
547end
548if in range ground "Copper ore"
549 find ground "Copper ore"
550 go ground
551 take
552end
553goto loop
554
555label smelt
556go @mid
557go @furnace
558find block "Furnace"
559go block
560while can craft "Bronze bar"
561 craft "Bronze bar"
562end
563go @bank
564find block "Bank"
565go block
566bank deposit "Bronze bar" 999
567goto loop
568```
569
570---
571
572## 9. Syntax highlighting (editor)
573
574Highlight at least:
575
576| Class | Examples |
577|-------|----------|
578| Keyword | `find`, `go`, `mine`, `chop`, `harvest`, `craft`, `brew`, `cauldron`, `attack`, `buy`, `sell`, `equip`, `unequip`, `drink`, `eat`, `drop`, `read`, `cast`, `bank`, `market`, `write`, `redeem`, `raise`, `send`, `say`, `label`, `goto`, `if`, `end`, `for`, `while`, `wait`, `stop`, `run`, `take`, `use`, `can`, `set` |
579| Subkeyword | `block`, `mob`, `ground`, `item`, `health`, `stamina`, `below`, `at`, `least`, `in`, `range`, `on`, `off`, `until`, `or`, `arrived`, `gathered`, `crafted`, `target`, `dead`, `here`, `deposit`, `withdraw`, `cheque`, `pigeon`, `bounty`, `sell`, `buy`, `cancel`, `insert`, `heat`, `stir`, `cool`, `bottle`, `clear`, `dye` |
580| String | `"..."` |
581| List | `[ "...", "..." ]` (flower lists for `cauldron dye`) |
582| Number | `10`, `30` |
583| Comment | `# ...` |
584| Label name | after `label` / `goto` |
585| Slot name | after `unequip` (`weapon`, `head`, …) |
586
587| Variable | `@furnace`, `@mid` |
588| Coord pair | `(5, 18)` or `512 128` after `set @name` |
589
590Invalid lines can be marked with a subtle error underline on Save (optional v1).
591
592---
593
594## 10. Persistence & limits
595
596- Scripts stored per character in state DB (name, source text, flags, updatedAt).
597- Soft caps (suggested): **20** scripts / character, **200** lines / script, **4 KB** source.
598- Offline script runtime state: program counter, targets, `@` variables, loop stack, `offlineUntil` timestamp — rehydrated on server restart (§18.6).
599- Instruction budget: small per simulation tick (at most one **blocking** wait/path/gather/craft at a time; non-blocking lines burst with a low cap).
600
601---
602
603## 11. Authority & safety (implementation notes)
604
605- Interpreter runs only on the server.
606- Every gameplay effect goes through existing command handlers.
607- No filesystem, network, `eval`, or shared mutable globals across characters.
608- Name matching uses the same display names players see in tooltips / shops — **exact**, case-insensitive, never fuzzy.
609- Script controller and client controller: only one produces intents at a time; **any manual gameplay intent stops** the script.
610- Offline `say` / pigeon / bounty: same validation as players; add rate limits if abused.
611
612---
613
614## 12. Implementation plan (phased)
615
6161. **Data + UI shell** — CRUD scripts, flags, editor with highlighting + **live position readout**, no execution.
6172. **Online runner** — interpreter + run bar + stop; `find` / `go` (blocking, **2-chunk** cap) / `set` / `@` vars / `wait` / `wait until` / `label` / `goto` / `stop` / universal `can`.
6183. **Gather + gear + vitals** — `mine` / `chop` / `harvest` / `equip` / `unequip` / `drink` / `eat` / `if health|stamina`.
6194. **Combat + shops + craft/alchemy** — stations via `craft` (tailor `dye` flag); cauldron via step verbs + recipe-gated `brew` + `cauldron dye [...]`; per-player station state.
6205. **Loops + range + bag/target queries**.
6216. **Bank, cheques, market, spells, pigeon, chat, bounty, spellbooks**.
6227. **AFK auto-start** — 30-minute idle.
6238. **Offline logout flow** — modal, entity retention, 1-hour cap, re-login attach, error pigeon, **death → full logout**.
624
625---
626
627## 13. Open choices (resolve during implementation)
628
629Resolved defaults (change only with a good reason):
630
631| Topic | Decision |
632|-------|----------|
633| `in range mob/ground` radius | **15** tiles Chebyshev |
634| AFK timer vs Scripts panel | Opening the panel does **not** reset idle |
635| Name matching | **Exact** display name, case-insensitive; never fuzzy. Multiple exact matches → **closest** in the visible **3×3** chunk window |
636| `find` / nearest search | Player chunk + 8 neighbours only (`VISIBLE_CHUNK_RADIUS` = 1) — what a real player would see |
637| `go` max distance | Destination must be within **2 chunks** or fail `Too far away.` |
638| AFK idle duration | **30 minutes** |
639| `wait until` timeout | **Required** form: `wait until <cond> or <seconds>` (max 300). Bare `wait until` without `or N` is a **parse error** so offline scripts cannot hang forever |
640| `cast` fizzle | **Not** a script error — line completes; use `if` / skill checks if you care |
641| Quantity overflow (`bank deposit "Tin ore" 999` with only 5) | Deposit/withdraw/sell/buy **as many as possible up to N**; error only if **zero** moved |
642| `redeem cheque` with several cheques | Redeem the **first** written cheque in bag order |
643| `market cancel sell "Tin ore"` | Cancel the **oldest** open sell order for that item name |
644| `send pigeon to "Name"` | Payload = **one** selected bag item: prefer a written **letter** if present, else a **cheque**, else fail asking for a letter/cheque (`send pigeon — Carry a letter or cheque to send.`) |
645| `write letter "..."` | Writes onto a **blank letter** in the bag (fails if none); does not send |
646| Editing a script while it runs | Save applies next **Run** only; running copy is a snapshot |
647| AFK start while a script already runs | Do **not** start a second script |
648| Offline logout while a script already runs online | Offline flag continues **that** run (same PC); do not restart from line 1 |
649| Station inventory | Mats **never leave** the bag until craft/brew **succeeds**; death/UI close cannot destroy them |
650
651Still soft:
652
653- Flower **display names** in `cauldron dye` must match item defs exactly (document in editor autocomplete later).
654
655---
656
657## 14. Out of scope
658
659| Area | Reason |
660|------|--------|
661| **Follow** | Not needed for scripts |
662| **Friends** | Social; low AFK value |
663| **Barber / hair** | Cosmetics |
664| **Inspect / social panel** | Not needed for AFK |
665| **Graphics settings** | Client-only |
666| **World editor** | Admin |
667| **`respawn` command** | Death always full-logout; player uses respawn UI on next login |
668| **User-defined functions** | v1 stays line+label+`@` vars only |
669
670Script steps should stay aligned with player UI actions; never add a verb that skips a check the human UI enforces (recipe paper for `brew`, random dye only for tailor, etc.).
671
672### Still fine to add later if play gains new intents
673
674Inheritance claim, blank-cheque get/return — add a matching verb when useful.
675
676When a new player-facing intent ships, add a matching script statement in the same feature commit.
677
678---
679
680## 15. Runtime edge cases (resolved in plan)
681
682### 15.1 Targeting & names
683
684- `find` uses **exact** display names (case-insensitive). Ore nodes, trees, and dyed clothing must match tooltips character-for-character aside from case.
685- `find` / `in range` world searches only the **visible 3×3** chunks (current + 8 surrounding). `go` may still path up to **2 chunks**; farther → `Too far away.` Use `@` coordinate waypoints for long trips.
686- After `find`, if the world changes (ore depleted, mob died, item picked up) before `go`/`mine` completes → **fail** that op with a clear reason (`mine — Target is gone.`).
687- Block vs ground vs bag: verbs decide the namespace (`mine` always uses **block** target; `take` uses **ground**; `in range item` uses bag).
688- `@` vars holding targets re-resolve on use; gone → error. Coords always valid geometrically but still need path + 2-chunk proximity at `go` time.
689
690### 15.2 Blocking ops interrupted
691
692- If the player is **shoved**, loses the gather, or combat cancels a path while `go`/`mine`/… is blocking → treat as **script error** for that line (not silent continue).
693- `run on` with 0 stamina: gait falls back to walk (same as player); **not** an error.
694- Full bag on `take` / gather loot / `unequip` → error for that line.
695
696### 15.3 Combat & waits
697
698- `wait until target dead or 60`: success when target entity is despawned or HP ≤ 0; if the script never had a mob target → immediate error.
699- `attack` then `wait until target dead` while the mob flees out of chase range: wait hits **timeout** → error (script must re-`find`).
700- Town guards / retaliation killing the character → §7 death logout (clean stop, no Frederick letter).
701
702### 15.4 Stations & cauldron
703
704- `craft` / `brew` / `cauldron *` require adjacency to the targeted station block like the UI.
705- Station / cauldron progress is **per player** — never tile-global. Concurrent users at the same block do not share or corrupt each other’s brew/craft.
706- Materials in station slots are **never removed from the bag** until a craft/brew **succeeds**; close UI / clear / death / script stop cannot destroy those items (§6.4).
707- `brew` with a recipe paper: if **this player’s** cauldron already has leftover steps, **fail** (`brew — Cauldron is busy.`) unless cleared. Prefer: scripts `cauldron clear` before `brew` (clear is safe — bag unchanged).
708- `cauldron dye [...]` fails if **this player’s** alchemy brew is mid-potion.
709- Unstable potion from wrong manual steps is **success of bottling**, not a script error (player can get unstable too) — only then are reserved mats consumed.
710
711### 15.5 Mode switches
712
713- Disconnect while online script running **without** offline checkbox → stop script + normal logout (entity despawn).
714- Disconnect **with** offline already running → keep offline run.
715- Re-login onto offline script: restore run bar; PC unchanged.
716- Server restart: persist PC, targets (by tile + name + entityId if still valid), wait deadline, `offlineUntil`; invalid target after rehydrate → error letter.
717
718### 15.6 Safety / abuse
719
720- Rate-limit offline `say` and pigeon sends (e.g. max 1 say / 10s, max 3 pigeons / hour) — same spirit as anti-spam, documented in implementation.
721- Cap concurrent **offline-scripting** characters per server (suggested **50** initially) to protect ChunkLoader cost; further logouts with offline checked fail with toast if at cap.
722
723---
724
725## 16. Known weaknesses & open problems
726
727Issues that remain hard or only partly specified — fix in implementation or revisit the design:
728
7291. **Display-name fragility** — renames in item/block defs break scripts (exact match). *Mitigation:* editor autocomplete from live defs; optional stable ids later.
7302. **Manual waypoints** — long trips need author-maintained `@` coords; wrong midpoints → `Too far away.` *Mitigation:* document hop spacing (≤ 2 chunks); later optional `go via @a @b @c` sugar.
7313. **Equal ore without bag-vs-bag compare** — scripts approximate balance with thresholds (`below 5`), not true `Tin < Copper`. *Mitigation:* add `if bag "Tin ore" below bag "Copper ore"` later if needed.
7324. **Recipe paper ↔ `brew "Name"` matching** — papers may store potion keys/hashes, not display strings. *Must* define a canonical match (displayName on the paper instance). If ambiguous, fail.
7335. **Pigeon cargo model** — real UI may allow more than letter/cheque; script support may lag the UI until cargo selection is unified.
7346. **Marketplace disambiguation** — multiple sell orders same item at different prices; “oldest” may surprise players. Acceptable v1; later allow `market cancel sell "Tin ore" for 8`.
7357. **Tailor random dye** — non-deterministic scripts (harder to test). Intentional per design; document it.
7368. **`goto` vs loops** — statically forbidding jump into/`out of` `for`/`while` needs a clear compiler pass; easy to get wrong with nested `if`. *Must* implement a block-stack checker at save/run.
7379. **Offline ChunkLoader cost** — many offline miners keep regions hot; the concurrency cap helps but economy/world load can still spike. Needs live metrics after ship.
73810. **Partial command surface** — any new play feature without a script verb creates parity drift (§14 reminder). Process discipline, not a technical guarantee.
73911. **Universal `can` cost** — dry-running every action (esp. pathfinding) each `while can` tick must be cheap or cached. *Must* budget path checks.
74012. **AFK false positives** — idle 30 minutes in a menu reading skills still starts AFK script. Acceptable; players can Stop or unmark AFK.
741
742---
743
744## 17. Feasibility & stability (assessment)
745
746**Feasibility: high for a phased build; medium-high for “full parity.”**
747The architecture already assumes a script controller emitting the same intents (§18). Online runner + gather/`go`/`wait until` is straightforward. Offline + ChunkLoader + re-login + restart rehydrate is the hard part but is sketched in the design doc. Full verb parity (market, cauldron, pigeons) is mostly glue once the interpreter and blocking scheduler exist — estimate **several milestones**, not one dump.
748
749**Stability in use: good if timeouts and fail-loud rules hold; fragile if name-matching and waits are sloppy.**
750
751| Area | Outlook |
752|------|---------|
753| Online scripts | Stable: same validation as players; run bar + Stop; manual intent cancels script |
754| AFK auto-start | Stable with clear Stop; occasional surprise starts (§16.12) |
755| Offline hour | Stable for gameplay; **ops risk** on region load — needs caps + metrics |
756| Long `wait until` | Stable **only** with mandatory `or N` timeouts |
757| Economy bots | Will exist (shops/market/gather); rate limits and normal game costs are the balance knobs |
758| Player trust | Death→logout and Frederick letters are clear; station mats cannot be lost on death/UI close (§6.4) |
759
760**Bottom line:** the concept is **implementable and can be sturdy** for gather/bank/fight loops. Treat **exact** name matching, **visible-only** `find` (3×3 chunks), the **2-chunk** `go` cap, mandatory wait timeouts, offline concurrency caps, per-player station state, **non-committing station inventory**, and recipe matching as **non-negotiable** for stability. Full “every button in the game” parity is **achievable over phases**, not day one — the plan is strongest when each new UI action ships with its script verb in the same commit.