mycelium-network 0.3.1__py3-none-any.whl
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.
- lichen/__init__.py +4 -0
- lichen/api.py +303 -0
- lichen/cartographer.py +337 -0
- lichen/checkpoint.py +291 -0
- lichen/commands.py +723 -0
- lichen/engine.py +926 -0
- lichen/inventory.py +79 -0
- lichen/lore/lexicon.json +22 -0
- lichen/lore/self_claims.yaml +8 -0
- lichen/lore/structured_turn.txt +54 -0
- lichen/lore/style_crimes.json +12 -0
- lichen/lore/system_prompts.json +3 -0
- lichen/opening.py +41 -0
- lichen/premise.py +277 -0
- lichen/static/index.html +1066 -0
- lichen/story.py +705 -0
- lichen/story_context.py +201 -0
- lichen/story_journal.py +181 -0
- lichen/story_migration.py +190 -0
- lichen/story_objects.py +226 -0
- lichen/story_observations.py +238 -0
- lichen/story_presence.py +266 -0
- lichen/story_scenes.py +376 -0
- lichen/story_tags.py +381 -0
- lichen/turn.py +139 -0
- muscaria/__init__.py +1 -0
- muscaria/api.py +117 -0
- muscaria/engine.py +320 -0
- muscaria/lore/lexicon.json +22 -0
- muscaria/lore/self_claims.yaml +10 -0
- muscaria/lore/style_crimes.json +12 -0
- muscaria/lore/system_prompts.json +3 -0
- muscaria/static/index.html +288 -0
- mycelium/__init__.py +67 -0
- mycelium/adventure_snapshot.py +69 -0
- mycelium/api.py +305 -0
- mycelium/chat_intake.py +175 -0
- mycelium/chat_store.py +103 -0
- mycelium/checkin.py +150 -0
- mycelium/cli.py +105 -0
- mycelium/composer.py +337 -0
- mycelium/config.py +162 -0
- mycelium/core_engine.py +362 -0
- mycelium/distress.py +148 -0
- mycelium/doctor.py +297 -0
- mycelium/gate.py +118 -0
- mycelium/lexicon.py +92 -0
- mycelium/llm.py +107 -0
- mycelium/lore/lexicon.json +20 -0
- mycelium/lore/self_claims.yaml +8 -0
- mycelium/lore/style_crimes.json +5 -0
- mycelium/lore/system_prompts.json +3 -0
- mycelium/memory_zones.py +530 -0
- mycelium/model_routes.py +78 -0
- mycelium/physics.py +68 -0
- mycelium/recall.py +215 -0
- mycelium/receipts.py +120 -0
- mycelium/somatic_budget.py +320 -0
- mycelium/static/index.html +509 -0
- mycelium/static/safe_markdown.js +175 -0
- mycelium/store.py +244 -0
- mycelium/turn_guard.py +72 -0
- mycelium/vector_index.py +294 -0
- mycelium_hub/__init__.py +12 -0
- mycelium_hub/app.py +160 -0
- mycelium_hub/static/index.html +483 -0
- mycelium_network-0.3.1.dist-info/METADATA +111 -0
- mycelium_network-0.3.1.dist-info/RECORD +82 -0
- mycelium_network-0.3.1.dist-info/WHEEL +5 -0
- mycelium_network-0.3.1.dist-info/entry_points.txt +2 -0
- mycelium_network-0.3.1.dist-info/licenses/LICENSE +21 -0
- mycelium_network-0.3.1.dist-info/top_level.txt +5 -0
- spore/__init__.py +1 -0
- spore/api.py +85 -0
- spore/engine.py +480 -0
- spore/lore/lexicon.json +22 -0
- spore/lore/self_claims.yaml +7 -0
- spore/lore/style_crimes.json +17 -0
- spore/lore/system_prompts.json +3 -0
- spore/patches.py +231 -0
- spore/sandbox.py +346 -0
- spore/static/index.html +203 -0
lichen/__init__.py
ADDED
lichen/api.py
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
from fastapi import FastAPI
|
|
2
|
+
from fastapi.responses import HTMLResponse, JSONResponse
|
|
3
|
+
from fastapi.staticfiles import StaticFiles
|
|
4
|
+
from pydantic import BaseModel, ValidationError, model_validator
|
|
5
|
+
import os
|
|
6
|
+
import json
|
|
7
|
+
import sqlite3
|
|
8
|
+
from datetime import datetime, timezone
|
|
9
|
+
from lichen import checkpoint
|
|
10
|
+
from lichen.cartographer import Room
|
|
11
|
+
from lichen.inventory import Item
|
|
12
|
+
from lichen.opening import PlayMode, STARTER_ACTIONS
|
|
13
|
+
from lichen.story import Story
|
|
14
|
+
from lichen.turn import PendingTransfer
|
|
15
|
+
from mycelium.physics import PhysicsPacket
|
|
16
|
+
from mycelium.adventure_snapshot import SnapshotPickup
|
|
17
|
+
from typing import Literal
|
|
18
|
+
from uuid import UUID
|
|
19
|
+
from pydantic import Field, ConfigDict
|
|
20
|
+
|
|
21
|
+
from lichen.engine import PAUSE_PLAY, LichenEngine, UnresolvedTurn
|
|
22
|
+
from mycelium.chat_intake import has_credential
|
|
23
|
+
from mycelium.model_routes import attach_model_routes
|
|
24
|
+
from mycelium.receipts import attach_diag_route
|
|
25
|
+
from mycelium.turn_guard import TurnBusy, TurnGuard, TurnTimeout
|
|
26
|
+
|
|
27
|
+
app = FastAPI(title="Lichen Adventure API")
|
|
28
|
+
|
|
29
|
+
# Initialize Engine globally for the session
|
|
30
|
+
engine = LichenEngine()
|
|
31
|
+
# Chat runs off the event loop and one turn owns the world at a time.
|
|
32
|
+
turns = TurnGuard()
|
|
33
|
+
|
|
34
|
+
# Setup static directory
|
|
35
|
+
static_dir = os.path.join(os.path.dirname(__file__), "static")
|
|
36
|
+
os.makedirs(static_dir, exist_ok=True)
|
|
37
|
+
app.mount("/static", StaticFiles(directory=static_dir), name="static")
|
|
38
|
+
attach_model_routes(
|
|
39
|
+
app,
|
|
40
|
+
app_name="lichen",
|
|
41
|
+
get_llm=lambda: engine.llm,
|
|
42
|
+
is_busy=lambda: turns.is_busy,
|
|
43
|
+
)
|
|
44
|
+
attach_diag_route(app, engine.ledger)
|
|
45
|
+
|
|
46
|
+
class ChatRequest(BaseModel):
|
|
47
|
+
message: str
|
|
48
|
+
request_id: UUID | None = None
|
|
49
|
+
|
|
50
|
+
def state_payload():
|
|
51
|
+
room = None
|
|
52
|
+
if engine.cartographer.current_room:
|
|
53
|
+
r = engine.cartographer.get_room(engine.cartographer.current_room)
|
|
54
|
+
if r:
|
|
55
|
+
room = {
|
|
56
|
+
"name": r.name,
|
|
57
|
+
"description": r.visible_description(),
|
|
58
|
+
"pois": r.visible_points(),
|
|
59
|
+
"items": [item.name for item in r.available_items()],
|
|
60
|
+
"exits": [*r.exits, *sorted(r.uncharted_exits)],
|
|
61
|
+
"characters": [
|
|
62
|
+
{"id": str(character.character_id), "name": character.name, "description": character.description}
|
|
63
|
+
for character in r.characters
|
|
64
|
+
],
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
vitals = {
|
|
68
|
+
"stamina": engine.physics.energy.stamina,
|
|
69
|
+
"dopamine": engine.physics.energy.dopamine,
|
|
70
|
+
"cortisol": engine.physics.energy.cortisol,
|
|
71
|
+
"drag": engine.physics.space.narrative_drag
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
inventory = engine.inventory.list_items()
|
|
75
|
+
inventory_items = [
|
|
76
|
+
{"name": item.name, "contents": [held.name for held in item.contents]}
|
|
77
|
+
for item in engine.inventory.inventory
|
|
78
|
+
]
|
|
79
|
+
if engine.story is not None:
|
|
80
|
+
room = engine.story.scene_payload()
|
|
81
|
+
inventory = [entry.name for entry in engine.story.possessions]
|
|
82
|
+
inventory_items = [
|
|
83
|
+
{"name": entry.name, "contents": [held.name for held in engine.story.contents(entry)]}
|
|
84
|
+
for entry in engine.story.possessions
|
|
85
|
+
]
|
|
86
|
+
starter_actions = list(STARTER_ACTIONS[engine.mode]) if (
|
|
87
|
+
engine.mode and engine.seeded_opening and len(engine.transcript) == 1 and not engine.visible_from
|
|
88
|
+
) else []
|
|
89
|
+
if (engine.story and engine.story.last_beat_turn == len(engine.transcript)
|
|
90
|
+
and engine.story.reviewed_turn != engine.story.last_beat_turn):
|
|
91
|
+
starter_actions.append("/review")
|
|
92
|
+
if engine.can_pause_play:
|
|
93
|
+
starter_actions.append(PAUSE_PLAY)
|
|
94
|
+
|
|
95
|
+
return {
|
|
96
|
+
"mode": engine.mode,
|
|
97
|
+
"shared_biology": True,
|
|
98
|
+
"starter_actions": starter_actions,
|
|
99
|
+
"room": room,
|
|
100
|
+
"vitals": vitals,
|
|
101
|
+
"inventory": inventory,
|
|
102
|
+
# The sidebar shows what each container holds; inventory stays a name list for older callers.
|
|
103
|
+
"inventory_items": inventory_items,
|
|
104
|
+
"journal": engine.story.journal_payload() if engine.story is not None else [],
|
|
105
|
+
"inline_tags": engine.story.inline_tags_payload() if engine.story is not None else [],
|
|
106
|
+
"max_slots": engine.inventory.max_slots
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
@app.get("/api/state")
|
|
110
|
+
async def saved_adventure():
|
|
111
|
+
return JSONResponse(
|
|
112
|
+
{**state_payload(), "history": engine.transcript[engine.visible_from:], "cleared": bool(engine.visible_from)},
|
|
113
|
+
headers={"Cache-Control": "no-store"},
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
class AdventureFile(BaseModel):
|
|
117
|
+
model_config = ConfigDict(allow_inf_nan=False)
|
|
118
|
+
version: Literal[1]
|
|
119
|
+
mode: PlayMode | None = None
|
|
120
|
+
seeded_opening: bool = False
|
|
121
|
+
legacy_prose: bool = False
|
|
122
|
+
story: Story | None = None
|
|
123
|
+
# The typed Story fills a default version on a versionless file. Remember the
|
|
124
|
+
# version the file declared so checkpoint migration still recognizes an old save.
|
|
125
|
+
story_version: int | None = Field(default=None, exclude=True)
|
|
126
|
+
rooms: list[Room]
|
|
127
|
+
current_room: str | None
|
|
128
|
+
offer: tuple[str, str] | None = None
|
|
129
|
+
pending_transfer: PendingTransfer | None = None
|
|
130
|
+
pending_exit: tuple[str, str] | None
|
|
131
|
+
inventory: list[Item]
|
|
132
|
+
capacity: int = Field(ge=0)
|
|
133
|
+
pickups: list[SnapshotPickup]
|
|
134
|
+
history: list[tuple[str, str]]
|
|
135
|
+
transcript: list[tuple[str, str]] | None = None
|
|
136
|
+
visible_from: int = Field(default=0, ge=0)
|
|
137
|
+
turn_receipts: dict[UUID, int] = Field(default_factory=dict)
|
|
138
|
+
physics: PhysicsPacket
|
|
139
|
+
|
|
140
|
+
@model_validator(mode="before")
|
|
141
|
+
@classmethod
|
|
142
|
+
def note_story_version(cls, values):
|
|
143
|
+
story = values.get("story") if isinstance(values, dict) else None
|
|
144
|
+
if isinstance(story, dict):
|
|
145
|
+
values["story_version"] = story.get("version")
|
|
146
|
+
return values
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
@app.get("/api/adventure/save")
|
|
150
|
+
async def download_adventure():
|
|
151
|
+
return JSONResponse(checkpoint.capture(engine), headers={
|
|
152
|
+
"Cache-Control": "no-store",
|
|
153
|
+
"Content-Disposition": 'attachment; filename="lichen-adventure.json"',
|
|
154
|
+
})
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
@app.get("/api/adventure/history")
|
|
158
|
+
async def adventure_history():
|
|
159
|
+
return JSONResponse(
|
|
160
|
+
{"transcript": engine.transcript, "archives": checkpoint.archived_adventures(engine)},
|
|
161
|
+
headers={"Cache-Control": "no-store"},
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
@app.get("/api/adventure/history/{archive_id}")
|
|
166
|
+
async def archived_adventure(archive_id: UUID):
|
|
167
|
+
data = engine.store.get_record(checkpoint.ARCHIVE_PREFIX + str(archive_id))
|
|
168
|
+
if data is None:
|
|
169
|
+
return JSONResponse({"error": "Adventure history not found."}, status_code=404)
|
|
170
|
+
return JSONResponse(data, headers={"Cache-Control": "no-store"})
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
@app.post("/api/adventure/open")
|
|
174
|
+
async def open_adventure(save: AdventureFile, legacy_mode: PlayMode | None = None):
|
|
175
|
+
data = save.model_dump(mode="json")
|
|
176
|
+
if save.story is not None and save.story_version is None:
|
|
177
|
+
data["story"].pop("version", None)
|
|
178
|
+
transcript = save.history if save.transcript is None else save.transcript
|
|
179
|
+
rooms = {room.slug: room for room in save.rooms}
|
|
180
|
+
pending = save.pending_exit
|
|
181
|
+
valid_route = not pending or pending[0] in rooms and (
|
|
182
|
+
rooms[pending[0]].exits.get(pending[1]) == save.current_room and pending[1] in rooms[pending[0]].exits
|
|
183
|
+
or pending[0] == save.current_room and pending[1] in rooms[pending[0]].uncharted_exits
|
|
184
|
+
)
|
|
185
|
+
if (has_credential(json.dumps(data)) or len(rooms) != len(save.rooms)
|
|
186
|
+
or save.visible_from > len(transcript)
|
|
187
|
+
or (save.story is not None and (save.mode != "free" or save.legacy_prose))
|
|
188
|
+
or (save.story is not None and any(event.turn > len(transcript) for event in save.story.object_events))
|
|
189
|
+
or (save.story is not None and any(event.turn > len(transcript) for event in save.story.scene_events))
|
|
190
|
+
or (save.story is not None and any(record.turn > len(transcript) for record in save.story.observations))
|
|
191
|
+
or (save.story is not None and (save.story.reviewed_turn or 0) > len(transcript))
|
|
192
|
+
or (save.story is not None and (save.story.last_beat_turn or 0) > len(transcript))
|
|
193
|
+
or any(not 0 <= index < len(transcript) for index in save.turn_receipts.values())
|
|
194
|
+
or (save.pending_transfer and save.pending_transfer.room_id != save.current_room)
|
|
195
|
+
or not valid_route
|
|
196
|
+
or (save.current_room is not None and save.current_room not in rooms and not pending)):
|
|
197
|
+
return JSONResponse({"error": "Invalid adventure snapshot."}, status_code=422)
|
|
198
|
+
if save.mode is None and legacy_mode is None:
|
|
199
|
+
return JSONResponse({"error": "Choose a play mode for this older save."}, status_code=409)
|
|
200
|
+
data["mode"] = save.mode or legacy_mode
|
|
201
|
+
data["transcript"] = transcript
|
|
202
|
+
before = checkpoint.capture(engine)
|
|
203
|
+
try:
|
|
204
|
+
checkpoint.restore(engine, data)
|
|
205
|
+
checkpoint.switch_adventure(engine, before, checkpoint.capture(engine))
|
|
206
|
+
except (ValueError, sqlite3.Error):
|
|
207
|
+
checkpoint.restore(engine, before)
|
|
208
|
+
return JSONResponse({"error": "Could not open the adventure snapshot."}, status_code=422)
|
|
209
|
+
return await saved_adventure()
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
class AdventureAction(BaseModel):
|
|
213
|
+
confirmed: Literal[True]
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
class AdventureStart(BaseModel):
|
|
217
|
+
mode: PlayMode
|
|
218
|
+
opening: Literal["preset", "custom", "surprise"]
|
|
219
|
+
premise: str = Field(default="", max_length=2_000)
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
@app.post("/api/adventure/start")
|
|
223
|
+
async def start_adventure(request: AdventureStart):
|
|
224
|
+
if engine.mode is not None:
|
|
225
|
+
return JSONResponse({"error": "There is already an active adventure."}, status_code=409)
|
|
226
|
+
premise = request.premise.strip()
|
|
227
|
+
if request.opening == "custom":
|
|
228
|
+
if not premise:
|
|
229
|
+
return JSONResponse({"error": "Enter a premise before starting."}, status_code=422)
|
|
230
|
+
if has_credential(premise):
|
|
231
|
+
return JSONResponse({"error": "This premise appears to contain a credential."}, status_code=422)
|
|
232
|
+
elif request.opening == "surprise":
|
|
233
|
+
premise = "Surprise me with an opening scene."
|
|
234
|
+
else:
|
|
235
|
+
premise = None
|
|
236
|
+
try:
|
|
237
|
+
engine.start_adventure(request.mode, premise)
|
|
238
|
+
except (UnresolvedTurn, sqlite3.Error):
|
|
239
|
+
return JSONResponse(
|
|
240
|
+
{"error": "Could not start this adventure. Try again or choose a ready-made opening."},
|
|
241
|
+
status_code=503,
|
|
242
|
+
)
|
|
243
|
+
return await saved_adventure()
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
@app.post("/api/adventure/new")
|
|
247
|
+
async def new_adventure(request: AdventureAction):
|
|
248
|
+
try:
|
|
249
|
+
checkpoint.switch_adventure(engine, checkpoint.capture(engine), None)
|
|
250
|
+
except sqlite3.Error:
|
|
251
|
+
return JSONResponse({"error": "Could not save the outgoing adventure."}, status_code=503)
|
|
252
|
+
engine.reset_world()
|
|
253
|
+
return await saved_adventure()
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
@app.post("/api/adventure/clear")
|
|
257
|
+
async def clear_conversation(request: AdventureAction):
|
|
258
|
+
data = checkpoint.capture(engine)
|
|
259
|
+
data["visible_from"] = len(engine.transcript)
|
|
260
|
+
engine.store.put_record(checkpoint.CHECKPOINT_KEY, data)
|
|
261
|
+
engine.visible_from = len(engine.transcript)
|
|
262
|
+
return await saved_adventure()
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
@app.post("/api/chat")
|
|
266
|
+
def chat(request: ChatRequest):
|
|
267
|
+
try:
|
|
268
|
+
response_text = turns.run(
|
|
269
|
+
lambda abandoned: engine.process_input(
|
|
270
|
+
request.message, str(request.request_id) if request.request_id else None,
|
|
271
|
+
aborted=abandoned,
|
|
272
|
+
)
|
|
273
|
+
)
|
|
274
|
+
except TurnBusy:
|
|
275
|
+
return JSONResponse({"error": "The previous turn is still in progress."}, status_code=409)
|
|
276
|
+
except TurnTimeout:
|
|
277
|
+
return JSONResponse({"error": "This turn took too long. The world was not changed."}, status_code=504)
|
|
278
|
+
return {"response": response_text, **state_payload()}
|
|
279
|
+
|
|
280
|
+
@app.get("/api/context-snapshot")
|
|
281
|
+
async def export_snapshot():
|
|
282
|
+
try:
|
|
283
|
+
snapshot = (engine.cmd_processor.snapshot() if engine.story is None
|
|
284
|
+
else engine.story.snapshot(datetime.now(timezone.utc)))
|
|
285
|
+
except ValidationError:
|
|
286
|
+
return JSONResponse({"error": "The current room contains labels that cannot be shared."}, status_code=422)
|
|
287
|
+
if snapshot is None:
|
|
288
|
+
return JSONResponse({"error": "There is no mapped room to share."}, status_code=409)
|
|
289
|
+
if has_credential(snapshot.model_dump_json()):
|
|
290
|
+
return JSONResponse({"error": "The snapshot appears to contain a credential."}, status_code=422)
|
|
291
|
+
return JSONResponse(
|
|
292
|
+
snapshot.model_dump(mode="json"),
|
|
293
|
+
headers={
|
|
294
|
+
"Cache-Control": "no-store",
|
|
295
|
+
"Content-Disposition": 'attachment; filename="lichen-snapshot.json"',
|
|
296
|
+
},
|
|
297
|
+
)
|
|
298
|
+
|
|
299
|
+
@app.get("/", response_class=HTMLResponse)
|
|
300
|
+
async def serve_ui():
|
|
301
|
+
with open(os.path.join(static_dir, "index.html"), "r") as f:
|
|
302
|
+
return HTMLResponse(f.read(), headers={"Cache-Control": "no-store"})
|
|
303
|
+
|
lichen/cartographer.py
ADDED
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
import re
|
|
2
|
+
from dataclasses import dataclass, field
|
|
3
|
+
from typing import List, Dict, Optional
|
|
4
|
+
|
|
5
|
+
from .inventory import Item, item_name_key
|
|
6
|
+
from .turn import Character, CharacterDraft, RoomDraft
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
OPPOSITE = {
|
|
10
|
+
"NORTH": "SOUTH", "SOUTH": "NORTH", "EAST": "WEST", "WEST": "EAST",
|
|
11
|
+
"NORTHEAST": "SOUTHWEST", "SOUTHWEST": "NORTHEAST",
|
|
12
|
+
"NORTHWEST": "SOUTHEAST", "SOUTHEAST": "NORTHWEST",
|
|
13
|
+
"UP": "DOWN", "DOWN": "UP", "OUT": "IN", "IN": "OUT",
|
|
14
|
+
}
|
|
15
|
+
LOOSE = re.compile(
|
|
16
|
+
r"(?:on\s+(?:(?:the|a|an)\s+)?(?:table|floor|ground|desk|shelf|counter|bench)|next to [\w -]+)\.?$",
|
|
17
|
+
re.IGNORECASE,
|
|
18
|
+
)
|
|
19
|
+
BLOCKED = re.compile(
|
|
20
|
+
r"\b(?:inside|behind|within)\b|\bin\s+(?:(?:the|a|an)\s+)?"
|
|
21
|
+
r"(?:(?:locked|sealed|closed)\s+)?(?:case|cabinet|crate|box|chest)\b",
|
|
22
|
+
re.IGNORECASE,
|
|
23
|
+
)
|
|
24
|
+
PLACEMENT_START = re.compile(
|
|
25
|
+
r"\s+(?:(?:is|lies|rests|sits|stands)\s+)?(?P<location>(?:on|next to|inside|behind|within|in)\s+)",
|
|
26
|
+
re.I,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def label_parts(label: str) -> tuple[str, str]:
|
|
31
|
+
name, parenthesis, location = label.partition("(")
|
|
32
|
+
if parenthesis:
|
|
33
|
+
detail, _, trailing = location.partition(")")
|
|
34
|
+
return name.strip(), (detail.rstrip(". ") + trailing).strip()
|
|
35
|
+
if placement := PLACEMENT_START.search(label):
|
|
36
|
+
location = label[placement.start("location"):].strip()
|
|
37
|
+
if LOOSE.fullmatch(location) or BLOCKED.search(location):
|
|
38
|
+
return label[:placement.start()].strip(), location
|
|
39
|
+
return label.rstrip(".").strip(), ""
|
|
40
|
+
|
|
41
|
+
# Item lists sometimes arrive as sentences, with the placement after the noun.
|
|
42
|
+
ITEM_PLACEMENT = re.compile(
|
|
43
|
+
r"\s+(?:is|lies|rests|sits|hangs|stands)\s+"
|
|
44
|
+
r"(?=(?:on|under|beneath|inside|behind|within|in|beside|by|against|near)\b)", re.I,
|
|
45
|
+
)
|
|
46
|
+
PICKED_UP = re.compile(r"\s*[(*_]*picked up[)*_.!]*\s*$", re.I)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def item_parts(label: str) -> tuple[str, str]:
|
|
50
|
+
if "(" in label:
|
|
51
|
+
return label_parts(label)
|
|
52
|
+
if placement := ITEM_PLACEMENT.search(label):
|
|
53
|
+
return label[:placement.start()].strip(), label[placement.end():].rstrip(".")
|
|
54
|
+
return label_parts(label)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def merge_points(points: list[str]) -> list[str]:
|
|
58
|
+
by_feature = {}
|
|
59
|
+
for point in points:
|
|
60
|
+
name, _ = label_parts(point)
|
|
61
|
+
# A trailing descriptive clause can change while the named feature stays in place.
|
|
62
|
+
subject = re.split(r",\s+(?=where\b|which\b|covered\b|with\b|leading\b|lined\b)", name, maxsplit=1, flags=re.I)[0]
|
|
63
|
+
by_feature[item_name_key(subject)] = point
|
|
64
|
+
return list(by_feature.values())
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def empty_item(label: str) -> bool:
|
|
68
|
+
return label.strip().rstrip(".").casefold() in {"none", "none visible", "no items", "no items visible", "nothing visible"}
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass
|
|
72
|
+
class Room:
|
|
73
|
+
slug: str
|
|
74
|
+
name: str
|
|
75
|
+
description: str
|
|
76
|
+
points_of_interest: List[str] = field(default_factory=list)
|
|
77
|
+
exits: Dict[str, str] = field(default_factory=dict) # direction -> target_slug
|
|
78
|
+
items: List[Item] = field(default_factory=list)
|
|
79
|
+
confirmed_exits: Dict[str, str] = field(default_factory=dict)
|
|
80
|
+
discovered_items: set[str] = field(default_factory=set)
|
|
81
|
+
blocked_items: set[str] = field(default_factory=set)
|
|
82
|
+
uncharted_exits: set[str] = field(default_factory=set)
|
|
83
|
+
characters: list[Character] = field(default_factory=list)
|
|
84
|
+
|
|
85
|
+
def with_character_updates(self, drafts: list[CharacterDraft]) -> list[Character]:
|
|
86
|
+
characters = {character.character_id: character for character in self.characters}
|
|
87
|
+
updated = set()
|
|
88
|
+
for draft in drafts:
|
|
89
|
+
existing = characters.get(draft.character_id)
|
|
90
|
+
if draft.character_id is not None and existing is None:
|
|
91
|
+
raise ValueError("Use a character ID from this room.")
|
|
92
|
+
key = item_name_key(draft.name)
|
|
93
|
+
for character in characters.values():
|
|
94
|
+
if item_name_key(character.name) == key and character.character_id != draft.character_id:
|
|
95
|
+
if draft.character_id is not None:
|
|
96
|
+
raise ValueError("Keep established characters distinct.")
|
|
97
|
+
existing = character
|
|
98
|
+
break
|
|
99
|
+
if existing:
|
|
100
|
+
if existing.character_id in updated:
|
|
101
|
+
raise ValueError("Update each character at most once per turn.")
|
|
102
|
+
character = Character(draft.name, draft.description or existing.description, existing.character_id)
|
|
103
|
+
else:
|
|
104
|
+
character = Character(draft.name, draft.description)
|
|
105
|
+
characters[character.character_id] = character
|
|
106
|
+
updated.add(character.character_id)
|
|
107
|
+
return list(characters.values())
|
|
108
|
+
|
|
109
|
+
def available_items(self) -> list[Item]:
|
|
110
|
+
# An Items heading alone cannot override a specific barrier in the room.
|
|
111
|
+
blocked = {
|
|
112
|
+
item_name_key(name)
|
|
113
|
+
for name, location in map(item_parts, self.points_of_interest)
|
|
114
|
+
if BLOCKED.search(location)
|
|
115
|
+
}
|
|
116
|
+
return [item for item in self.items if item_name_key(item.name) not in blocked | self.blocked_items]
|
|
117
|
+
|
|
118
|
+
def blocks_item(self, name: str) -> bool:
|
|
119
|
+
key = item_name_key(name)
|
|
120
|
+
return key in self.blocked_items or any(
|
|
121
|
+
item_name_key(subject) == key and BLOCKED.search(location)
|
|
122
|
+
for subject, location in map(item_parts, self.visible_points())
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
def visible_description(self) -> str:
|
|
126
|
+
missing = self.discovered_items - {item_name_key(item.name) for item in self.items}
|
|
127
|
+
if not missing:
|
|
128
|
+
return self.description
|
|
129
|
+
names = "|".join(re.escape(name) for name in sorted(missing) if name)
|
|
130
|
+
if not names:
|
|
131
|
+
return self.description
|
|
132
|
+
placement = re.compile(
|
|
133
|
+
rf"^\s*(?:you (?:see|notice|spot)\s+)?(?:(?:a|an|the)\s+)?(?:{names})\s+"
|
|
134
|
+
r"(?:(?:is|lies|rests|sits|hangs|stands)\s+)?"
|
|
135
|
+
r"(?:on|under|inside|in|beside|by|from|against)\s+",
|
|
136
|
+
re.IGNORECASE,
|
|
137
|
+
)
|
|
138
|
+
lines = re.split(r"(?<=[.!?])\s+", self.description)
|
|
139
|
+
kept = [line for line in lines if not placement.match(line)]
|
|
140
|
+
return " ".join(kept) if len(kept) != len(lines) else self.description
|
|
141
|
+
|
|
142
|
+
def visible_points(self) -> list[str]:
|
|
143
|
+
missing = self.discovered_items - {item_name_key(item.name) for item in self.items}
|
|
144
|
+
return [point for point in self.points_of_interest if item_name_key(label_parts(point)[0]) not in missing]
|
|
145
|
+
|
|
146
|
+
class Cartographer:
|
|
147
|
+
"""
|
|
148
|
+
Parses spatial descriptions from the LLM and maps them into graph nodes.
|
|
149
|
+
Expects format:
|
|
150
|
+
**[Room Name]**
|
|
151
|
+
Description...
|
|
152
|
+
**Points of Interest:**
|
|
153
|
+
- point
|
|
154
|
+
**Items:**
|
|
155
|
+
- item name
|
|
156
|
+
**Exits:**
|
|
157
|
+
- North to [Room Name]
|
|
158
|
+
"""
|
|
159
|
+
def __init__(self):
|
|
160
|
+
self.world_map: Dict[str, Room] = {}
|
|
161
|
+
self.current_room: Optional[str] = None
|
|
162
|
+
self.pending_exit: tuple[str, str] | None = None
|
|
163
|
+
|
|
164
|
+
def _slugify(self, text: str) -> str:
|
|
165
|
+
return re.sub(r'[^a-z0-9]+', '_', text.lower()).strip('_')
|
|
166
|
+
|
|
167
|
+
def proposed_room(self, draft: RoomDraft) -> Room:
|
|
168
|
+
slug = self._slugify(draft.name)
|
|
169
|
+
if not slug:
|
|
170
|
+
raise ValueError("Provide a room name with a usable identifier.")
|
|
171
|
+
points = [point for point in draft.points_of_interest if any(char.isalnum() for char in point)]
|
|
172
|
+
room = Room(slug, draft.name, draft.description, points)
|
|
173
|
+
for exit in draft.exits:
|
|
174
|
+
if exit.direction in room.exits or exit.direction in room.uncharted_exits:
|
|
175
|
+
raise ValueError("Provide each exit direction once.")
|
|
176
|
+
if exit.destination is None:
|
|
177
|
+
room.uncharted_exits.add(exit.direction)
|
|
178
|
+
continue
|
|
179
|
+
target = self._slugify(exit.destination)
|
|
180
|
+
if not target:
|
|
181
|
+
raise ValueError("Provide a usable destination name or null for an uncharted exit.")
|
|
182
|
+
room.exits[exit.direction] = target
|
|
183
|
+
|
|
184
|
+
names = set()
|
|
185
|
+
for item in draft.items:
|
|
186
|
+
key = item_name_key(item.name)
|
|
187
|
+
if key in names or empty_item(item.name) or PICKED_UP.search(item.name):
|
|
188
|
+
raise ValueError("List distinct physical items by name.")
|
|
189
|
+
names.add(key)
|
|
190
|
+
if not item.reachable or BLOCKED.search(item.placement):
|
|
191
|
+
room.blocked_items.add(key)
|
|
192
|
+
room.points_of_interest.append(f"{item.name} ({item.placement})")
|
|
193
|
+
else:
|
|
194
|
+
room.items.append(Item(name=item.name, description=item.placement))
|
|
195
|
+
return room
|
|
196
|
+
|
|
197
|
+
def read_room(self, llm_output: str) -> Optional[Room]:
|
|
198
|
+
sections = list(re.finditer(
|
|
199
|
+
r"^[ \t]*\*\*(Points of Interest|Items|Exits):\*\*[ \t]*\r?$",
|
|
200
|
+
llm_output, re.IGNORECASE | re.MULTILINE,
|
|
201
|
+
))
|
|
202
|
+
intro = llm_output[:sections[0].start()] if sections else llm_output
|
|
203
|
+
title = re.search(r"^[ \t]*\*\*\[([^\]\r\n]+)\]\*\*[ \t]*(?:\r?\n|$)", intro, re.MULTILINE)
|
|
204
|
+
if title:
|
|
205
|
+
name = title[1].strip()
|
|
206
|
+
description = intro[title.end():].strip()
|
|
207
|
+
else:
|
|
208
|
+
# A narrator can greet the player before introducing a room in prose.
|
|
209
|
+
if len({section[1].casefold() for section in sections}) < 2:
|
|
210
|
+
return None
|
|
211
|
+
heading = re.match(r"\s*\*\*([^*\[\]\r\n]+)\*\*[ \t]*(?:\r?\n|$)", intro)
|
|
212
|
+
body = intro[heading.end():] if heading else intro
|
|
213
|
+
introduction = re.search(
|
|
214
|
+
r"\byou (?:find yourself|are|arrive) (?:now )?(?:in|at|inside) (?:the )?\*\*([^*\r\n]+)\*\*",
|
|
215
|
+
body, re.IGNORECASE,
|
|
216
|
+
)
|
|
217
|
+
if introduction:
|
|
218
|
+
name = introduction[1].strip()
|
|
219
|
+
elif heading and not heading[1].endswith(("!", "?")):
|
|
220
|
+
name = heading[1].strip()
|
|
221
|
+
else:
|
|
222
|
+
return None
|
|
223
|
+
description = body.strip()
|
|
224
|
+
|
|
225
|
+
slug = self._slugify(name)
|
|
226
|
+
if not slug:
|
|
227
|
+
return None
|
|
228
|
+
|
|
229
|
+
bullets: dict[str, list[str]] = {}
|
|
230
|
+
for index, section in enumerate(sections):
|
|
231
|
+
end = sections[index + 1].start() if index + 1 < len(sections) else len(llm_output)
|
|
232
|
+
lines = llm_output[section.end():end].strip().splitlines()
|
|
233
|
+
labels = bullets.setdefault(section[1].casefold(), [])
|
|
234
|
+
for line in lines:
|
|
235
|
+
match = re.match(r"\s*-\s+(.+)", line)
|
|
236
|
+
if not match:
|
|
237
|
+
break
|
|
238
|
+
labels.append(match[1].strip().replace("**", ""))
|
|
239
|
+
|
|
240
|
+
pois = bullets.get("points of interest", [])
|
|
241
|
+
exits = {}
|
|
242
|
+
for label in bullets.get("exits", []):
|
|
243
|
+
direction, _, route = label.partition(" ")
|
|
244
|
+
direction = direction.rstrip(",:").upper()
|
|
245
|
+
if direction not in OPPOSITE:
|
|
246
|
+
continue
|
|
247
|
+
target = re.search(r"\[([^\]]+)\]", route) or re.search(r"\bto\s+(.+)", route, re.I)
|
|
248
|
+
if target and (target_slug := self._slugify(target[1])):
|
|
249
|
+
exits[direction] = target_slug
|
|
250
|
+
|
|
251
|
+
items = []
|
|
252
|
+
known_items = set()
|
|
253
|
+
for label in bullets.get("items", []):
|
|
254
|
+
if empty_item(label) or PICKED_UP.search(label):
|
|
255
|
+
continue
|
|
256
|
+
item_name, location = item_parts(label)
|
|
257
|
+
key = item_name_key(item_name)
|
|
258
|
+
if BLOCKED.search(location):
|
|
259
|
+
pois.append(label)
|
|
260
|
+
elif key and key not in known_items and len(item_name) <= 96 and len(items) < 32:
|
|
261
|
+
if LOOSE.fullmatch(location):
|
|
262
|
+
pois.append(label)
|
|
263
|
+
items.append(Item(name=item_name, description=label if label != item_name else ""))
|
|
264
|
+
known_items.add(key)
|
|
265
|
+
|
|
266
|
+
pois.sort(key=lambda point: bool(BLOCKED.search(label_parts(point)[1])))
|
|
267
|
+
known_items = {item_name_key(item.name) for item in items}
|
|
268
|
+
for point in pois:
|
|
269
|
+
item_name, location = label_parts(point)
|
|
270
|
+
key = item_name_key(item_name)
|
|
271
|
+
if key and key not in known_items and len(item_name) <= 96 and len(items) < 32 and LOOSE.fullmatch(location):
|
|
272
|
+
items.append(Item(name=item_name, description=point))
|
|
273
|
+
known_items.add(key)
|
|
274
|
+
|
|
275
|
+
return Room(slug=slug, name=name, description=description,
|
|
276
|
+
points_of_interest=pois, exits=exits, items=items)
|
|
277
|
+
|
|
278
|
+
def record_room(self, room: Room, action: str = "") -> Room | None:
|
|
279
|
+
if self.pending_exit:
|
|
280
|
+
origin, direction = self.pending_exit
|
|
281
|
+
if direction in self.world_map[origin].uncharted_exits:
|
|
282
|
+
if room.slug == origin:
|
|
283
|
+
return None
|
|
284
|
+
elif room.slug != self.current_room:
|
|
285
|
+
return None
|
|
286
|
+
existing = self.world_map.get(room.slug)
|
|
287
|
+
if existing is not None:
|
|
288
|
+
# A fresh description can add discoveries. Replacing a feature needs a
|
|
289
|
+
# physical action directed at the feature or its recorded placement.
|
|
290
|
+
changed = re.fullmatch(
|
|
291
|
+
r"(?:i\s+)?(?:open|unlock|close|break|cut|scrape|wipe|clean|paint|move|push|pull)"
|
|
292
|
+
r"\s+(?:the\s+|a\s+|an\s+)?([\w -]+)[.!]?", action.strip(), re.I,
|
|
293
|
+
)
|
|
294
|
+
protected = [
|
|
295
|
+
point for point in existing.points_of_interest
|
|
296
|
+
if not changed or not re.search(r"\b" + re.escape(changed[1].strip()) + r"\b", point, re.I)
|
|
297
|
+
]
|
|
298
|
+
existing.points_of_interest = merge_points(existing.points_of_interest + room.points_of_interest + protected)
|
|
299
|
+
existing.exits = {**room.exits, **existing.exits, **existing.confirmed_exits}
|
|
300
|
+
existing.uncharted_exits = (existing.uncharted_exits | room.uncharted_exits) - existing.exits.keys()
|
|
301
|
+
existing.description = existing.description or room.description
|
|
302
|
+
existing.blocked_items.update(room.blocked_items)
|
|
303
|
+
# Omission is a change in narration. A successful take is what removes an item placement.
|
|
304
|
+
for item in room.items:
|
|
305
|
+
key = item_name_key(item.name)
|
|
306
|
+
if key not in existing.discovered_items and len(existing.discovered_items) < 32:
|
|
307
|
+
existing.discovered_items.add(key)
|
|
308
|
+
existing.items.append(item)
|
|
309
|
+
room = existing
|
|
310
|
+
else:
|
|
311
|
+
room.points_of_interest = merge_points(room.points_of_interest)
|
|
312
|
+
room.discovered_items = {item_name_key(item.name) for item in room.items}
|
|
313
|
+
self.world_map[room.slug] = room
|
|
314
|
+
|
|
315
|
+
self.current_room = room.slug
|
|
316
|
+
if self.pending_exit:
|
|
317
|
+
origin, direction = self.pending_exit
|
|
318
|
+
self.confirm_traversal(origin, direction, room.slug)
|
|
319
|
+
self.pending_exit = None
|
|
320
|
+
return room
|
|
321
|
+
|
|
322
|
+
def parse_room(self, llm_output: str) -> Optional[Room]:
|
|
323
|
+
room = self.read_room(llm_output)
|
|
324
|
+
return self.record_room(room) if room is not None else None
|
|
325
|
+
|
|
326
|
+
def confirm_traversal(self, origin: str, direction: str, target: str) -> None:
|
|
327
|
+
start = self.world_map[origin]
|
|
328
|
+
start.uncharted_exits.discard(direction)
|
|
329
|
+
start.confirmed_exits[direction] = start.exits[direction] = target
|
|
330
|
+
reverse = OPPOSITE.get(direction)
|
|
331
|
+
if reverse and target != origin:
|
|
332
|
+
destination = self.world_map[target]
|
|
333
|
+
destination.uncharted_exits.discard(reverse)
|
|
334
|
+
destination.exits[reverse] = destination.confirmed_exits.setdefault(reverse, origin)
|
|
335
|
+
|
|
336
|
+
def get_room(self, slug: str | None) -> Optional[Room]:
|
|
337
|
+
return self.world_map.get(slug) if slug is not None else None
|