forked from johnny603/lux
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent.py
More file actions
515 lines (469 loc) · 18 KB
/
Copy pathagent.py
File metadata and controls
515 lines (469 loc) · 18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
import os
import requests
from requests.exceptions import RequestException
import achievements
import cli
import game_systems
import leaderboard
import learning_paths
import rooms
import storage
SERVER = os.getenv("PUZZLE_SERVER", "http://127.0.0.1:5050")
HINT_MODELS_ENV = "LUX_OLLAMA_MODELS"
HINT_MODEL_ENV = "LUX_OLLAMA_MODEL"
def list_levels():
try:
r = requests.get(f"{SERVER}/levels", timeout=5)
r.raise_for_status()
return r.json()
except RequestException as e:
print(f"Failed to fetch levels from {SERVER}: {e}")
return []
def get_level(level_id):
try:
r = requests.get(f"{SERVER}/level/{level_id}", timeout=5)
if r.status_code != 200:
return None
return r.json()
except RequestException as e:
print(f"Failed to fetch level {level_id}: {e}")
return None
def submit_attempt(level_id, attempt):
r = requests.post(
f"{SERVER}/submit", json={"level_id": level_id, "attempt": attempt}, timeout=15
)
r.raise_for_status()
return r.json()
def submit_files(level_id, files: dict):
"""Submit a dict of filename->content to the server for script-based validation."""
r = requests.post(f"{SERVER}/submit", json={"level_id": level_id, "files": files}, timeout=15)
r.raise_for_status()
return r.json()
def _configured_hint_models():
preferred = os.getenv(HINT_MODEL_ENV, "").strip()
configured = os.getenv(HINT_MODELS_ENV, "").strip()
defaults = ["llama3.2", "qwen2.5-coder:7b", "mistral", "phi3"]
models = []
if preferred:
models.append(preferred)
if configured:
models.extend([item.strip() for item in configured.split(",") if item.strip()])
if not models:
models = defaults
if preferred and preferred not in models:
models.insert(0, preferred)
# preserve order while removing duplicates
deduped = []
for model in models:
if model not in deduped:
deduped.append(model)
return deduped
def _safe_hint_text(text: str):
compact = " ".join((text or "").strip().split())
if not compact:
return ""
sentences = []
for chunk in compact.replace("!", ".").replace("?", ".").split("."):
chunk = chunk.strip()
if chunk:
sentences.append(chunk)
if len(sentences) >= 2:
break
hint = ". ".join(sentences) if sentences else compact
if len(hint) > 220:
hint = hint[:217].rstrip() + "..."
return hint
def _attempt_summary_for_level(state, level_id):
stats = storage.get_level_attempt_stats(state, level_id)
if not stats:
return "No prior attempts recorded."
pieces = [f"{stats.get('attempts', 0)} attempts"]
if stats.get("incorrect"):
pieces.append(f"{stats['incorrect']} incorrect")
if stats.get("last_outcome"):
pieces.append(f"last outcome: {stats['last_outcome']}")
return ", ".join(pieces)
def _build_hint_prompt(level, state=None):
state = state or storage.load_state()
tags = ", ".join(level.get("tags", []))
progress = storage.get_progress_summary(state)
attempt_summary = _attempt_summary_for_level(state, level.get("id"))
solved_sample = ", ".join(progress.get("recent_solved") or []) or "none"
return (
"You are a careful tutoring assistant for Lux puzzle practice. "
"Give one short hint only. Do not reveal the solution, flag, exact command, or full code. "
"Prefer a next step, concept reminder, or debugging direction. "
"Keep the hint concise and practical.\n\n"
f"Title: {level['title']}\n"
f"Description: {level['description']}\n"
f"Category: {level.get('category', 'uncategorized')}\n"
f"Difficulty: {level.get('difficulty', 'unknown')}\n"
f"Tags: {tags or 'none'}\n"
f"Solved progress: {progress.get('solved_count', 0)} solved, "
f"current streak {progress.get('current_streak', 0)}, "
f"best streak {progress.get('longest_streak', 0)}\n"
f"Recent solved levels: {solved_sample}\n"
f"Attempt history for this level: {attempt_summary}\n"
)
def ask_hint_via_ollama(level, state=None):
try:
import ollama
except Exception as e:
raise RuntimeError("Ollama is not available: " + str(e))
prompt = _build_hint_prompt(level, state=state)
messages = [{"role": "user", "content": prompt}]
last_error = None
for model in _configured_hint_models():
try:
res = ollama.chat(model=model, messages=messages)
content = getattr(getattr(res, "message", None), "content", "")
hint = _safe_hint_text(content)
if hint:
return hint
except Exception as exc:
last_error = exc
continue
raise RuntimeError(f"Unable to generate a hint with Ollama: {last_error}")
def print_levels(levels, solved_set=None, state=None):
print("\nAvailable levels:")
ordered = cli.sort_levels(levels, solved_set)
for lvl in ordered:
print(" ", cli.format_level_line(lvl, solved_set))
if state is None:
try:
state = storage.load_state()
except Exception:
state = None
if state:
print("\nProgress:")
print(" " + cli.format_progress_summary(state, levels))
# show achievement summary
try:
ach = state.get("achievements", {})
if ach:
print("\nAchievements:")
for k, v in ach.items():
print(f" - {v.get('title', '?')} ({k}) unlocked: {v.get('unlocked_at')}")
except Exception:
pass
def read_files_from_paths():
print("This level requires source files. Provide local file paths to upload.")
files = {}
while True:
path = input("Enter local path to a source file (or blank to finish): ").strip()
if not path:
break
try:
with open(path, "r") as f:
files[os.path.basename(path)] = f.read()
except Exception as e:
print("Failed to read file:", e)
return files
def _persist_attempt_state(state, choice, lvl, attempt_preview, correct):
storage.record_attempt(
state,
choice,
correct=correct,
title=lvl.get("title"),
difficulty=lvl.get("difficulty"),
category=lvl.get("category"),
attempt_preview=attempt_preview,
)
if correct:
stats = storage.get_level_attempt_stats(state, choice)
storage.mark_solved(
state,
choice,
attempts=stats.get("attempts", 1),
title=lvl.get("title"),
difficulty=lvl.get("difficulty"),
category=lvl.get("category"),
)
try:
game_systems.on_level_solved(state, lvl)
except Exception:
pass
try:
levels = list_levels()
except Exception:
levels = []
newly = achievements.evaluate_achievements(state, levels)
try:
leaderboard.upsert_local_entry(state, levels)
except Exception:
pass
if newly:
print("New achievements unlocked:")
for a in newly:
print(f" - {a.get('title')} ({a.get('id')})")
storage.save_state(state)
def _submit_text_attempt(choice, lvl):
attempt = input("Enter your answer/command: ").strip()
try:
res = submit_attempt(choice, attempt)
except Exception as e:
print("Submission failed:", e)
return False
state = storage.load_state()
if res.get("correct"):
print("Correct! Level solved.")
try:
_persist_attempt_state(state, choice, lvl, attempt, True)
except Exception:
pass
return True
try:
_persist_attempt_state(state, choice, lvl, attempt, False)
except Exception:
pass
print("Incorrect or tests failed.")
if res.get("output"):
print(res["output"])
return False
def _submit_script_attempt(choice, lvl):
files = read_files_from_paths()
if not files:
print("No files provided; canceling attempt.")
return False
try:
res = submit_files(choice, files)
except Exception as e:
print("Submission failed:", e)
return False
state = storage.load_state()
if res.get("correct"):
print("Correct! Level solved.")
try:
_persist_attempt_state(state, choice, lvl, None, True)
except Exception:
pass
return True
try:
_persist_attempt_state(state, choice, lvl, None, False)
except Exception:
pass
print("Incorrect or tests failed.")
if res.get("output"):
print(res["output"])
return False
def handle_attempt(choice, lvl):
if lvl.get("validator") == "script":
return _submit_script_attempt(choice, lvl)
return _submit_text_attempt(choice, lvl)
def handle_level(choice):
lvl = get_level(choice)
if not lvl:
print("Level not found.")
return
print(f"\n{lvl['title']}\n{lvl['description']}\n")
while True:
cmd = input("Options: (a)ttempt, (h)int, (b)ack: ").strip().lower()
if cmd in ("b", "back"):
return
if cmd in ("h", "hint"):
try:
print("Hint:\n", ask_hint_via_ollama(lvl, state=storage.load_state()))
except Exception as e:
print("Hint failed:", e)
continue
if cmd in ("a", "attempt"):
if handle_attempt(choice, lvl):
return
continue
print("Unknown option — choose 'a', 'h', or 'b'.")
def _handle_menu_choice(choice, state, levels):
lowered = choice.lower()
if (
lowered.startswith("look")
or lowered.startswith("look around")
or lowered.startswith("inspect room")
or lowered.startswith("atmosphere")
):
parts = choice.split(maxsplit=2)
room_id = "room-1"
if len(parts) >= 2 and parts[1].startswith("room-"):
room_id = parts[1].strip()
elif len(parts) >= 3 and parts[2].startswith("room-"):
room_id = parts[2].strip()
# Try fetching from server or fallback to local room lookup
try:
r = requests.get(f"{SERVER}/api/v1/rooms/{room_id}", timeout=5)
if r.status_code == 200:
room_data = r.json()
else:
room_data = rooms.get_room(room_id)
except Exception:
room_data = rooms.get_room(room_id)
if room_data:
print(cli.format_room_atmosphere(room_data))
else:
print(f"❌ Room '{room_id}' not found.")
return True
if lowered in ("inv", "inventory"):
inv_ids = storage.get_inventory(state)
items = [
rooms.find_object_across_rooms(iid) or {"id": iid, "name": iid, "description": ""}
for iid in inv_ids
]
print(cli.format_inventory(items))
return True
if lowered.startswith("pickup ") or lowered.startswith("take "):
parts = choice.split(maxsplit=2)
if len(parts) >= 2:
obj_id = parts[1].strip()
room_id = parts[2].strip() if len(parts) > 2 else "room-1"
res = rooms.pickup_object(room_id, obj_id, state)
if res and res.get("success"):
storage.save_state(state)
print(f"✅ {res.get('message')}")
else:
print(f"❌ {res.get('error') if res else 'Object not found'}")
else:
print("Usage: pickup <object_id> [room_id]")
return True
if lowered.startswith("use "):
parts = choice.split(maxsplit=3)
if len(parts) >= 2:
obj_id = parts[1].strip()
target_id = parts[2].strip() if len(parts) > 2 else None
room_id = parts[3].strip() if len(parts) > 3 else "room-1"
res = rooms.use_object(room_id, obj_id, target_id=target_id, state=state)
if res and res.get("success"):
storage.save_state(state)
print(f"✨ {res.get('message')}")
if res.get("use_effect"):
print(f" Effect: {res.get('use_effect')}")
else:
print(f"❌ {res.get('error') if res else 'Object not found'}")
else:
print("Usage: use <object_id> [target] [room_id]")
return True
if lowered.startswith("hint") or lowered.startswith("hints"):
parts = choice.split(maxsplit=1)
room_id = parts[1].strip() if len(parts) > 1 else "room-1"
try:
r = requests.get(f"{SERVER}/api/v1/rooms/{room_id}/hints", timeout=5)
if r.status_code == 200:
hdata = r.json()
print(cli.format_adaptive_hints(hdata))
else:
# Local fallback calculation if server is not reachable
hdata = rooms.get_adaptive_room_hints(room_id, state=state)
if hdata:
print(cli.format_adaptive_hints(hdata))
else:
print(f"❌ Room '{room_id}' not found.")
except Exception:
hdata = rooms.get_adaptive_room_hints(room_id, state=state)
if hdata:
print(cli.format_adaptive_hints(hdata))
else:
print(f"❌ Room '{room_id}' not found.")
return True
if lowered in ("rooms", "escape-rooms", "escape"):
try:
r = requests.get(f"{SERVER}/api/v1/rooms", timeout=5)
if r.status_code == 200:
summary = r.json()
print("\n=== Escape Room Progression Map ===")
for rm in summary:
st = rm.get("status")
timer = rm.get("timer")
timer_suffix = ""
if timer and timer.get("time_limit_seconds"):
t_sec = timer.get("time_limit_seconds")
if timer.get("is_expired"):
timer_suffix = f" [⏱️ EXPIRED - {t_sec}s limit]"
else:
rem = timer.get("remaining_seconds")
timer_suffix = f" [⏱️ {rem}s remaining]"
elif rm.get("time_limit_seconds"):
timer_suffix = f" [⏱️ {rm.get('time_limit_seconds')}s limit]"
if st == "escaped":
status_icon = "🔓"
elif st == "unlocked":
status_icon = "🚪"
elif st == "expired":
status_icon = "⏰"
else:
status_icon = "🔒"
r_name = rm.get('name')
r_id = rm.get('id')
print(f"[{status_icon}] {r_id}: {r_name} (Status: {st}){timer_suffix}")
if st in ("locked", "expired"):
print(f" Lock Info: {rm.get('unlock_instruction')}")
else:
task_desc = rm.get("escape_condition", {}).get("description")
print(f" Objective: {task_desc}")
print("===================================\n")
else:
print("Could not retrieve escape rooms from server.")
except Exception as exc:
print("Escape rooms unavailable:", exc)
return True
if lowered in ("ach", "achievements"):
ach = state.get("achievements", {})
if not ach:
print("No achievements unlocked yet.")
else:
print("Achievements:")
for k, v in ach.items():
print(f" - {v.get('title', '?')} ({k}) unlocked: {v.get('unlocked_at')}")
return True
if lowered in ("stats", "progress"):
print(cli.format_progress_summary(state, levels))
return True
if lowered in ("reset-ach", "reset-achievements"):
confirm = input("Are you sure you want to reset all achievements? type 'yes' to confirm: ")
if confirm.strip().lower() == "yes":
state["achievements"] = {}
storage.save_state(state)
print("Achievements cleared.")
else:
print("Reset cancelled.")
return True
if lowered in ("path", "learning-path", "recommend"):
try:
path = learning_paths.build_learning_path(state, levels)
print(path.get("summary"))
print("Recommended levels:")
for item in path.get("recommended_levels", []):
print(
f" - {item.get('id')}: {item.get('title')} "
f"({item.get('category')} · {item.get('difficulty')})"
)
except Exception as exc:
print("Learning path unavailable:", exc)
return True
if lowered in ("daily",):
try:
daily = game_systems.daily_challenge_status(state, levels)
level = daily.get("level", {})
print(
f"Daily challenge ({daily.get('date')}): {level.get('id')} - {level.get('title')}"
)
print("Completed today:" if daily.get("completed_today") else "Not completed yet.")
except Exception as exc:
print("Daily challenge unavailable:", exc)
return True
return False
def main():
print("Interactive Puzzle Agent — connect to the puzzle server and request hints.")
while True:
state = storage.load_state()
levels = list_levels()
print_levels(levels, storage.get_solved_levels(state), state=state)
print(
"Options: enter a level id to open it, 'ach' to list achievements, "
"'stats' for progress, 'path' for recommendations, "
"'daily' for today's challenge, 'reset-ach' to clear achievements, "
"or 'q' to quit."
)
choice = input("Choose level id (or 'q' to quit): ").strip()
if choice.lower() in ("q", "quit", "exit"):
break
if _handle_menu_choice(choice, state, levels):
continue
handle_level(choice)
if __name__ == "__main__":
main()