osrlib 2.5.1__tar.gz → 2.6.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. osrlib-2.6.0/PKG-INFO +197 -0
  2. osrlib-2.6.0/README.md +172 -0
  3. {osrlib-2.5.1 → osrlib-2.6.0}/pyproject.toml +2 -2
  4. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/__init__.py +10 -6
  5. osrlib-2.6.0/src/osrlib/crawl/_feature_handles.py +169 -0
  6. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/crawl/_hauling.py +11 -9
  7. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/crawl/_movement.py +3 -4
  8. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/crawl/_party_location.py +14 -0
  9. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/crawl/_search.py +16 -10
  10. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/crawl/_treasure.py +29 -4
  11. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/crawl/adventure.py +62 -0
  12. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/crawl/battle.py +17 -9
  13. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/crawl/commands.py +38 -30
  14. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/crawl/dungeon.py +19 -8
  15. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/crawl/session.py +42 -9
  16. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/crawl/views.py +272 -20
  17. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/persistence.py +33 -10
  18. osrlib-2.5.1/PKG-INFO +0 -147
  19. osrlib-2.5.1/README.md +0 -122
  20. {osrlib-2.5.1 → osrlib-2.6.0}/LICENSE +0 -0
  21. {osrlib-2.5.1 → osrlib-2.6.0}/LICENSE-OGL.md +0 -0
  22. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/core/__init__.py +0 -0
  23. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/core/_descriptions.py +0 -0
  24. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/core/abilities.py +0 -0
  25. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/core/alignment.py +0 -0
  26. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/core/character.py +0 -0
  27. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/core/classes.py +0 -0
  28. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/core/clock.py +0 -0
  29. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/core/combat.py +0 -0
  30. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/core/creature.py +0 -0
  31. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/core/dice.py +0 -0
  32. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/core/effects.py +0 -0
  33. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/core/events.py +0 -0
  34. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/core/frozen.py +0 -0
  35. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/core/items.py +0 -0
  36. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/core/monsters.py +0 -0
  37. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/core/npc.py +0 -0
  38. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/core/rng.py +0 -0
  39. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/core/ruleset.py +0 -0
  40. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/core/spells.py +0 -0
  41. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/core/tables.py +0 -0
  42. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/core/treasure.py +0 -0
  43. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/core/validation.py +0 -0
  44. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/crawl/__init__.py +0 -0
  45. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/crawl/_arrival.py +0 -0
  46. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/crawl/_doors.py +0 -0
  47. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/crawl/_gating.py +0 -0
  48. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/crawl/_items.py +0 -0
  49. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/crawl/_light.py +0 -0
  50. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/crawl/_magic_items.py +0 -0
  51. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/crawl/_odometer.py +0 -0
  52. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/crawl/_party_members.py +0 -0
  53. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/crawl/_spells.py +0 -0
  54. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/crawl/_town.py +0 -0
  55. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/crawl/content_pack.py +0 -0
  56. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/crawl/encounter.py +0 -0
  57. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/crawl/events.py +0 -0
  58. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/crawl/exploration.py +0 -0
  59. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/crawl/gates.py +0 -0
  60. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/crawl/interpreter.py +0 -0
  61. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/crawl/narrative.py +0 -0
  62. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/crawl/party.py +0 -0
  63. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/crawl/quests.py +0 -0
  64. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/crawl/stocking.py +0 -0
  65. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/crawl/triggers.py +0 -0
  66. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/data/LICENSE-OGL.md +0 -0
  67. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/data/__init__.py +0 -0
  68. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/data/abilities.json +0 -0
  69. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/data/classes.json +0 -0
  70. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/data/combat_tables.json +0 -0
  71. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/data/encounter_tables.json +0 -0
  72. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/data/equipment.json +0 -0
  73. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/data/languages.json +0 -0
  74. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/data/magic_items.json +0 -0
  75. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/data/monsters.json +0 -0
  76. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/data/spells.json +0 -0
  77. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/data/treasure.json +0 -0
  78. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/errors.py +0 -0
  79. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/messages.py +0 -0
  80. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/py.typed +0 -0
  81. {osrlib-2.5.1 → osrlib-2.6.0}/src/osrlib/versioning.py +0 -0
osrlib-2.6.0/PKG-INFO ADDED
@@ -0,0 +1,197 @@
1
+ Metadata-Version: 2.4
2
+ Name: osrlib
3
+ Version: 2.6.0
4
+ Summary: B/X (1981 Basic/Expert) tabletop RPG rules engine for turn-based dungeon crawlers
5
+ Keywords: basic-expert,bx,dungeon-crawler,game-engine,osr,rpg,srd,ttrpg
6
+ Author: Marsh Macy
7
+ License-Expression: MIT AND LicenseRef-OGL-1.0a
8
+ License-File: LICENSE
9
+ License-File: LICENSE-OGL.md
10
+ Classifier: Development Status :: 5 - Production/Stable
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.14
15
+ Classifier: Topic :: Games/Entertainment :: Role-Playing
16
+ Classifier: Topic :: Software Development :: Libraries
17
+ Classifier: Typing :: Typed
18
+ Requires-Dist: pydantic>=2
19
+ Requires-Python: >=3.14
20
+ Project-URL: Changelog, https://github.com/mmacy/osrlib-python/blob/main/CHANGELOG.md
21
+ Project-URL: Documentation, https://mmacy.github.io/osrlib-python/
22
+ Project-URL: Issues, https://github.com/mmacy/osrlib-python/issues
23
+ Project-URL: Repository, https://github.com/mmacy/osrlib-python
24
+ Description-Content-Type: text/markdown
25
+
26
+ # osrlib
27
+
28
+ osrlib is a Python library that implements the classic 1981 B/X (Basic/Expert) fantasy adventure game rules for turn-based, grid-based dungeon crawlers in the style of the original Bard's Tale. The rules come from the [Old-School Essentials System Reference Document](https://oldschoolessentials.necroticgnome.com/srd/) (SRD), an Open Game Content restatement of the B/X rules.
29
+
30
+ osrlib has no UI, networking, or save-file I/O: you pass typed commands into an in-memory session, osrlib resolves the rules and updates game state, and your application handles rendering, player input, persistence, and transport. Every random roll draws from a named stream derived from a master seed, so running the same commands from the same starting state and seed under the same engine version produces the same game state and events every time.
31
+
32
+ osrlib separates standalone rules in `osrlib.core` (such as rolling characters, resolving attacks, or rolling treasure) from stateful dungeon-crawl sessions in `osrlib.crawl`, with shared top-level modules for compiled SRD data, message formatting, and persistence. In `osrlib.crawl`, you can bundle custom monsters, items, and spells with an adventure, put conditions on doors and stairs (which osrlib calls gates), and define quests and scripted reactions to play events (triggers).
33
+
34
+ You can use osrlib in several ways:
35
+
36
+ - **Web or mobile backends**: Serve game sessions over HTTP (for example, with FastAPI) using the generated Pydantic JSON Schemas for commands and events.
37
+ - **Terminal or desktop games**: Drive `GameSession` synchronously in process from a local interface.
38
+ - **LLM referees and narrators**: Pass structured events to a language model and execute the typed commands it returns.
39
+ - **Scripts and simulations**: Call functions in `osrlib.core` directly for character generation, combat statistics, or content validation without starting a session (see [Determinism, saves, and replay](#determinism-saves-and-replay) for a standalone dice roll and [Using the rules without a session](https://mmacy.github.io/osrlib-python/guides/rules-without-a-session/)).
40
+
41
+ ## Installation
42
+
43
+ osrlib requires Python 3.14 or later, and its only runtime dependency is [pydantic](https://docs.pydantic.dev/). Public APIs follow semantic versioning.
44
+
45
+ In an existing [uv](https://docs.astral.sh/uv/) project (run `uv init` first in a new directory), install [osrlib from PyPI](https://pypi.org/project/osrlib/):
46
+
47
+ ```sh
48
+ uv add osrlib
49
+ ```
50
+
51
+ Or install into an active virtual environment with `pip`:
52
+
53
+ ```sh
54
+ python -m pip install osrlib
55
+ ```
56
+
57
+ ## Quickstart
58
+
59
+ osrlib does not re-export names at the package root, so import each class or function from the module that defines it. Save the example below as `quickstart.py` to roll a party, move one cell east through a dungeon, print the movement message, and round-trip the session through JSON:
60
+
61
+ ```python
62
+ import json
63
+
64
+ from osrlib.core.alignment import Alignment
65
+ from osrlib.core.character import CHARACTER_CREATION_STREAM, create_character
66
+ from osrlib.core.events import Visibility
67
+ from osrlib.core.rng import RngStreams
68
+ from osrlib.core.ruleset import Ruleset
69
+ from osrlib.crawl.adventure import Adventure, TownSpec
70
+ from osrlib.crawl.commands import EnterDungeon, MoveParty, SessionMode
71
+ from osrlib.crawl.dungeon import Direction, DungeonSpec, Edge, EdgeKind, LevelSpec
72
+ from osrlib.crawl.party import Party
73
+ from osrlib.crawl.session import GameSession
74
+ from osrlib.messages import format_message
75
+ from osrlib.persistence import load_game, save_game
76
+
77
+ # Roll two 1st-level characters; every random draw comes from a named, seeded stream.
78
+ rules = Ruleset()
79
+ creation = RngStreams(master_seed=7).get(CHARACTER_CREATION_STREAM)
80
+ fighter = create_character(name="Hild", class_id="fighter", alignment=Alignment.LAWFUL, ruleset=rules, stream=creation)
81
+ cleric = create_character(name="Osric", class_id="cleric", alignment=Alignment.LAWFUL, ruleset=rules, stream=creation)
82
+ party = Party(members=[fighter.character, cleric.character])
83
+
84
+ # The smallest adventure: a town and a one-corridor dungeon, two cells joined west-east.
85
+ crypt = DungeonSpec(
86
+ id="crypt",
87
+ name="The Old Crypt",
88
+ levels=(LevelSpec(number=1, width=2, height=1, entrance=(0, 0), edges={"1,0:west": Edge(kind=EdgeKind.OPEN)}),),
89
+ )
90
+ town = TownSpec(name="Threshold", travel_turns={"crypt": 1})
91
+ adventure = Adventure(name="A First Delve", town=town, dungeons=(crypt,))
92
+
93
+ # A session starts in town; entering the dungeon switches it to exploring.
94
+ session = GameSession.new(party, adventure, seed=7, ruleset=rules)
95
+ session.execute(EnterDungeon(dungeon_id="crypt"))
96
+ assert session.mode is SessionMode.EXPLORING
97
+
98
+ # Commands in, events out: filter to player-visible events before rendering.
99
+ result = session.execute(MoveParty(direction=Direction.EAST))
100
+ assert result.accepted
101
+ lines = [format_message(event) for event in result.events if event.visibility is Visibility.PLAYER]
102
+ print(lines[0])
103
+ # The party moves to (1, 0), facing east.
104
+
105
+ # The whole session round-trips through JSON.
106
+ document = save_game(session)
107
+ restored = load_game(json.loads(json.dumps(document)))
108
+ assert save_game(restored) == document
109
+ ```
110
+
111
+ Run `quickstart.py` with `uv`:
112
+
113
+ ```sh
114
+ uv run quickstart.py
115
+ ```
116
+
117
+ Or run it with the Python interpreter from your activated virtual environment:
118
+
119
+ ```sh
120
+ python quickstart.py
121
+ ```
122
+
123
+ Running the script prints `The party moves to (1, 0), facing east.` and checks that the restored session serializes identically to the saved JSON. When adapting this snippet, keep these details in mind:
124
+
125
+ - **Map edges and travel**: Unlisted cell boundaries are walls. Setting `"1,0:west"` to `EdgeKind.OPEN` opens the west wall of `(1, 0)`, which is the shared boundary crossed when moving east from `entrance=(0, 0)`. `"crypt"` in `travel_turns={"crypt": 1}` matches `DungeonSpec(id="crypt", ...)` and `EnterDungeon(dungeon_id="crypt")`, advancing the clock by `1` ten-minute exploration turn on entry.
126
+ - **Session streams vs. creation streams**: `GameSession.new(..., seed=7)` creates a fresh set of session RNG streams from `seed`, separate from the `creation` stream used before play. If rolled ability scores miss a class's minimums, `create_character` advances `stream` and raises `ValueError`; retry with the same `stream` instance so the next attempt draws fresh rolls.
127
+ - **Player visibility and command rejections**: Filter `result.events` to `Visibility.PLAYER` before showing events to players so referee-only events stay hidden, and render screens from `session.view(Visibility.PLAYER)` rather than directly from `session` attributes. When a rule blocks a command (such as walking into a wall), `result.accepted` is `False`, `result.rejections` lists `Rejection` objects (each with a `code` and `params`), and session state, RNG streams, and the clock remain unchanged.
128
+ - **Capturing starting party state for replay**: `GameSession.new` assigns session-scoped IDs to `party.members`. If you plan to audit or replay the run from scratch with `replay_game` later, call `party_to_document(party.members)` (from `osrlib.core.character`) *before* calling `GameSession.new`.
129
+
130
+ For a step-by-step walkthrough of this program, see the [Quickstart guide](https://mmacy.github.io/osrlib-python/getting-started/quickstart/).
131
+
132
+ ## Determinism, saves, and replay
133
+
134
+ osrlib never calls Python's `random` module. Every random draw comes from a named PCG64 stream (`RngStream`) managed by `RngStreams`. Calling `streams.get("treasure")` repeatedly on the same `RngStreams` instance returns the same stateful stream, advancing on each roll without shifting other streams such as `"combat"`. Creating a new `RngStreams` with the same `master_seed` reproduces the sequence from the first draw:
135
+
136
+ ```python
137
+ from osrlib.core.dice import roll
138
+ from osrlib.core.rng import RngStreams
139
+
140
+ treasure_a = RngStreams(master_seed=42).get("treasure")
141
+ rolls_a = [roll("2d6×10", treasure_a).total for _ in range(3)]
142
+ print(rolls_a)
143
+ # [60, 80, 100]
144
+
145
+ treasure_b = RngStreams(master_seed=42).get("treasure")
146
+ rolls_b = [roll("2d6×10", treasure_b).total for _ in range(3)]
147
+ assert rolls_a == rolls_b
148
+ ```
149
+
150
+ Choose how you persist a session based on whether you need to continue play or audit a run:
151
+
152
+ - **To continue playing later, save the session (`save_game` / `load_game`)**: `save_game` serializes a running session (including the embedded adventure, current party, explored dungeon state, RNG stream positions, `command_log`, and `event_log`) to a JSON-compatible dict stamped with `schema_version` and `engine_version`. `load_game` restores that state directly without re-running commands and automatically upgrades saves written under older schema versions. Because saves store JSON data rather than Python objects, re-register any event listeners and custom monster AI policies (`action_policies`) on the restored session before executing new commands.
153
+ - **To audit or reproduce a run from scratch, also save the starting inputs (`replay_game`)**: Under the same `engine_version`, `replay_game` starts a fresh session from the master seed, a pre-session party document (captured with `party_to_document` before `GameSession.new` assigns member IDs), the adventure, and the `Ruleset`, then re-executes `command_log`. It reproduces all command-driven state, including commands that listeners issued during original play, but omits private `listener_state` dicts and events that listeners returned directly without executing a command.
154
+
155
+ ## Documentation
156
+
157
+ Read the [documentation site](https://mmacy.github.io/osrlib-python/) for guides, walkthroughs, and full reference pages for every public symbol, command, event, rejection code, message code, RNG stream, and content ID:
158
+
159
+ - **Build a dungeon**: [Building an adventure](https://mmacy.github.io/osrlib-python/getting-started/building-an-adventure/) covers laying out a dungeon grid with doors and a keyed encounter, adding features, traps, treasure, and transitions, and validating the adventure.
160
+ - **Run the command and event loop**: [Sessions, commands, and events](https://mmacy.github.io/osrlib-python/guides/sessions-commands-events/) covers session modes, command rejections, JSON serialization, and the event log.
161
+ - **Add conditional doors, scripted events, and quests**: [Gates, triggers, and quests](https://mmacy.github.io/osrlib-python/guides/gates-triggers-quests/) covers gating doors and transitions, scripting triggers, defining quests, and registering the built-in `Interpreter` listener to advance quests to a `victory` ending.
162
+ - **Call rules without a session**: [Using the rules without a session](https://mmacy.github.io/osrlib-python/guides/rules-without-a-session/) covers calling `osrlib.core` functions directly for combat, character creation, spells, and treasure.
163
+ - **Connect a UI, HTTP server, or LLM**: [The TUI crawler](https://mmacy.github.io/osrlib-python/front-ends/tui-crawler/) and [The FastAPI pattern](https://mmacy.github.io/osrlib-python/front-ends/fastapi-pattern/) walk through the terminal and HTTP applications in `examples/`, and [LLM referees](https://mmacy.github.io/osrlib-python/front-ends/llm-referees/) shows how to connect an LLM agent to commands and events.
164
+ - **Configure B/X rule options and adaptations**: [Ruleset options](https://mmacy.github.io/osrlib-python/guides/ruleset-options/) lists configurable rule flags on `Ruleset`, and the [Adaptations register](https://mmacy.github.io/osrlib-python/adaptations/) documents how osrlib resolves ambiguous B/X rules and tabletop referee procedures.
165
+
166
+ ## Contributing
167
+
168
+ Development requires Python 3.14 or later and [uv](https://docs.astral.sh/uv/). Clone the repository, install the development, documentation, and example dependencies with `uv sync`, and run the CI checks:
169
+
170
+ ```sh
171
+ git clone https://github.com/mmacy/osrlib-python.git
172
+ cd osrlib-python
173
+ uv sync
174
+ uv run ruff format --check
175
+ uv run ruff check
176
+ uv run pyright
177
+ uv run pytest
178
+ uv run mkdocs build --strict
179
+ ```
180
+
181
+ See [the specification](https://github.com/mmacy/osrlib-python/blob/main/docs/spec.md) for the architecture, contracts, and rules scope.
182
+
183
+ ### SRD data pipeline
184
+
185
+ The compiler in `tools/srd_compile/` parses the scraped SRD markdown in `srd/` and writes the validated JSON data files in `src/osrlib/data/`. Do not edit `srd/` or `src/osrlib/data/` by hand. After changing compiler code or overrides, regenerate the data files and commit the updated files in `src/osrlib/data/` with your change:
186
+
187
+ ```sh
188
+ uv run python -m tools.srd_compile
189
+ ```
190
+
191
+ CI runs this command and fails if `src/osrlib/data/` has uncommitted changes. Put parser corrections in `tools/srd_compile/overrides/` with a non-empty `reason` field; the compiler applies them during generation and records each modified field path in the entry's `overrides_applied` list.
192
+
193
+ ## Licensing
194
+
195
+ Library code is licensed under the [MIT license](https://github.com/mmacy/osrlib-python/blob/main/LICENSE). SRD-derived content (the scraped SRD markdown in `srd/` and the compiled game data in `src/osrlib/data/`) is Open Game Content under the [Open Game License 1.0a](https://github.com/mmacy/osrlib-python/blob/main/LICENSE-OGL.md), which includes the complete Section 15 copyright notice. Built wheels include a copy of `LICENSE-OGL.md` with the osrlib Section 15 entry inside `osrlib/data/`.
196
+
197
+ osrlib is an independent project and is not affiliated with or endorsed by Necrotic Gnome. "Old-School Essentials" is a trademark of Necrotic Gnome, used here only to identify the source document. osrlib makes no claim of compatibility.
osrlib-2.6.0/README.md ADDED
@@ -0,0 +1,172 @@
1
+ # osrlib
2
+
3
+ osrlib is a Python library that implements the classic 1981 B/X (Basic/Expert) fantasy adventure game rules for turn-based, grid-based dungeon crawlers in the style of the original Bard's Tale. The rules come from the [Old-School Essentials System Reference Document](https://oldschoolessentials.necroticgnome.com/srd/) (SRD), an Open Game Content restatement of the B/X rules.
4
+
5
+ osrlib has no UI, networking, or save-file I/O: you pass typed commands into an in-memory session, osrlib resolves the rules and updates game state, and your application handles rendering, player input, persistence, and transport. Every random roll draws from a named stream derived from a master seed, so running the same commands from the same starting state and seed under the same engine version produces the same game state and events every time.
6
+
7
+ osrlib separates standalone rules in `osrlib.core` (such as rolling characters, resolving attacks, or rolling treasure) from stateful dungeon-crawl sessions in `osrlib.crawl`, with shared top-level modules for compiled SRD data, message formatting, and persistence. In `osrlib.crawl`, you can bundle custom monsters, items, and spells with an adventure, put conditions on doors and stairs (which osrlib calls gates), and define quests and scripted reactions to play events (triggers).
8
+
9
+ You can use osrlib in several ways:
10
+
11
+ - **Web or mobile backends**: Serve game sessions over HTTP (for example, with FastAPI) using the generated Pydantic JSON Schemas for commands and events.
12
+ - **Terminal or desktop games**: Drive `GameSession` synchronously in process from a local interface.
13
+ - **LLM referees and narrators**: Pass structured events to a language model and execute the typed commands it returns.
14
+ - **Scripts and simulations**: Call functions in `osrlib.core` directly for character generation, combat statistics, or content validation without starting a session (see [Determinism, saves, and replay](#determinism-saves-and-replay) for a standalone dice roll and [Using the rules without a session](https://mmacy.github.io/osrlib-python/guides/rules-without-a-session/)).
15
+
16
+ ## Installation
17
+
18
+ osrlib requires Python 3.14 or later, and its only runtime dependency is [pydantic](https://docs.pydantic.dev/). Public APIs follow semantic versioning.
19
+
20
+ In an existing [uv](https://docs.astral.sh/uv/) project (run `uv init` first in a new directory), install [osrlib from PyPI](https://pypi.org/project/osrlib/):
21
+
22
+ ```sh
23
+ uv add osrlib
24
+ ```
25
+
26
+ Or install into an active virtual environment with `pip`:
27
+
28
+ ```sh
29
+ python -m pip install osrlib
30
+ ```
31
+
32
+ ## Quickstart
33
+
34
+ osrlib does not re-export names at the package root, so import each class or function from the module that defines it. Save the example below as `quickstart.py` to roll a party, move one cell east through a dungeon, print the movement message, and round-trip the session through JSON:
35
+
36
+ ```python
37
+ import json
38
+
39
+ from osrlib.core.alignment import Alignment
40
+ from osrlib.core.character import CHARACTER_CREATION_STREAM, create_character
41
+ from osrlib.core.events import Visibility
42
+ from osrlib.core.rng import RngStreams
43
+ from osrlib.core.ruleset import Ruleset
44
+ from osrlib.crawl.adventure import Adventure, TownSpec
45
+ from osrlib.crawl.commands import EnterDungeon, MoveParty, SessionMode
46
+ from osrlib.crawl.dungeon import Direction, DungeonSpec, Edge, EdgeKind, LevelSpec
47
+ from osrlib.crawl.party import Party
48
+ from osrlib.crawl.session import GameSession
49
+ from osrlib.messages import format_message
50
+ from osrlib.persistence import load_game, save_game
51
+
52
+ # Roll two 1st-level characters; every random draw comes from a named, seeded stream.
53
+ rules = Ruleset()
54
+ creation = RngStreams(master_seed=7).get(CHARACTER_CREATION_STREAM)
55
+ fighter = create_character(name="Hild", class_id="fighter", alignment=Alignment.LAWFUL, ruleset=rules, stream=creation)
56
+ cleric = create_character(name="Osric", class_id="cleric", alignment=Alignment.LAWFUL, ruleset=rules, stream=creation)
57
+ party = Party(members=[fighter.character, cleric.character])
58
+
59
+ # The smallest adventure: a town and a one-corridor dungeon, two cells joined west-east.
60
+ crypt = DungeonSpec(
61
+ id="crypt",
62
+ name="The Old Crypt",
63
+ levels=(LevelSpec(number=1, width=2, height=1, entrance=(0, 0), edges={"1,0:west": Edge(kind=EdgeKind.OPEN)}),),
64
+ )
65
+ town = TownSpec(name="Threshold", travel_turns={"crypt": 1})
66
+ adventure = Adventure(name="A First Delve", town=town, dungeons=(crypt,))
67
+
68
+ # A session starts in town; entering the dungeon switches it to exploring.
69
+ session = GameSession.new(party, adventure, seed=7, ruleset=rules)
70
+ session.execute(EnterDungeon(dungeon_id="crypt"))
71
+ assert session.mode is SessionMode.EXPLORING
72
+
73
+ # Commands in, events out: filter to player-visible events before rendering.
74
+ result = session.execute(MoveParty(direction=Direction.EAST))
75
+ assert result.accepted
76
+ lines = [format_message(event) for event in result.events if event.visibility is Visibility.PLAYER]
77
+ print(lines[0])
78
+ # The party moves to (1, 0), facing east.
79
+
80
+ # The whole session round-trips through JSON.
81
+ document = save_game(session)
82
+ restored = load_game(json.loads(json.dumps(document)))
83
+ assert save_game(restored) == document
84
+ ```
85
+
86
+ Run `quickstart.py` with `uv`:
87
+
88
+ ```sh
89
+ uv run quickstart.py
90
+ ```
91
+
92
+ Or run it with the Python interpreter from your activated virtual environment:
93
+
94
+ ```sh
95
+ python quickstart.py
96
+ ```
97
+
98
+ Running the script prints `The party moves to (1, 0), facing east.` and checks that the restored session serializes identically to the saved JSON. When adapting this snippet, keep these details in mind:
99
+
100
+ - **Map edges and travel**: Unlisted cell boundaries are walls. Setting `"1,0:west"` to `EdgeKind.OPEN` opens the west wall of `(1, 0)`, which is the shared boundary crossed when moving east from `entrance=(0, 0)`. `"crypt"` in `travel_turns={"crypt": 1}` matches `DungeonSpec(id="crypt", ...)` and `EnterDungeon(dungeon_id="crypt")`, advancing the clock by `1` ten-minute exploration turn on entry.
101
+ - **Session streams vs. creation streams**: `GameSession.new(..., seed=7)` creates a fresh set of session RNG streams from `seed`, separate from the `creation` stream used before play. If rolled ability scores miss a class's minimums, `create_character` advances `stream` and raises `ValueError`; retry with the same `stream` instance so the next attempt draws fresh rolls.
102
+ - **Player visibility and command rejections**: Filter `result.events` to `Visibility.PLAYER` before showing events to players so referee-only events stay hidden, and render screens from `session.view(Visibility.PLAYER)` rather than directly from `session` attributes. When a rule blocks a command (such as walking into a wall), `result.accepted` is `False`, `result.rejections` lists `Rejection` objects (each with a `code` and `params`), and session state, RNG streams, and the clock remain unchanged.
103
+ - **Capturing starting party state for replay**: `GameSession.new` assigns session-scoped IDs to `party.members`. If you plan to audit or replay the run from scratch with `replay_game` later, call `party_to_document(party.members)` (from `osrlib.core.character`) *before* calling `GameSession.new`.
104
+
105
+ For a step-by-step walkthrough of this program, see the [Quickstart guide](https://mmacy.github.io/osrlib-python/getting-started/quickstart/).
106
+
107
+ ## Determinism, saves, and replay
108
+
109
+ osrlib never calls Python's `random` module. Every random draw comes from a named PCG64 stream (`RngStream`) managed by `RngStreams`. Calling `streams.get("treasure")` repeatedly on the same `RngStreams` instance returns the same stateful stream, advancing on each roll without shifting other streams such as `"combat"`. Creating a new `RngStreams` with the same `master_seed` reproduces the sequence from the first draw:
110
+
111
+ ```python
112
+ from osrlib.core.dice import roll
113
+ from osrlib.core.rng import RngStreams
114
+
115
+ treasure_a = RngStreams(master_seed=42).get("treasure")
116
+ rolls_a = [roll("2d6×10", treasure_a).total for _ in range(3)]
117
+ print(rolls_a)
118
+ # [60, 80, 100]
119
+
120
+ treasure_b = RngStreams(master_seed=42).get("treasure")
121
+ rolls_b = [roll("2d6×10", treasure_b).total for _ in range(3)]
122
+ assert rolls_a == rolls_b
123
+ ```
124
+
125
+ Choose how you persist a session based on whether you need to continue play or audit a run:
126
+
127
+ - **To continue playing later, save the session (`save_game` / `load_game`)**: `save_game` serializes a running session (including the embedded adventure, current party, explored dungeon state, RNG stream positions, `command_log`, and `event_log`) to a JSON-compatible dict stamped with `schema_version` and `engine_version`. `load_game` restores that state directly without re-running commands and automatically upgrades saves written under older schema versions. Because saves store JSON data rather than Python objects, re-register any event listeners and custom monster AI policies (`action_policies`) on the restored session before executing new commands.
128
+ - **To audit or reproduce a run from scratch, also save the starting inputs (`replay_game`)**: Under the same `engine_version`, `replay_game` starts a fresh session from the master seed, a pre-session party document (captured with `party_to_document` before `GameSession.new` assigns member IDs), the adventure, and the `Ruleset`, then re-executes `command_log`. It reproduces all command-driven state, including commands that listeners issued during original play, but omits private `listener_state` dicts and events that listeners returned directly without executing a command.
129
+
130
+ ## Documentation
131
+
132
+ Read the [documentation site](https://mmacy.github.io/osrlib-python/) for guides, walkthroughs, and full reference pages for every public symbol, command, event, rejection code, message code, RNG stream, and content ID:
133
+
134
+ - **Build a dungeon**: [Building an adventure](https://mmacy.github.io/osrlib-python/getting-started/building-an-adventure/) covers laying out a dungeon grid with doors and a keyed encounter, adding features, traps, treasure, and transitions, and validating the adventure.
135
+ - **Run the command and event loop**: [Sessions, commands, and events](https://mmacy.github.io/osrlib-python/guides/sessions-commands-events/) covers session modes, command rejections, JSON serialization, and the event log.
136
+ - **Add conditional doors, scripted events, and quests**: [Gates, triggers, and quests](https://mmacy.github.io/osrlib-python/guides/gates-triggers-quests/) covers gating doors and transitions, scripting triggers, defining quests, and registering the built-in `Interpreter` listener to advance quests to a `victory` ending.
137
+ - **Call rules without a session**: [Using the rules without a session](https://mmacy.github.io/osrlib-python/guides/rules-without-a-session/) covers calling `osrlib.core` functions directly for combat, character creation, spells, and treasure.
138
+ - **Connect a UI, HTTP server, or LLM**: [The TUI crawler](https://mmacy.github.io/osrlib-python/front-ends/tui-crawler/) and [The FastAPI pattern](https://mmacy.github.io/osrlib-python/front-ends/fastapi-pattern/) walk through the terminal and HTTP applications in `examples/`, and [LLM referees](https://mmacy.github.io/osrlib-python/front-ends/llm-referees/) shows how to connect an LLM agent to commands and events.
139
+ - **Configure B/X rule options and adaptations**: [Ruleset options](https://mmacy.github.io/osrlib-python/guides/ruleset-options/) lists configurable rule flags on `Ruleset`, and the [Adaptations register](https://mmacy.github.io/osrlib-python/adaptations/) documents how osrlib resolves ambiguous B/X rules and tabletop referee procedures.
140
+
141
+ ## Contributing
142
+
143
+ Development requires Python 3.14 or later and [uv](https://docs.astral.sh/uv/). Clone the repository, install the development, documentation, and example dependencies with `uv sync`, and run the CI checks:
144
+
145
+ ```sh
146
+ git clone https://github.com/mmacy/osrlib-python.git
147
+ cd osrlib-python
148
+ uv sync
149
+ uv run ruff format --check
150
+ uv run ruff check
151
+ uv run pyright
152
+ uv run pytest
153
+ uv run mkdocs build --strict
154
+ ```
155
+
156
+ See [the specification](https://github.com/mmacy/osrlib-python/blob/main/docs/spec.md) for the architecture, contracts, and rules scope.
157
+
158
+ ### SRD data pipeline
159
+
160
+ The compiler in `tools/srd_compile/` parses the scraped SRD markdown in `srd/` and writes the validated JSON data files in `src/osrlib/data/`. Do not edit `srd/` or `src/osrlib/data/` by hand. After changing compiler code or overrides, regenerate the data files and commit the updated files in `src/osrlib/data/` with your change:
161
+
162
+ ```sh
163
+ uv run python -m tools.srd_compile
164
+ ```
165
+
166
+ CI runs this command and fails if `src/osrlib/data/` has uncommitted changes. Put parser corrections in `tools/srd_compile/overrides/` with a non-empty `reason` field; the compiler applies them during generation and records each modified field path in the entry's `overrides_applied` list.
167
+
168
+ ## Licensing
169
+
170
+ Library code is licensed under the [MIT license](https://github.com/mmacy/osrlib-python/blob/main/LICENSE). SRD-derived content (the scraped SRD markdown in `srd/` and the compiled game data in `src/osrlib/data/`) is Open Game Content under the [Open Game License 1.0a](https://github.com/mmacy/osrlib-python/blob/main/LICENSE-OGL.md), which includes the complete Section 15 copyright notice. Built wheels include a copy of `LICENSE-OGL.md` with the osrlib Section 15 entry inside `osrlib/data/`.
171
+
172
+ osrlib is an independent project and is not affiliated with or endorsed by Necrotic Gnome. "Old-School Essentials" is a trademark of Necrotic Gnome, used here only to identify the source document. osrlib makes no claim of compatibility.
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "osrlib"
3
- version = "2.5.1"
3
+ version = "2.6.0"
4
4
  description = "B/X (1981 Basic/Expert) tabletop RPG rules engine for turn-based dungeon crawlers"
5
5
  readme = "README.md"
6
6
  # The wheel ships Open Game Content (osrlib/data/*.json and its LICENSE-OGL.md
@@ -71,7 +71,7 @@ docs = [
71
71
  # the package's runtime dependency remains pydantic alone.
72
72
  examples = [
73
73
  "fastapi>=0.115",
74
- "httpx>=0.28",
74
+ "httpx2>=2.16.2",
75
75
  "uvicorn>=0.32",
76
76
  ]
77
77
 
@@ -89,8 +89,11 @@ events, save, and load. For a step-by-step explanation of this example, see the
89
89
  https://mmacy.github.io/osrlib-python/getting-started/quickstart/.
90
90
 
91
91
  ```python
92
+ import json
93
+
92
94
  from osrlib.core.alignment import Alignment
93
95
  from osrlib.core.character import CHARACTER_CREATION_STREAM, create_character
96
+ from osrlib.core.events import Visibility
94
97
  from osrlib.core.rng import RngStreams
95
98
  from osrlib.core.ruleset import Ruleset
96
99
  from osrlib.crawl.adventure import Adventure, TownSpec
@@ -118,19 +121,20 @@ town = TownSpec(name="Threshold", travel_turns={"crypt": 1})
118
121
  adventure = Adventure(name="A First Delve", town=town, dungeons=(crypt,))
119
122
 
120
123
  # A session starts in town; entering the dungeon switches it to exploring.
121
- session = GameSession.new(party, adventure, seed=7)
124
+ session = GameSession.new(party, adventure, seed=7, ruleset=rules)
122
125
  session.execute(EnterDungeon(dungeon_id="crypt"))
123
126
  assert session.mode is SessionMode.EXPLORING
124
127
 
125
- # Commands in, events out: every rules resolution is a typed event with a message code.
128
+ # Commands in, events out: filter to player-visible events before rendering.
126
129
  result = session.execute(MoveParty(direction=Direction.EAST))
127
130
  assert result.accepted
128
- lines = [format_message(event) for event in result.events]
129
- assert lines # every event formats to a default English line
131
+ lines = [format_message(event) for event in result.events if event.visibility is Visibility.PLAYER]
132
+ print(lines[0])
133
+ # The party moves to (1, 0), facing east.
130
134
 
131
- # The whole session round-trips through JSON: same seed, same commands, same game.
135
+ # The whole session round-trips through JSON.
132
136
  document = save_game(session)
133
- restored = load_game(document)
137
+ restored = load_game(json.loads(json.dumps(document)))
134
138
  assert save_game(restored) == document
135
139
  ```
136
140
  """
@@ -0,0 +1,169 @@
1
+ """Opaque player feature handles and current-location feature resolution."""
2
+
3
+ import hmac
4
+ from dataclasses import dataclass
5
+ from hashlib import sha256
6
+
7
+ from osrlib.crawl._party_location import _cell_ref, _feature_ref, _features_here
8
+ from osrlib.crawl.dungeon import FeatureSpec, GeneratedCache, Position, cell_ref
9
+
10
+ __all__ = []
11
+
12
+ _AUTHORED_DOMAIN = b"osrlib:player-feature-handle:authored:v1\0"
13
+ _GENERATED_DOMAIN = b"osrlib:player-feature-handle:generated:v1\0"
14
+ _SEED_KEY_DOMAIN = b"osrlib:player-feature-handle-key:v1\0"
15
+ _HANDLE_PREFIX = "feature:"
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class _ResolvedFeature:
20
+ """One public feature candidate resolved to its internal identity."""
21
+
22
+ raw_id: str
23
+ public_id: str
24
+ feature: FeatureSpec | None = None
25
+ cache_id: str | None = None
26
+ ref: str | None = None
27
+
28
+
29
+ def _player_handle_key(session) -> bytes:
30
+ supplied = session._player_handle_key
31
+ if supplied is not None:
32
+ return supplied
33
+ seed_bytes = str(session.master_seed).encode("ascii")
34
+ return hmac.digest(_SEED_KEY_DOMAIN, seed_bytes, sha256)
35
+
36
+
37
+ def _encode_identity(dungeon_id: str, level_number: int, item_id: str) -> bytes:
38
+ """Encode one structured feature identity without delimiter ambiguity."""
39
+ encoded = []
40
+ for value in (dungeon_id.encode(), str(level_number).encode(), item_id.encode()):
41
+ encoded.append(len(value).to_bytes(8, "big"))
42
+ encoded.append(value)
43
+ return b"".join(encoded)
44
+
45
+
46
+ def _authored_feature_id(session, dungeon_id: str, level_number: int, feature_id: str) -> str:
47
+ identity = _encode_identity(dungeon_id, level_number, feature_id)
48
+ digest = hmac.digest(_player_handle_key(session), _AUTHORED_DOMAIN + identity, sha256)
49
+ return _HANDLE_PREFIX + digest.hex()
50
+
51
+
52
+ def _generated_feature_id(session, dungeon_id: str, level_number: int, cache_id: str) -> str:
53
+ identity = _encode_identity(dungeon_id, level_number, cache_id)
54
+ digest = hmac.digest(_player_handle_key(session), _GENERATED_DOMAIN + identity, sha256)
55
+ return _HANDLE_PREFIX + digest.hex()
56
+
57
+
58
+ def _parse_cell_location(session, ref: str) -> tuple[str, int, Position] | None:
59
+ """Resolve a canonical cell reference against the session's adventure."""
60
+ if not isinstance(ref, str) or not ref.startswith("cell:"):
61
+ return None
62
+ try:
63
+ dungeon_id, level_text, cell_text = ref.removeprefix("cell:").rsplit(":", 2)
64
+ x_text, y_text = cell_text.split(",", 1)
65
+ position = (int(x_text), int(y_text))
66
+ level_number = int(level_text)
67
+ level = session.adventure.dungeon(dungeon_id).level(level_number)
68
+ except TypeError, ValueError:
69
+ return None
70
+ if not dungeon_id or not level.in_bounds(position) or ref != cell_ref(dungeon_id, level_number, position):
71
+ return None
72
+ return dungeon_id, level_number, position
73
+
74
+
75
+ def _area_at_ref(session, ref: str):
76
+ matches = [
77
+ (dungeon.id, level.number, area)
78
+ for dungeon in session.adventure.dungeons
79
+ for level in dungeon.levels
80
+ for area in level.areas
81
+ if f"{dungeon.id}:{level.number}:{area.id}" == ref
82
+ ]
83
+ if len(matches) != 1:
84
+ return None
85
+ return matches[0]
86
+
87
+
88
+ def _lair_cache_available(session, cache: GeneratedCache) -> bool:
89
+ parsed_cache = _parse_cell_location(session, cache.cell_ref)
90
+ parsed_area = _area_at_ref(session, cache.lair_area_ref or "")
91
+ if parsed_cache is None or parsed_area is None:
92
+ return False
93
+ dungeon_id, level_number, position = parsed_cache
94
+ area_dungeon_id, area_level_number, area = parsed_area
95
+ return (
96
+ (dungeon_id, level_number) == (area_dungeon_id, area_level_number)
97
+ and area.encounter is not None
98
+ and position in area.cells
99
+ and cache.lair_area_ref in session.dungeon_state.resolved_encounters
100
+ )
101
+
102
+
103
+ def _cache_available(session, cache: GeneratedCache) -> bool:
104
+ """Return whether players may see and act on a generated cache."""
105
+ parsed = _parse_cell_location(session, cache.cell_ref)
106
+ if parsed is None:
107
+ return False
108
+ dungeon_id, level_number, position = parsed
109
+ if cache.origin == "area":
110
+ return cache.lair_area_ref is None
111
+ if cache.origin == "lair":
112
+ return _lair_cache_available(session, cache)
113
+ if cache.lair_area_ref is not None:
114
+ return False
115
+ level = session.adventure.dungeon(dungeon_id).level(level_number)
116
+ for area in level.areas:
117
+ if position not in area.cells or area.encounter is None:
118
+ continue
119
+ ref = f"{dungeon_id}:{level_number}:{area.id}"
120
+ if ref not in session.dungeon_state.resolved_encounters:
121
+ return False
122
+ return True
123
+
124
+
125
+ def _current_feature_candidates(session) -> list[_ResolvedFeature]:
126
+ location = session.dungeon_state.location
127
+ if location.dungeon_id is None or location.level_number is None:
128
+ return []
129
+ dungeon_id = location.dungeon_id
130
+ level_number = location.level_number
131
+ candidates = []
132
+ for feature in _features_here(session):
133
+ ref = _feature_ref(session, feature)
134
+ candidates.append(
135
+ _ResolvedFeature(
136
+ raw_id=feature.id,
137
+ public_id=_authored_feature_id(session, dungeon_id, level_number, feature.id),
138
+ feature=feature,
139
+ ref=ref,
140
+ )
141
+ )
142
+ location_ref = _cell_ref(session)
143
+ for cache_id, cache in session.dungeon_state.generated_caches.items():
144
+ if cache.cell_ref != location_ref or not _cache_available(session, cache):
145
+ continue
146
+ candidates.append(
147
+ _ResolvedFeature(
148
+ raw_id=cache_id,
149
+ public_id=_generated_feature_id(session, dungeon_id, level_number, cache_id),
150
+ cache_id=cache_id,
151
+ )
152
+ )
153
+ return candidates
154
+
155
+
156
+ def _resolve_current_feature(session, identifier: str) -> _ResolvedFeature | None:
157
+ """Resolve a public handle or unambiguous legacy raw id at the current location."""
158
+ if identifier == "pile":
159
+ return None
160
+ candidates = _current_feature_candidates(session)
161
+ if identifier.startswith(_HANDLE_PREFIX):
162
+ matches = [
163
+ candidate
164
+ for candidate in candidates
165
+ if hmac.compare_digest(candidate.public_id.encode(), identifier.encode())
166
+ ]
167
+ else:
168
+ matches = [candidate for candidate in candidates if candidate.raw_id == identifier]
169
+ return matches[0] if len(matches) == 1 else None
@@ -23,8 +23,9 @@ from osrlib.core.items import (
23
23
  from osrlib.core.ruleset import EncumbranceMode
24
24
  from osrlib.core.validation import Rejection
25
25
  from osrlib.crawl._arrival import _spring_check
26
+ from osrlib.crawl._feature_handles import _resolve_current_feature
26
27
  from osrlib.crawl._odometer import _spend_turn
27
- from osrlib.crawl._party_location import _cell_ref, _feature_ref, _features_here
28
+ from osrlib.crawl._party_location import _cell_ref
28
29
  from osrlib.crawl._party_members import _member_able
29
30
  from osrlib.crawl._treasure import _treasure_tier
30
31
  from osrlib.crawl.commands import TakeTreasure
@@ -55,20 +56,21 @@ def _handle_take_treasure(session, command: TakeTreasure) -> tuple[list[Rejectio
55
56
  turn_events, _ = _spend_turn(session)
56
57
  events.extend(turn_events)
57
58
  return [], events
58
- cache = state.generated_caches.get(command.feature_id)
59
- if cache is not None:
60
- if cache.cell_ref != _cell_ref(session):
61
- return [Rejection(code="exploration.feature.unknown", params={"feature": command.feature_id})], []
59
+ target = _resolve_current_feature(session, command.feature_id)
60
+ if target is None:
61
+ return [Rejection(code="exploration.feature.unknown", params={"feature": command.feature_id})], []
62
+ if target.cache_id is not None:
63
+ cache = state.generated_caches[target.cache_id]
62
64
  haul = DropPile(coins=cache.coins, valuables=list(cache.valuables), magic_items=list(cache.magic_items))
63
- del state.generated_caches[command.feature_id]
65
+ del state.generated_caches[target.cache_id]
64
66
  events.extend(_take_haul(session, carriers, haul))
65
67
  turn_events, _ = _spend_turn(session)
66
68
  events.extend(turn_events)
67
69
  return [], events
68
- feature = next((f for f in _features_here(session) if f.id == command.feature_id), None)
69
- if feature is None or feature.kind != "treasure_cache":
70
+ feature = target.feature
71
+ if feature is None or feature.kind != "treasure_cache" or target.ref is None:
70
72
  return [Rejection(code="exploration.feature.unknown", params={"feature": command.feature_id})], []
71
- ref = _feature_ref(session, feature)
73
+ ref = target.ref
72
74
  if ref in state.emptied_caches:
73
75
  return [Rejection(code="exploration.feature.emptied", params={"feature": command.feature_id})], []
74
76
  trap = feature.trap