-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
910 lines (792 loc) · 28 KB
/
Copy pathapp.py
File metadata and controls
910 lines (792 loc) · 28 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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
from __future__ import annotations
import json
import logging
import os
import sys
import tempfile
from datetime import datetime, timezone
from pathlib import Path
from threading import Lock
from typing import Any
from flask import Flask, jsonify, request
from agent import (
AGENT_LEVEL,
AGENT_PLAY_DATA,
AgentConfigError,
AgentExecutionError,
AgentRequestError,
plan_next_action,
validate_agent_request,
)
from agent.logging_utils import (
configure_logging,
get_logger,
log_event,
normalize_flask_logger,
)
if "--debug" in sys.argv:
sys.argv.remove("--debug")
os.environ["AGENT_DEBUG_LOG"] = "1"
os.environ["APP_LOG_LEVEL"] = "DEBUG"
configure_logging()
LOGGER = get_logger("app")
app = Flask(__name__)
normalize_flask_logger(app)
STORE_PATH = Path(__file__).resolve().parent / "__data1" / "recordings.json"
TRACE_STORE_PATH = Path(__file__).resolve().parent / "__data1" / "agent-traces.json"
STORE_VERSION = 1
TRACE_STORE_VERSION = 3
TRACE_RUN_LIMIT = 10
RECORDING_RUN_LIMIT = 10
_store_lock = Lock()
_trace_store_lock = Lock()
log_event(
LOGGER,
logging.INFO,
"backend_startup_complete",
store_path=STORE_PATH.name,
trace_store_path=TRACE_STORE_PATH.name,
app_log_level=os.environ.get("APP_LOG_LEVEL", "INFO").upper(),
)
def utc_now() -> str:
return (
datetime.now(timezone.utc)
.isoformat(timespec="milliseconds")
.replace("+00:00", "Z")
)
def empty_store() -> dict[str, Any]:
return {"version": STORE_VERSION, "updatedAt": None, "records": {}}
def empty_trace_store() -> dict[str, Any]:
return {"version": TRACE_STORE_VERSION, "updatedAt": None, "runs": {}}
def normalize_id(value: str, name: str) -> str:
try:
parsed = int(value)
except ValueError as exc:
raise ValueError(f"{name} must be an integer") from exc
if parsed <= 0:
raise ValueError(f"{name} must be positive")
return str(parsed)
def load_json_store(path: Path, empty_factory) -> dict[str, Any]:
if not path.exists():
return empty_factory()
try:
with path.open("r", encoding="utf-8") as handle:
data = json.load(handle)
except Exception as exc:
log_event(
LOGGER, logging.ERROR, "json_store_load_failed", path=path.name, error=exc
)
raise
if not isinstance(data, dict):
return empty_factory()
return data
def save_json_store(path: Path, store: dict[str, Any]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
fd, tmp_path = tempfile.mkstemp(
prefix=f".{path.name}.",
suffix=".tmp",
dir=path.parent,
text=True,
)
try:
with os.fdopen(fd, "w", encoding="utf-8") as handle:
json.dump(store, handle, indent=2, sort_keys=True)
handle.write("\n")
os.replace(tmp_path, path)
except Exception as exc:
try:
os.unlink(tmp_path)
except FileNotFoundError:
pass
log_event(
LOGGER, logging.ERROR, "json_store_save_failed", path=path.name, error=exc
)
raise
def load_store() -> dict[str, Any]:
data = load_json_store(STORE_PATH, empty_store)
data.setdefault("version", STORE_VERSION)
data.setdefault("updatedAt", None)
if not isinstance(data.get("records"), dict):
data["records"] = {}
return data
def save_store(store: dict[str, Any]) -> None:
save_json_store(STORE_PATH, store)
def recording_sort_key(record: dict[str, Any]) -> str:
value = record.get("savedAt") or ""
return str(value)
def sorted_record_items(records: dict[str, Any]) -> list[tuple[str, dict[str, Any]]]:
retained = sorted(
(
(index, str(record_id), record)
for index, (record_id, record) in enumerate(records.items())
if isinstance(record, dict)
),
key=lambda item: (recording_sort_key(item[2]), item[0]),
reverse=True,
)
return [(record_id, record) for _index, record_id, record in retained]
def prune_recordings(store: dict[str, Any]) -> None:
records = store.get("records")
if not isinstance(records, dict):
store["records"] = {}
return
sorted_items = sorted_record_items(records)
pinned_ids = {
record_id
for record_id, record in sorted_items
if record.get("pinned") is True
}
unpinned_items = [
item for item in sorted_items if item[1].get("pinned") is not True
]
retained_unpinned_ids = {
record_id
for record_id, _record in unpinned_items[:RECORDING_RUN_LIMIT]
}
retained_ids = pinned_ids | retained_unpinned_ids
store["records"] = dict(
(record_id, record)
for record_id, record in sorted_items
if record_id in retained_ids
)
def pinned_trace_ids_from_store(store: dict[str, Any]) -> set[str]:
records = store.get("records", {})
if not isinstance(records, dict):
return set()
return {
trace_id
for record in records.values()
if isinstance(record, dict)
and record.get("pinned") is True
and record.get("source") == "agent"
for trace_id in [record.get("traceId")]
if isinstance(trace_id, str) and trace_id
}
def load_pinned_trace_ids() -> set[str]:
with _store_lock:
return pinned_trace_ids_from_store(load_store())
def find_latest_recording(
store: dict[str, Any], play_data: str, level: str
) -> dict[str, Any] | None:
records = store.get("records", {})
if not isinstance(records, dict):
return None
for _record_id, record in sorted_record_items(records):
if (
str(record.get("playData")) == play_data
and str(record.get("level")) == level
):
return record
return None
def find_recordings(
store: dict[str, Any], play_data: str, level: str
) -> list[dict[str, Any]]:
records = store.get("records", {})
if not isinstance(records, dict):
return []
return [
record
for _record_id, record in sorted_record_items(records)
if str(record.get("playData")) == play_data
and str(record.get("level")) == level
]
def resolve_recording_id(
store: dict[str, Any], record_id_prefix: str, play_data: str, level: str
) -> tuple[str | None, bool]:
records = store.get("records", {})
if not isinstance(records, dict):
return None, False
matching_ids = [
str(record_id)
for record_id, record in records.items()
if isinstance(record, dict)
and str(record.get("playData")) == play_data
and str(record.get("level")) == level
and str(record_id).startswith(record_id_prefix)
]
if record_id_prefix in matching_ids:
return record_id_prefix, False
if len(matching_ids) == 1:
return matching_ids[0], False
return None, len(matching_ids) > 1
def delete_trace_run(trace_id: str | None) -> bool:
if not trace_id:
return False
with _trace_store_lock:
store = load_trace_store()
existed = store["runs"].pop(trace_id, None) is not None
if existed:
store["updatedAt"] = utc_now()
save_trace_store(store)
return existed
def load_trace_store() -> dict[str, Any]:
data = load_json_store(TRACE_STORE_PATH, empty_trace_store)
data.setdefault("version", TRACE_STORE_VERSION)
data.setdefault("updatedAt", None)
if not isinstance(data.get("runs"), dict):
data["runs"] = {}
return data
def save_trace_store(store: dict[str, Any]) -> None:
save_json_store(TRACE_STORE_PATH, store)
def validate_demo(demo: Any) -> dict[str, Any]:
if not isinstance(demo, dict):
raise ValueError("demo must be an object")
for key in ("level", "ai", "time", "state", "action", "goldDrop", "bornPos"):
if key not in demo:
raise ValueError(f"demo.{key} is required")
for key in ("action", "goldDrop", "bornPos"):
if not isinstance(demo[key], list):
raise ValueError(f"demo.{key} must be an array")
return demo
def validate_source(value: Any) -> str:
if value is None:
return "user"
if value not in {"user", "agent"}:
raise ValueError("source must be user or agent")
return value
def validate_result(value: Any, demo: dict[str, Any]) -> str:
if value is None:
return "success" if int(demo.get("state", 0)) == 1 else "failure"
if value not in {"success", "failure"}:
raise ValueError("result must be success or failure")
return value
def validate_solver(value: Any) -> dict[str, Any] | None:
if value is None:
return None
if not isinstance(value, dict):
raise ValueError("solver must be an object")
allowed_keys = {
"modelProfile",
"provider",
"model",
"generatedAt",
"responseId",
"traceId",
"failureReason",
}
solver = {
key: value[key]
for key in allowed_keys
if key in value and value[key] is not None
}
for key in (
"modelProfile",
"provider",
"model",
"responseId",
"traceId",
"failureReason",
):
if key in solver and not isinstance(solver[key], str):
raise ValueError(f"solver.{key} must be a string")
if "generatedAt" in solver and not isinstance(
solver["generatedAt"], (int, float, str)
):
raise ValueError("solver.generatedAt must be a number or string")
return solver or None
def validate_trace_id(value: Any) -> str | None:
if value is None:
return None
if not isinstance(value, str) or not value.strip():
raise ValueError("traceId must be a string")
return value.strip()
def validate_record_id(value: Any) -> str | None:
if value is None:
return None
if not isinstance(value, str) or not value.strip():
raise ValueError("id must be a string")
return value.strip()
def trace_model_summary(planner: dict[str, Any] | None) -> dict[str, Any] | None:
if not isinstance(planner, dict):
return None
summary = {
key: planner.get(key)
for key in ("modelProfile", "provider", "model", "modelSource")
if planner.get(key) is not None
}
return summary or None
def trace_config_summary(planner: dict[str, Any] | None) -> dict[str, Any] | None:
if not isinstance(planner, dict):
return None
config = planner.get("config")
return config if isinstance(config, dict) and config else None
def trace_sort_key(run: dict[str, Any]) -> str:
value = run.get("updatedAt") or run.get("createdAt") or ""
return str(value)
def prune_trace_runs(
store: dict[str, Any], pinned_trace_ids: set[str] | None = None
) -> None:
runs = store.get("runs", {})
if not isinstance(runs, dict):
store["runs"] = {}
return
pinned_trace_ids = pinned_trace_ids or set()
sorted_items = sorted(
runs.items(),
key=lambda item: trace_sort_key(item[1]) if isinstance(item[1], dict) else "",
reverse=True,
)
unpinned_items = [
item for item in sorted_items if item[0] not in pinned_trace_ids
]
retained_unpinned_ids = {
trace_id
for trace_id, _run in unpinned_items[:TRACE_RUN_LIMIT]
}
retained_ids = pinned_trace_ids | retained_unpinned_ids
store["runs"] = dict(
(trace_id, run)
for trace_id, run in sorted_items
if trace_id in retained_ids
)
def summarize_trace_run(trace_id: str, run: dict[str, Any]) -> dict[str, Any]:
return {
"traceId": trace_id,
"playData": run.get("playData"),
"level": run.get("level"),
"createdAt": run.get("createdAt"),
"updatedAt": run.get("updatedAt"),
"stepCount": run.get("stepCount", 0),
"latestAction": run.get("latestAction"),
"model": run.get("model"),
}
def summarize_record_trace(
record: dict[str, Any], trace_store: dict[str, Any]
) -> dict[str, Any] | None:
trace_id = record.get("traceId")
if not isinstance(trace_id, str) or not trace_id:
return None
runs = trace_store.get("runs", {})
if not isinstance(runs, dict):
return None
run = runs.get(trace_id)
if not isinstance(run, dict):
return None
return {
"traceId": trace_id,
"createdAt": run.get("createdAt"),
"updatedAt": run.get("updatedAt"),
"stepCount": run.get("stepCount", 0),
"latestAction": run.get("latestAction"),
"model": run.get("model"),
}
def find_latest_trace_run(
store: dict[str, Any], play_data: str, level: str
) -> dict[str, Any] | None:
latest: tuple[str, dict[str, Any]] | None = None
runs = store.get("runs", {})
if not isinstance(runs, dict):
return None
for trace_id, run in runs.items():
if not isinstance(run, dict):
continue
if str(run.get("playData")) != play_data or str(run.get("level")) != level:
continue
if latest is None or trace_sort_key(run) > trace_sort_key(latest[1]):
latest = (trace_id, run)
if latest is None:
return None
return summarize_trace_run(*latest)
def append_trace_step(run_id: str, step_trace: dict[str, Any]) -> dict[str, Any]:
now = utc_now()
pinned_trace_ids = load_pinned_trace_ids()
with _trace_store_lock:
store = load_trace_store()
run = store["runs"].get(run_id)
if run is None:
run = {
"id": run_id,
"createdAt": step_trace.get("createdAt", now),
"updatedAt": now,
"playData": step_trace["playData"],
"level": step_trace["level"],
"model": step_trace.get("model"),
"config": step_trace.get("config"),
"steps": [],
}
store["runs"][run_id] = run
step_index = len(run["steps"])
stored_step = dict(step_trace)
stored_step.pop("model", None)
stored_step.pop("config", None)
stored_step["stepIndex"] = step_index
run["steps"].append(stored_step)
run["updatedAt"] = now
run["stepCount"] = len(run["steps"])
run["latestAction"] = stored_step.get("action")
if run.get("model") is None and step_trace.get("model") is not None:
run["model"] = step_trace.get("model")
if run.get("config") is None and step_trace.get("config") is not None:
run["config"] = step_trace.get("config")
prune_trace_runs(store, pinned_trace_ids)
store["updatedAt"] = now
save_trace_store(store)
return store["runs"][run_id]
def finalize_trace_run(
trace_id: str,
*,
play_data: int,
level: int,
model: dict[str, Any] | None,
result: str,
reason: str | None,
final_snapshot: dict[str, Any] | None,
) -> bool:
pinned_trace_ids = load_pinned_trace_ids()
with _trace_store_lock:
store = load_trace_store()
run = store["runs"].get(trace_id)
if not isinstance(run, dict):
now = utc_now()
run = {
"id": trace_id,
"createdAt": now,
"updatedAt": now,
"playData": play_data,
"level": level,
"model": model,
"config": None,
"stepCount": 0,
"latestAction": None,
"steps": [],
}
store["runs"][trace_id] = run
now = utc_now()
run["updatedAt"] = now
run["outcome"] = {
"result": result,
"reason": reason,
"finalState": final_snapshot,
}
store["updatedAt"] = now
prune_trace_runs(store, pinned_trace_ids)
save_trace_store(store)
return True
@app.get("/api/health")
def health():
return jsonify({"ok": True})
@app.get("/api/recordings")
def get_recordings():
with _store_lock:
return jsonify(load_store())
@app.get("/api/recordings/<play_data>/<level>")
def get_recording(play_data: str, level: str):
try:
play_data_key = normalize_id(play_data, "playData")
level_key = normalize_id(level, "level")
except ValueError as exc:
return jsonify({"error": str(exc)}), 400
with _store_lock:
store = load_store()
record = find_latest_recording(store, play_data_key, level_key)
if record is None:
return jsonify({"error": "recording not found"}), 404
return jsonify(record)
@app.get("/api/recordings/<play_data>/<level>/records")
def get_recording_records(play_data: str, level: str):
try:
play_data_key = normalize_id(play_data, "playData")
level_key = normalize_id(level, "level")
except ValueError as exc:
return jsonify({"error": str(exc)}), 400
with _store_lock:
recording_store = load_store()
records = find_recordings(recording_store, play_data_key, level_key)
with _trace_store_lock:
trace_store = load_trace_store()
joined_records = []
for record in records:
joined = dict(record)
joined["trace"] = summarize_record_trace(record, trace_store)
joined_records.append(joined)
return jsonify({"records": joined_records, "count": len(joined_records)})
@app.put("/api/recordings/<play_data>/<level>")
def put_recording(play_data: str, level: str):
try:
play_data_key = normalize_id(play_data, "playData")
level_key = normalize_id(level, "level")
payload = request.get_json(silent=True)
if not isinstance(payload, dict):
raise ValueError("request body must be an object")
demo = validate_demo(payload.get("demo", payload))
source = validate_source(payload.get("source"))
result = validate_result(payload.get("result"), demo)
solver = validate_solver(payload.get("solver"))
trace_id = validate_trace_id(payload.get("traceId", payload.get("traceRef")))
record_id = validate_record_id(payload.get("id"))
final_snapshot = payload.get("finalSnapshot")
if final_snapshot is not None and not isinstance(final_snapshot, dict):
raise ValueError("finalSnapshot must be an object")
if source == "agent" and trace_id is None:
raise ValueError("agent recording requires traceId")
if source == "agent" and record_id is not None and record_id != trace_id:
raise ValueError("agent recording id must match traceId")
except ValueError as exc:
log_event(
LOGGER,
logging.WARNING,
"recording_request_invalid",
play_data=play_data,
level=level,
error=exc,
)
return jsonify({"error": str(exc)}), 400
now = utc_now()
record_id = trace_id if source == "agent" else record_id or f"user:{now}"
record = {
"id": record_id,
"playData": int(play_data_key),
"level": int(level_key),
"savedAt": now,
"source": source,
"result": result,
"pinned": False,
"demo": demo,
}
if solver is not None:
record["solver"] = solver
if trace_id is not None:
record["traceId"] = trace_id
with _store_lock:
try:
store = load_store()
existing_record = store["records"].get(record_id)
if isinstance(existing_record, dict):
record["pinned"] = existing_record.get("pinned") is True
store["version"] = STORE_VERSION
store["updatedAt"] = now
store["records"][record_id] = record
prune_recordings(store)
save_store(store)
except Exception as exc:
log_event(
LOGGER,
logging.ERROR,
"recording_persist_failed",
play_data=play_data_key,
level=level_key,
source=source,
result=result,
error=exc,
)
return jsonify({"error": "failed to persist recording"}), 500
if source == "agent":
finalize_trace_run(
trace_id,
play_data=int(play_data_key),
level=int(level_key),
model=trace_model_summary(solver),
result=result,
reason=(solver or {}).get("failureReason"),
final_snapshot=final_snapshot,
)
log_event(
LOGGER,
logging.INFO,
"agent_recording_saved",
play_data=play_data_key,
level=level_key,
result=result,
reason=(solver or {}).get("failureReason"),
trace_id=trace_id,
model=(solver or {}).get("model"),
)
return jsonify(record)
@app.patch("/api/recordings/<play_data>/<level>/pin")
def set_recording_pin(play_data: str, level: str):
try:
play_data_key = normalize_id(play_data, "playData")
level_key = normalize_id(level, "level")
payload = request.get_json(silent=True)
if not isinstance(payload, dict):
raise ValueError("request body must be an object")
record_id_prefix = validate_record_id(payload.get("recordId"))
if record_id_prefix is None:
raise ValueError("recordId is required")
pinned = payload.get("pinned")
if not isinstance(pinned, bool):
raise ValueError("pinned must be a boolean")
except ValueError as exc:
return jsonify({"error": str(exc)}), 400
with _store_lock:
store = load_store()
record_id, ambiguous = resolve_recording_id(
store, record_id_prefix, play_data_key, level_key
)
if ambiguous:
return jsonify({"error": "recordId prefix is ambiguous"}), 409
if record_id is None:
return jsonify({"error": "recording not found"}), 404
record = store["records"][record_id]
record["pinned"] = pinned
store["updatedAt"] = utc_now()
save_store(store)
return jsonify(
{
"recordId": record_id,
"traceId": record.get("traceId"),
"pinned": pinned,
}
)
@app.post("/api/agent/next-action")
def next_agent_action():
payload = request.get_json(silent=True)
try:
snapshot, history, options = validate_agent_request(payload)
run_id = options.get("runId") or f"trace-{utc_now()}"
plan = plan_next_action(snapshot, history, options)
except AgentRequestError as exc:
log_event(
LOGGER,
logging.WARNING,
"agent_request_invalid",
trace_id=(payload or {}).get("runId"),
error=exc,
)
return jsonify({"error": str(exc)}), 400
except AgentConfigError as exc:
log_event(
LOGGER,
logging.ERROR,
"agent_config_error",
trace_id=(payload or {}).get("runId"),
error=exc,
)
return jsonify({"error": str(exc)}), 503
except AgentExecutionError as exc:
log_event(
LOGGER,
logging.ERROR,
"agent_execution_failed",
trace_id=(payload or {}).get("runId"),
error=exc,
)
return jsonify({"error": "agent execution failed", "detail": str(exc)}), 502
step_trace = dict(plan["trace"])
step_trace["playData"] = snapshot.get("playData", 1)
step_trace["level"] = snapshot.get("level", 1)
step_trace["model"] = trace_model_summary(plan.get("planner"))
step_trace["config"] = trace_config_summary(plan.get("planner"))
try:
run = append_trace_step(run_id, step_trace)
except Exception as exc:
log_event(
LOGGER,
logging.ERROR,
"agent_trace_persist_failed",
trace_id=run_id,
play_data=step_trace["playData"],
level=step_trace["level"],
error=exc,
)
return jsonify({"error": "failed to persist agent trace"}), 500
log_event(
LOGGER,
logging.INFO,
"agent_step_selected",
trace_id=run_id,
play_data=step_trace["playData"],
level=step_trace["level"],
model=plan["planner"].get("model"),
model_profile=plan["planner"].get("modelProfile"),
candidate_id=plan.get("candidateId"),
step_count=run.get("stepCount"),
)
return jsonify(
{
"action": plan["action"],
"planner": plan["planner"],
"traceId": run_id,
"stepCount": run.get("stepCount"),
"candidateId": plan.get("candidateId"),
}
)
@app.get("/api/agent/traces/<trace_id>")
def get_agent_trace(trace_id: str):
with _trace_store_lock:
store = load_trace_store()
run = store["runs"].get(trace_id)
if run is None:
return jsonify({"error": "trace not found"}), 404
return jsonify(run)
@app.get("/api/agent/runs/<play_data>/<level>")
def get_agent_run(play_data: str, level: str):
try:
play_data_key = normalize_id(play_data, "playData")
level_key = normalize_id(level, "level")
except ValueError as exc:
return jsonify({"error": str(exc)}), 400
with _trace_store_lock:
trace_store = load_trace_store()
latest_run = find_latest_trace_run(trace_store, play_data_key, level_key)
with _store_lock:
recording_store = load_store()
recording = find_latest_recording(recording_store, play_data_key, level_key)
if latest_run is None and recording is None:
return jsonify({"error": "agent run not found"}), 404
return jsonify({"latestRun": latest_run, "recording": recording})
@app.delete("/api/recordings/<play_data>/<level>")
def delete_recording(play_data: str, level: str):
try:
play_data_key = normalize_id(play_data, "playData")
level_key = normalize_id(level, "level")
except ValueError as exc:
return jsonify({"error": str(exc)}), 400
selected_trace_id = request.args.get("traceId") or None
selected_record_id = request.args.get("recordId") or selected_trace_id
deleted_trace_id = None
latest_record = None
with _store_lock:
store = load_store()
records = store.get("records", {})
existed = False
if isinstance(records, dict):
if selected_record_id:
record_key = selected_record_id
candidate = records.get(record_key)
record = (
candidate
if isinstance(candidate, dict)
and str(candidate.get("playData")) == play_data_key
and str(candidate.get("level")) == level_key
else None
)
else:
record = find_latest_recording(store, play_data_key, level_key)
record_key = record.get("id") if isinstance(record, dict) else None
if isinstance(record, dict) and record.get("pinned") is True:
return (
jsonify(
{
"error": "pinned recording must be unpinned before deletion",
"pinned": True,
"recordId": record.get("id"),
"traceId": record.get("traceId"),
}
),
409,
)
if record_key and isinstance(record, dict):
record = records.pop(str(record_key), None)
existed = isinstance(record, dict)
deleted_trace_id = record.get("traceId") if existed else selected_trace_id
prune_recordings(store)
latest_record = find_latest_recording(store, play_data_key, level_key)
store["updatedAt"] = utc_now()
save_store(store)
trace_deleted = delete_trace_run(deleted_trace_id) if existed else False
return jsonify(
{
"deleted": existed,
"traceDeleted": trace_deleted,
"traceId": deleted_trace_id,
"latestRecord": latest_record,
}
)
if __name__ == "__main__":
app.run(
host="localhost",
port=8485,
use_reloader=True,
use_debugger=False,
)