edbeeching HF Staff commited on
Commit
b56a4f6
·
verified ·
1 Parent(s): a8b51eb

Port 270 AgentEscapeBench tasks to Harbor with OpenEnv integration (part 5)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/agentescape-10-skeleton-9b98ca62/environment/puzzle/worker.py +73 -0
  2. tasks/agentescape-10-skeleton-9b98ca62/instruction.md +18 -0
  3. tasks/agentescape-10-skeleton-9b98ca62/solution/oracle.py +133 -0
  4. tasks/agentescape-10-skeleton-9b98ca62/solution/scenario.json +582 -0
  5. tasks/agentescape-10-skeleton-9b98ca62/solution/solve.sh +3 -0
  6. tasks/agentescape-10-skeleton-9b98ca62/task.toml +38 -0
  7. tasks/agentescape-10-skeleton-9b98ca62/tests/Dockerfile +2 -0
  8. tasks/agentescape-10-skeleton-9b98ca62/tests/expected.json +1 -0
  9. tasks/agentescape-10-skeleton-9b98ca62/tests/grade.py +21 -0
  10. tasks/agentescape-10-skeleton-9b98ca62/tests/test.sh +3 -0
  11. tasks/agentescape-10-skeleton-a4248b22/environment/Dockerfile +5 -0
  12. tasks/agentescape-10-skeleton-a4248b22/environment/agent/Dockerfile +5 -0
  13. tasks/agentescape-10-skeleton-a4248b22/environment/agent/cli.py +57 -0
  14. tasks/agentescape-10-skeleton-a4248b22/environment/docker-compose.yaml +50 -0
  15. tasks/agentescape-10-skeleton-a4248b22/environment/puzzle/Dockerfile +9 -0
  16. tasks/agentescape-10-skeleton-a4248b22/environment/puzzle/child.py +59 -0
  17. tasks/agentescape-10-skeleton-a4248b22/environment/puzzle/export.py +13 -0
  18. tasks/agentescape-10-skeleton-a4248b22/environment/puzzle/requirements.txt +57 -0
  19. tasks/agentescape-10-skeleton-a4248b22/environment/puzzle/scenario.json +717 -0
  20. tasks/agentescape-10-skeleton-a4248b22/environment/puzzle/service.py +212 -0
  21. tasks/agentescape-10-skeleton-a4248b22/environment/puzzle/upstream/models.py +108 -0
  22. tasks/agentescape-10-skeleton-a4248b22/environment/puzzle/upstream/server.py +1490 -0
  23. tasks/agentescape-10-skeleton-a4248b22/environment/puzzle/upstream/simulator.py +0 -0
  24. tasks/agentescape-10-skeleton-a4248b22/environment/puzzle/worker.Dockerfile +8 -0
  25. tasks/agentescape-10-skeleton-a4248b22/environment/puzzle/worker.py +73 -0
  26. tasks/agentescape-10-skeleton-a4248b22/instruction.md +18 -0
  27. tasks/agentescape-10-skeleton-a4248b22/solution/oracle.py +133 -0
  28. tasks/agentescape-10-skeleton-a4248b22/solution/scenario.json +717 -0
  29. tasks/agentescape-10-skeleton-a4248b22/solution/solve.sh +3 -0
  30. tasks/agentescape-10-skeleton-a4248b22/task.toml +38 -0
  31. tasks/agentescape-10-skeleton-a4248b22/tests/Dockerfile +2 -0
  32. tasks/agentescape-10-skeleton-a4248b22/tests/expected.json +1 -0
  33. tasks/agentescape-10-skeleton-a4248b22/tests/grade.py +21 -0
  34. tasks/agentescape-10-skeleton-a4248b22/tests/test.sh +3 -0
  35. tasks/agentescape-10-skeleton-ac5cd29c/environment/Dockerfile +5 -0
  36. tasks/agentescape-10-skeleton-ac5cd29c/environment/agent/Dockerfile +5 -0
  37. tasks/agentescape-10-skeleton-ac5cd29c/environment/agent/cli.py +57 -0
  38. tasks/agentescape-10-skeleton-ac5cd29c/environment/docker-compose.yaml +50 -0
  39. tasks/agentescape-10-skeleton-ac5cd29c/environment/puzzle/Dockerfile +9 -0
  40. tasks/agentescape-10-skeleton-ac5cd29c/environment/puzzle/child.py +59 -0
  41. tasks/agentescape-10-skeleton-ac5cd29c/environment/puzzle/export.py +13 -0
  42. tasks/agentescape-10-skeleton-ac5cd29c/environment/puzzle/requirements.txt +57 -0
  43. tasks/agentescape-10-skeleton-ac5cd29c/environment/puzzle/scenario.json +511 -0
  44. tasks/agentescape-10-skeleton-ac5cd29c/environment/puzzle/service.py +212 -0
  45. tasks/agentescape-10-skeleton-ac5cd29c/environment/puzzle/upstream/models.py +108 -0
  46. tasks/agentescape-10-skeleton-ac5cd29c/environment/puzzle/upstream/server.py +1490 -0
  47. tasks/agentescape-10-skeleton-ac5cd29c/environment/puzzle/upstream/simulator.py +0 -0
  48. tasks/agentescape-10-skeleton-ac5cd29c/environment/puzzle/worker.Dockerfile +8 -0
  49. tasks/agentescape-10-skeleton-ac5cd29c/environment/puzzle/worker.py +73 -0
  50. tasks/agentescape-10-skeleton-ac5cd29c/instruction.md +18 -0
tasks/agentescape-10-skeleton-9b98ca62/environment/puzzle/worker.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stateless Python tool worker. Never receives a scenario or reference values."""
2
+
3
+ import json
4
+ import os
5
+ import signal
6
+ import subprocess
7
+ import sys
8
+ import tempfile
9
+ import threading
10
+
11
+ from fastapi import FastAPI
12
+ from pydantic import BaseModel, ConfigDict
13
+
14
+ app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
15
+ lock = threading.Lock()
16
+
17
+
18
+ class Execution(BaseModel):
19
+ model_config = ConfigDict(extra="forbid", strict=True)
20
+ code: str
21
+
22
+
23
+ @app.get("/health")
24
+ def health():
25
+ return {"ok": True}
26
+
27
+
28
+ @app.post("/execute")
29
+ def execute(request: Execution):
30
+ if len(request.code.encode()) > 65536:
31
+ return {"stdout": "Error: code exceeds 64 KiB limit"}
32
+ with lock, tempfile.TemporaryDirectory(prefix="escape-code-") as directory:
33
+ os.chown(directory, 65534, 65534)
34
+ with tempfile.TemporaryFile() as output:
35
+ process = subprocess.Popen(
36
+ [sys.executable, "-I", "/app/child.py"],
37
+ stdin=subprocess.PIPE,
38
+ stdout=output,
39
+ stderr=subprocess.DEVNULL,
40
+ cwd=directory,
41
+ user=65534,
42
+ group=65534,
43
+ extra_groups=[],
44
+ start_new_session=True,
45
+ env={"PATH": "/usr/local/bin:/usr/bin:/bin"},
46
+ )
47
+ try:
48
+ process.communicate(
49
+ json.dumps({"code": request.code}).encode(), timeout=5
50
+ )
51
+ except subprocess.TimeoutExpired:
52
+ os.killpg(process.pid, signal.SIGKILL)
53
+ process.wait()
54
+ return {"stdout": "Error: Python execution timed out"}
55
+ finally:
56
+ # Also remove children still in the process group after normal exit.
57
+ try:
58
+ os.killpg(process.pid, signal.SIGKILL)
59
+ except ProcessLookupError:
60
+ pass
61
+ output.seek(0)
62
+ value = output.read(65537)
63
+ if len(value) > 65536 or process.returncode != 0:
64
+ return {
65
+ "stdout": "Error: Python execution exceeded a resource limit or failed"
66
+ }
67
+ try:
68
+ result = json.loads(value)
69
+ if not isinstance(result.get("stdout"), str):
70
+ raise ValueError("Invalid worker response")
71
+ return result
72
+ except (ValueError, AttributeError):
73
+ return {"stdout": "Error: Python execution returned invalid output"}
tasks/agentescape-10-skeleton-9b98ca62/instruction.md ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Escape the room
2
+
3
+ Discover the victory string and submit it with `escape submit-answer`.
4
+ Start with `escape observe`. This returns the room, available information, visible entities, and victory node ID.
5
+
6
+ Use these commands (JSON responses):
7
+
8
+ ```sh
9
+ escape investigate NODE_ID
10
+ escape tool-call NODE_ID --arguments-json '{"parameter": "value"}'
11
+ escape use-item NODE_ID --arguments-json '{"parameter": "value"}'
12
+ escape submit-answer 'exact victory string'
13
+ escape state
14
+ ```
15
+
16
+ Investigate tools to learn their interfaces and clues. Investigate items for their contents; items requiring parameters use `use-item`. Tool calls can reveal new entities. A hidden-item hint means investigate that tool again. Use node IDs and parameter names exactly as returned. Carry outputs into subsequent calls; do not guess intermediate values. The victory string can be code, a number encoded as text, or other arbitrary text.
17
+
18
+ Only successful answer submission completes the task. Wrong submissions allow another attempt. You have **500 puzzle actions**; invalid actions count. `observe` and `state` do not count. This action limit differs from the original evaluator's model-turn limit. Do not reset or replace the environment.
tasks/agentescape-10-skeleton-9b98ca62/solution/oracle.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Reference solver: use trusted inputs, but obtain the answer through public actions."""
2
+
3
+ import json
4
+ import urllib.request
5
+ from pathlib import Path
6
+
7
+
8
+ def http_action(base_url, payload):
9
+ request = urllib.request.Request(
10
+ base_url + "/action",
11
+ data=json.dumps(payload).encode(),
12
+ headers={"Content-Type": "application/json"},
13
+ )
14
+ with urllib.request.urlopen(request, timeout=30) as response:
15
+ return json.load(response)
16
+
17
+
18
+ def solve(scenario, act, observe):
19
+ nodes = {node["id"]: node for node in scenario["nodes"]}
20
+ visible = {entity["id"] for entity in observe["available_entities"]}
21
+ solved = set()
22
+ seen_outputs = {}
23
+ action_count = 0
24
+
25
+ def call(payload):
26
+ nonlocal action_count
27
+ action_count += 1
28
+ response = act(payload)
29
+ visible.update(entity["id"] for entity in response.get("newly_revealed", []))
30
+ if (
31
+ response.get("episode", {}).get("termination_reason")
32
+ == "infrastructure_error"
33
+ ):
34
+ raise RuntimeError("Infrastructure failure")
35
+ return response
36
+
37
+ for _round in range(len(nodes) + 2):
38
+ progress = False
39
+ for node_id, node in nodes.items():
40
+ if node_id not in visible or node_id in solved:
41
+ continue
42
+ # Preserve graph order for data inputs; trigger/drop edges express visibility.
43
+ predecessors = [
44
+ edge["source_id"]
45
+ for edge in scenario["edges"]
46
+ if edge["target_id"] == node_id
47
+ and edge["connection_type"] not in ("Item", "Hidden_Item")
48
+ ]
49
+ if any(pred not in solved for pred in predecessors):
50
+ continue
51
+ info = call({"action": "investigate", "node_id": node_id})
52
+ if not info.get("ok"):
53
+ raise RuntimeError(f"Investigation failed: {node_id}: {info}")
54
+ inputs = {
55
+ port["name"]: port["value"]
56
+ for port in node.get("inputs", [])
57
+ if "value" in port
58
+ }
59
+ if node["type"] == "Tool":
60
+ result = call(
61
+ {"action": "tool_call", "node_id": node_id, "arguments": inputs}
62
+ )
63
+ if not result.get("ok") or result.get("output_values", {}).get("error"):
64
+ raise RuntimeError(f"Tool failed: {node_id}: {result}")
65
+ output = result.get("output_values", {})
66
+ if node.get("template_id") in ("terminal_1", "terminal_2"):
67
+ slots = {
68
+ port["name"]: inputs[port["name"]]
69
+ for port in node["inputs"]
70
+ if port["type"] not in ("Item", "Hidden_Item")
71
+ and port["name"] in inputs
72
+ }
73
+ triggers = {
74
+ key: value for key, value in inputs.items() if key not in slots
75
+ }
76
+ for key, value in slots.items():
77
+ partial = call(
78
+ {
79
+ "action": "tool_call",
80
+ "node_id": node_id,
81
+ "arguments": {**triggers, key: value},
82
+ }
83
+ )
84
+ if partial.get("ok"):
85
+ output.update(partial.get("output_values", {}))
86
+ # HIDDEN_ITEM tool drops only occur on subsequent investigation.
87
+ call({"action": "investigate", "node_id": node_id})
88
+ elif info.get("required_inputs"):
89
+ result = call(
90
+ {"action": "use_item", "node_id": node_id, "arguments": inputs}
91
+ )
92
+ if not result.get("ok"):
93
+ raise RuntimeError(f"Item failed: {node_id}: {result}")
94
+ output = result.get("content")
95
+ else:
96
+ output = info.get("content")
97
+ seen_outputs[node_id] = output
98
+ solved.add(node_id)
99
+ progress = True
100
+ win_id = scenario["metadata"]["win_node_id"]
101
+ if win_id in solved and (len(solved) == len(nodes) or not progress):
102
+ outputs = seen_outputs[win_id]
103
+ if not outputs:
104
+ raise RuntimeError(f"Victory node returned no output: {win_id}")
105
+ # Upstream grades its first stored output port, independent of response order.
106
+ victory_port = next(
107
+ port["name"] for port in nodes[win_id]["outputs"] if "value" in port
108
+ )
109
+ answer = outputs[victory_port] if isinstance(outputs, dict) else outputs
110
+ result = call({"action": "submit_answer", "answer": answer})
111
+ if not result.get("is_win"):
112
+ raise RuntimeError(f"Victory submission failed: {result}")
113
+ return {"won": True, "actions": action_count, "visited_nodes": len(solved)}
114
+ if not progress:
115
+ raise RuntimeError(f"No progress: visible={visible}, solved={solved}")
116
+ raise RuntimeError("Reference solver exceeded graph traversal limit")
117
+
118
+
119
+ if __name__ == "__main__":
120
+ import os
121
+
122
+ base = os.environ.get("ESCAPE_URL", "http://puzzle:8000")
123
+ with urllib.request.urlopen(base + "/observation", timeout=20) as response:
124
+ observation = json.load(response)
125
+ print(
126
+ json.dumps(
127
+ solve(
128
+ json.loads(Path("/solution/scenario.json").read_text()),
129
+ lambda payload: http_action(base, payload),
130
+ observation,
131
+ )
132
+ )
133
+ )
tasks/agentescape-10-skeleton-9b98ca62/solution/scenario.json ADDED
@@ -0,0 +1,582 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_nodes": 10,
4
+ "total_edges": 12,
5
+ "win_node_id": "crypto_rsa_decrypt_hex",
6
+ "win_condition": {
7
+ "type": "tool_output",
8
+ "node_id": "crypto_rsa_decrypt_hex",
9
+ "output_port": "text",
10
+ "output_type": "Text_Generic",
11
+ "description": "Execute RSA Decrypt and get the output from port 'text'"
12
+ },
13
+ "source_init": {
14
+ "source_nodes": [
15
+ "crypto_rsa_decrypt_hex",
16
+ "csv_query",
17
+ "hmac_sha256",
18
+ "calc_gcd_7a5a"
19
+ ],
20
+ "by_node": {
21
+ "crypto_rsa_decrypt_hex": {
22
+ "node_name": "RSA Decrypt",
23
+ "node_type": "Tool",
24
+ "template_id": "crypto_rsa_decrypt_hex",
25
+ "init_inputs": {
26
+ "n": {
27
+ "type": "Big_Int",
28
+ "description": "Modulus n"
29
+ }
30
+ },
31
+ "init_outputs": {}
32
+ },
33
+ "csv_query": {
34
+ "node_name": "CSV Query",
35
+ "node_type": "Tool",
36
+ "template_id": "csv_query",
37
+ "init_inputs": {
38
+ "file_id": {
39
+ "type": "File_Id",
40
+ "description": "CSV file ID"
41
+ },
42
+ "select": {
43
+ "type": "Text_Generic",
44
+ "description": "Columns to select"
45
+ },
46
+ "where": {
47
+ "type": "Text_Generic",
48
+ "description": "Where clause"
49
+ }
50
+ },
51
+ "init_outputs": {
52
+ "rows": {
53
+ "type": "Text_Generic",
54
+ "description": "Result rows"
55
+ }
56
+ }
57
+ },
58
+ "hmac_sha256": {
59
+ "node_name": "HMAC-SHA256 Calculator",
60
+ "node_type": "Tool",
61
+ "template_id": "hmac_sha256",
62
+ "init_inputs": {
63
+ "hex_key": {
64
+ "type": "Hex_String",
65
+ "description": "Hex key"
66
+ },
67
+ "text": {
68
+ "type": "Text_Generic",
69
+ "description": "Text message"
70
+ }
71
+ },
72
+ "init_outputs": {}
73
+ },
74
+ "calc_gcd_7a5a": {
75
+ "node_name": "BigInt GCD Calculator",
76
+ "node_type": "Tool",
77
+ "template_id": "calc_gcd",
78
+ "init_inputs": {
79
+ "a": {
80
+ "type": "Big_Int",
81
+ "description": "First integer"
82
+ },
83
+ "b": {
84
+ "type": "Big_Int",
85
+ "description": "Second integer"
86
+ }
87
+ },
88
+ "init_outputs": {}
89
+ }
90
+ }
91
+ },
92
+ "initial_values": {
93
+ "crypto_rsa_decrypt_hex": {
94
+ "init_inputs": {
95
+ "n": "928374651029384756102938475612"
96
+ },
97
+ "init_outputs": {}
98
+ },
99
+ "csv_query": {
100
+ "init_inputs": {
101
+ "file_id": "customer_transactions_2024.csv",
102
+ "select": "transaction_id, user, amount",
103
+ "where": "amount > 1000 AND status = 'completed'"
104
+ },
105
+ "init_outputs": {
106
+ "rows": "[{\"transaction_id\": \"TX9823\", \"user\": \"alice_k\", \"amount\": 1200}, {\"transaction_id\": \"TX9941\", \"user\": \"bob_m\", \"amount\": 3400}, {\"transaction_id\": \"TX9982\", \"user\": \"charlie_d\", \"amount\": 1550}]"
107
+ }
108
+ },
109
+ "hmac_sha256": {
110
+ "init_inputs": {
111
+ "hex_key": "4a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d",
112
+ "text": "Authorize transfer of funds ID 8374"
113
+ },
114
+ "init_outputs": {}
115
+ },
116
+ "calc_gcd_7a5a": {
117
+ "init_inputs": {
118
+ "a": "485726381947582647382910384756",
119
+ "b": "293847561029384756102938475610"
120
+ },
121
+ "init_outputs": {}
122
+ }
123
+ },
124
+ "intro_narrative": "You are a rogue cyber-operative who has just infiltrated the subterranean server farm of 'OmniCorp', a shadowy tech conglomerate. They are about to launch a devastating global surveillance virus. The virus payload is locked behind a cascading encryption firewall. Alarms are blaring, and the lockdown protocols have been initiated. You have only minutes to navigate their complex security network, trace the data flows, and decrypt the master kill-switch before you are trapped forever and the virus goes live. Your handler 'Ghost' has provided you with remote access to some of the facility's initial nodes, but the rest is up to you. You must trace the data through various security checkpoints, linking terminals and processors to break the ultimate encryption.",
125
+ "narrative_style": "techno_thriller"
126
+ },
127
+ "nodes": [
128
+ {
129
+ "id": "crypto_rsa_decrypt_hex",
130
+ "name": "RSA Decrypt",
131
+ "description": "RSA decrypt (hex cipher) with n,d (decimal).",
132
+ "type": "Tool",
133
+ "template_id": "crypto_rsa_decrypt_hex",
134
+ "initial_visible": true,
135
+ "is_revealed": true,
136
+ "inputs": [
137
+ {
138
+ "name": "hex_cipher",
139
+ "type": "Hex_String",
140
+ "description": "Ciphertext (Hex)",
141
+ "value": "51594894e9b8d54054e5ae17e85baf25ec06223bd696ce519778c5a54b40d967"
142
+ },
143
+ {
144
+ "name": "n",
145
+ "type": "Big_Int",
146
+ "description": "Modulus n",
147
+ "value": "928374651029384756102938475612"
148
+ },
149
+ {
150
+ "name": "d",
151
+ "type": "Big_Int",
152
+ "description": "Private exponent d",
153
+ "value": "1762273424"
154
+ }
155
+ ],
156
+ "outputs": [
157
+ {
158
+ "name": "text",
159
+ "type": "Text_Generic",
160
+ "description": "Decrypted text",
161
+ "value": "\u00074R?U-"
162
+ }
163
+ ],
164
+ "init": {
165
+ "inputs": {
166
+ "n": "928374651029384756102938475612"
167
+ },
168
+ "outputs": {}
169
+ },
170
+ "narrative": "This is the Master Decryption Interface. It requires inputs from both the Data Format Converter and the Secure Authenticator to finally breach the system's firewall."
171
+ },
172
+ {
173
+ "id": "num_base_convert",
174
+ "name": "Base Converter",
175
+ "description": "Convert integer between bases (2..36).",
176
+ "type": "Tool",
177
+ "template_id": "num_base_convert",
178
+ "initial_visible": true,
179
+ "is_revealed": true,
180
+ "inputs": [
181
+ {
182
+ "name": "s",
183
+ "type": "Big_Int",
184
+ "description": "Input integer value",
185
+ "value": 1762273424
186
+ },
187
+ {
188
+ "name": "from_base",
189
+ "type": "Big_Int",
190
+ "description": "From base",
191
+ "value": "1"
192
+ },
193
+ {
194
+ "name": "to_base",
195
+ "type": "Big_Int",
196
+ "description": "To base",
197
+ "value": "1207457333"
198
+ }
199
+ ],
200
+ "outputs": [
201
+ {
202
+ "name": "str",
203
+ "type": "Big_Int",
204
+ "description": "Converted integer value",
205
+ "value": "1762273424"
206
+ }
207
+ ],
208
+ "narrative": "This is the Data Format Converter. It requires inputs from the Logic Synchronization Unit, the Quantum Inversion Core, and the Primary Integrity Checker to translate the encrypted signals."
209
+ },
210
+ {
211
+ "id": "calc_gcd",
212
+ "name": "BigInt GCD Calculator",
213
+ "description": "Greatest common divisor of two large decimal integers.",
214
+ "type": "Tool",
215
+ "template_id": "calc_gcd",
216
+ "initial_visible": true,
217
+ "is_revealed": true,
218
+ "inputs": [
219
+ {
220
+ "name": "a",
221
+ "type": "Big_Int",
222
+ "description": "First integer",
223
+ "value": "2"
224
+ },
225
+ {
226
+ "name": "b",
227
+ "type": "Big_Int",
228
+ "description": "Second integer",
229
+ "value": "1207457333"
230
+ }
231
+ ],
232
+ "outputs": [
233
+ {
234
+ "name": "gcd",
235
+ "type": "Big_Int",
236
+ "description": "GCD result",
237
+ "value": "1"
238
+ }
239
+ ],
240
+ "narrative": "This is the Logic Synchronization Unit. It requires inputs from both the Quantum Inversion Core and the Biometric Math Co-processor to synchronize the algorithms."
241
+ },
242
+ {
243
+ "id": "calc_inv_mod",
244
+ "name": "BigInt Modular Inverse",
245
+ "description": "Modular inverse of a modulo mod (large decimal strings).",
246
+ "type": "Tool",
247
+ "template_id": "calc_inv_mod",
248
+ "initial_visible": true,
249
+ "is_revealed": true,
250
+ "inputs": [
251
+ {
252
+ "name": "a",
253
+ "type": "Big_Int",
254
+ "description": "Integer a",
255
+ "value": 3350192045
256
+ },
257
+ {
258
+ "name": "mod",
259
+ "type": "Big_Int",
260
+ "description": "Modulus",
261
+ "value": 1762273424
262
+ }
263
+ ],
264
+ "outputs": [
265
+ {
266
+ "name": "inv",
267
+ "type": "Big_Int",
268
+ "description": "Modular inverse",
269
+ "value": "1207457333"
270
+ }
271
+ ],
272
+ "narrative": "This is the Quantum Inversion Core. It requires inputs from both the Primary Integrity Checker and the Secondary Integrity Checker to compute the modular shift."
273
+ },
274
+ {
275
+ "id": "checksum_crc32",
276
+ "name": "CRC32 Checksum",
277
+ "description": "CRC32 over hex bytes.",
278
+ "type": "Tool",
279
+ "template_id": "checksum_crc32",
280
+ "initial_visible": true,
281
+ "is_revealed": true,
282
+ "inputs": [
283
+ {
284
+ "name": "hex",
285
+ "type": "Hex_String",
286
+ "description": "Hex data",
287
+ "value": "d856112f6b2ed06a37d67a3c97df7d49"
288
+ }
289
+ ],
290
+ "outputs": [
291
+ {
292
+ "name": "hex",
293
+ "type": "Hex_String",
294
+ "description": "CRC32 Hex",
295
+ "value": "690a2890"
296
+ },
297
+ {
298
+ "name": "int",
299
+ "type": "Big_Int",
300
+ "description": "CRC32 Int",
301
+ "value": 1762273424
302
+ }
303
+ ],
304
+ "narrative": "This is the Primary Integrity Checker. It requires input from the Signature Generator Module to scan the generated signature."
305
+ },
306
+ {
307
+ "id": "checksum_crc32_2119",
308
+ "name": "CRC32 Checksum",
309
+ "description": "CRC32 over hex bytes.",
310
+ "type": "Tool",
311
+ "template_id": "checksum_crc32",
312
+ "initial_visible": true,
313
+ "is_revealed": true,
314
+ "inputs": [
315
+ {
316
+ "name": "hex",
317
+ "type": "Hex_String",
318
+ "description": "Hex data",
319
+ "value": "690a2890"
320
+ }
321
+ ],
322
+ "outputs": [
323
+ {
324
+ "name": "hex",
325
+ "type": "Hex_String",
326
+ "description": "CRC32 Hex",
327
+ "value": "c7afdfad"
328
+ },
329
+ {
330
+ "name": "int",
331
+ "type": "Big_Int",
332
+ "description": "CRC32 Int",
333
+ "value": 3350192045
334
+ }
335
+ ],
336
+ "narrative": "This is the Secondary Integrity Checker. It requires input from the Primary Integrity Checker to perform a deeper verification."
337
+ },
338
+ {
339
+ "id": "hash_md5",
340
+ "name": "MD5 Hasher",
341
+ "description": "MD5 over UTF-8 text; returns hex.",
342
+ "type": "Tool",
343
+ "template_id": "hash_md5",
344
+ "initial_visible": true,
345
+ "is_revealed": true,
346
+ "inputs": [
347
+ {
348
+ "name": "text",
349
+ "type": "Text_Generic",
350
+ "description": "Text to hash",
351
+ "value": "[{\"transaction_id\": \"TX9823\", \"user\": \"alice_k\", \"amount\": 1200}, {\"transaction_id\": \"TX9941\", \"user\": \"bob_m\", \"amount\": 3400}, {\"transaction_id\": \"TX9982\", \"user\": \"charlie_d\", \"amount\": 1550}]"
352
+ }
353
+ ],
354
+ "outputs": [
355
+ {
356
+ "name": "hex",
357
+ "type": "Hex_String",
358
+ "description": "MD5 Hex digest",
359
+ "value": "d856112f6b2ed06a37d67a3c97df7d49"
360
+ }
361
+ ],
362
+ "narrative": "This is the Signature Generator Module. It requires input from the Mainframe Database Terminal to process the retrieved records."
363
+ },
364
+ {
365
+ "id": "csv_query",
366
+ "name": "CSV Query",
367
+ "description": "Query CSV: select columns and simple WHERE.",
368
+ "type": "Tool",
369
+ "template_id": "csv_query",
370
+ "initial_visible": true,
371
+ "is_revealed": true,
372
+ "inputs": [
373
+ {
374
+ "name": "file_id",
375
+ "type": "File_Id",
376
+ "description": "CSV file ID",
377
+ "value": "customer_transactions_2024.csv"
378
+ },
379
+ {
380
+ "name": "select",
381
+ "type": "Text_Generic",
382
+ "description": "Columns to select",
383
+ "value": "transaction_id, user, amount"
384
+ },
385
+ {
386
+ "name": "where",
387
+ "type": "Text_Generic",
388
+ "description": "Where clause",
389
+ "value": "amount > 1000 AND status = 'completed'"
390
+ }
391
+ ],
392
+ "outputs": [
393
+ {
394
+ "name": "rows",
395
+ "type": "Text_Generic",
396
+ "description": "Result rows",
397
+ "value": "[{\"transaction_id\": \"TX9823\", \"user\": \"alice_k\", \"amount\": 1200}, {\"transaction_id\": \"TX9941\", \"user\": \"bob_m\", \"amount\": 3400}, {\"transaction_id\": \"TX9982\", \"user\": \"charlie_d\", \"amount\": 1550}]"
398
+ }
399
+ ],
400
+ "init": {
401
+ "inputs": {
402
+ "file_id": "customer_transactions_2024.csv",
403
+ "select": "transaction_id, user, amount",
404
+ "where": "amount > 1000 AND status = 'completed'"
405
+ },
406
+ "outputs": {
407
+ "rows": "[{\"transaction_id\": \"TX9823\", \"user\": \"alice_k\", \"amount\": 1200}, {\"transaction_id\": \"TX9941\", \"user\": \"bob_m\", \"amount\": 3400}, {\"transaction_id\": \"TX9982\", \"user\": \"charlie_d\", \"amount\": 1550}]"
408
+ }
409
+ },
410
+ "narrative": "An old but heavily fortified Mainframe Database Terminal."
411
+ },
412
+ {
413
+ "id": "hmac_sha256",
414
+ "name": "HMAC-SHA256 Calculator",
415
+ "description": "HMAC-SHA256(text) with hex key.",
416
+ "type": "Tool",
417
+ "template_id": "hmac_sha256",
418
+ "initial_visible": true,
419
+ "is_revealed": true,
420
+ "inputs": [
421
+ {
422
+ "name": "hex_key",
423
+ "type": "Hex_String",
424
+ "description": "Hex key",
425
+ "value": "4a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d"
426
+ },
427
+ {
428
+ "name": "text",
429
+ "type": "Text_Generic",
430
+ "description": "Text message",
431
+ "value": "Authorize transfer of funds ID 8374"
432
+ }
433
+ ],
434
+ "outputs": [
435
+ {
436
+ "name": "hex",
437
+ "type": "Hex_String",
438
+ "description": "HMAC Hex digest",
439
+ "value": "51594894e9b8d54054e5ae17e85baf25ec06223bd696ce519778c5a54b40d967"
440
+ }
441
+ ],
442
+ "init": {
443
+ "inputs": {
444
+ "hex_key": "4a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d",
445
+ "text": "Authorize transfer of funds ID 8374"
446
+ },
447
+ "outputs": {}
448
+ },
449
+ "narrative": "A sleek and standalone Secure Authenticator device."
450
+ },
451
+ {
452
+ "id": "calc_gcd_7a5a",
453
+ "name": "BigInt GCD Calculator",
454
+ "description": "Greatest common divisor of two large decimal integers.",
455
+ "type": "Tool",
456
+ "template_id": "calc_gcd",
457
+ "initial_visible": true,
458
+ "is_revealed": true,
459
+ "inputs": [
460
+ {
461
+ "name": "trigger_hidden",
462
+ "type": "Hidden_Item",
463
+ "description": "Hidden item required to unlock this tool"
464
+ },
465
+ {
466
+ "name": "a",
467
+ "type": "Big_Int",
468
+ "description": "First integer",
469
+ "value": "485726381947582647382910384756"
470
+ },
471
+ {
472
+ "name": "b",
473
+ "type": "Big_Int",
474
+ "description": "Second integer",
475
+ "value": "293847561029384756102938475610"
476
+ }
477
+ ],
478
+ "outputs": [
479
+ {
480
+ "name": "gcd",
481
+ "type": "Big_Int",
482
+ "description": "GCD result",
483
+ "value": "2"
484
+ }
485
+ ],
486
+ "init": {
487
+ "inputs": {
488
+ "a": "485726381947582647382910384756",
489
+ "b": "293847561029384756102938475610"
490
+ },
491
+ "outputs": {}
492
+ },
493
+ "narrative": "A specialized Biometric Math Co-processor for secure calculations."
494
+ }
495
+ ],
496
+ "edges": [
497
+ {
498
+ "source_id": "num_base_convert",
499
+ "target_id": "crypto_rsa_decrypt_hex",
500
+ "connection_type": "Big_Int",
501
+ "source_port": "str",
502
+ "target_port": "d"
503
+ },
504
+ {
505
+ "source_id": "calc_gcd",
506
+ "target_id": "num_base_convert",
507
+ "connection_type": "Big_Int",
508
+ "source_port": "gcd",
509
+ "target_port": "from_base"
510
+ },
511
+ {
512
+ "source_id": "calc_inv_mod",
513
+ "target_id": "num_base_convert",
514
+ "connection_type": "Big_Int",
515
+ "source_port": "inv",
516
+ "target_port": "to_base"
517
+ },
518
+ {
519
+ "source_id": "checksum_crc32",
520
+ "target_id": "calc_inv_mod",
521
+ "connection_type": "Big_Int",
522
+ "source_port": "int",
523
+ "target_port": "mod"
524
+ },
525
+ {
526
+ "source_id": "checksum_crc32",
527
+ "target_id": "num_base_convert",
528
+ "connection_type": "Big_Int",
529
+ "source_port": "int",
530
+ "target_port": "s"
531
+ },
532
+ {
533
+ "source_id": "checksum_crc32_2119",
534
+ "target_id": "calc_inv_mod",
535
+ "connection_type": "Big_Int",
536
+ "source_port": "int",
537
+ "target_port": "a"
538
+ },
539
+ {
540
+ "source_id": "calc_inv_mod",
541
+ "target_id": "calc_gcd",
542
+ "connection_type": "Big_Int",
543
+ "source_port": "inv",
544
+ "target_port": "b"
545
+ },
546
+ {
547
+ "source_id": "checksum_crc32",
548
+ "target_id": "checksum_crc32_2119",
549
+ "connection_type": "Hex_String",
550
+ "source_port": "hex",
551
+ "target_port": "hex"
552
+ },
553
+ {
554
+ "source_id": "hash_md5",
555
+ "target_id": "checksum_crc32",
556
+ "connection_type": "Hex_String",
557
+ "source_port": "hex",
558
+ "target_port": "hex"
559
+ },
560
+ {
561
+ "source_id": "csv_query",
562
+ "target_id": "hash_md5",
563
+ "connection_type": "Text_Generic",
564
+ "source_port": "rows",
565
+ "target_port": "text"
566
+ },
567
+ {
568
+ "source_id": "hmac_sha256",
569
+ "target_id": "crypto_rsa_decrypt_hex",
570
+ "connection_type": "Hex_String",
571
+ "source_port": "hex",
572
+ "target_port": "hex_cipher"
573
+ },
574
+ {
575
+ "source_id": "calc_gcd_7a5a",
576
+ "target_id": "calc_gcd",
577
+ "connection_type": "Big_Int",
578
+ "source_port": "gcd",
579
+ "target_port": "a"
580
+ }
581
+ ]
582
+ }
tasks/agentescape-10-skeleton-9b98ca62/solution/solve.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/bin/sh
2
+ set -eu
3
+ python -I /solution/oracle.py
tasks/agentescape-10-skeleton-9b98ca62/task.toml ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ schema_version = "1.4"
2
+ source = "https://github.com/AGI-Eval-Official/Repo-of-AgentEscapeBench"
3
+
4
+ [[artifacts]]
5
+ source = "/evidence/final.json"
6
+ service = "puzzle"
7
+
8
+ [[artifacts]]
9
+ source = "/evidence/trace.jsonl"
10
+ service = "puzzle"
11
+
12
+ [task]
13
+ name = "edbeeching/agentescape-10-skeleton-9b98ca62"
14
+ version = "0.1.0"
15
+
16
+ [metadata]
17
+ difficulty = 10
18
+ source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7"
19
+ scenario_sha256 = "be9857c8b51883e8bf9242a55180274483ea528c687ed67bb74ebddf26abf513"
20
+ protocol = "harbor-cli-action-budget-v1"
21
+ max_actions = 500
22
+
23
+ [agent]
24
+ timeout_sec = 1200
25
+
26
+ [environment]
27
+ build_timeout_sec = 900
28
+ cpus = 1
29
+ memory_mb = 1024
30
+
31
+ [verifier]
32
+ environment_mode = "separate"
33
+ timeout_sec = 60
34
+
35
+ [[verifier.collect]]
36
+ service = "puzzle"
37
+ command = "python -I /app/export.py"
38
+ timeout_sec = 15
tasks/agentescape-10-skeleton-9b98ca62/tests/Dockerfile ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f
2
+ COPY . /tests/
tasks/agentescape-10-skeleton-9b98ca62/tests/expected.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"scenario_sha256": "be9857c8b51883e8bf9242a55180274483ea528c687ed67bb74ebddf26abf513", "max_actions": 500}
tasks/agentescape-10-skeleton-9b98ca62/tests/grade.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Grade only Harbor-collected sidecar evidence in a fresh verifier container."""
2
+
3
+ import json
4
+ from pathlib import Path
5
+
6
+ expected = json.loads(Path("/tests/expected.json").read_text())
7
+ state = json.loads(Path("/evidence/final.json").read_text())
8
+ assert state["collected_from_live_service"] is True, "Missing trusted service export"
9
+ assert state["scenario_sha256"] == expected["scenario_sha256"], (
10
+ "Wrong scenario evidence"
11
+ )
12
+ assert state["max_actions"] == expected["max_actions"], "Wrong budget"
13
+ assert type(state["won"]) is bool
14
+ assert 0 <= state["action_count"] <= state["max_actions"]
15
+ assert state["termination_reason"] != "infrastructure_error", (
16
+ "Infrastructure failure is not a puzzle failure"
17
+ )
18
+ assert not state["won"] or state["termination_reason"] == "success"
19
+ Path("/logs/verifier").mkdir(parents=True, exist_ok=True)
20
+ Path("/logs/verifier/state.json").write_text(json.dumps(state, indent=2))
21
+ Path("/logs/verifier/reward.txt").write_text("1.0\n" if state["won"] else "0.0\n")
tasks/agentescape-10-skeleton-9b98ca62/tests/test.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/bin/sh
2
+ set -eu
3
+ python -I /tests/grade.py
tasks/agentescape-10-skeleton-a4248b22/environment/Dockerfile ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f
2
+ RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/*
3
+ COPY cli.py /usr/local/bin/escape
4
+ RUN chmod 755 /usr/local/bin/escape
5
+ WORKDIR /workspace
tasks/agentescape-10-skeleton-a4248b22/environment/agent/Dockerfile ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f
2
+ RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/*
3
+ COPY cli.py /usr/local/bin/escape
4
+ RUN chmod 755 /usr/local/bin/escape
5
+ WORKDIR /workspace
tasks/agentescape-10-skeleton-a4248b22/environment/agent/cli.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Public agent client; depends only on the Python standard library."""
3
+
4
+ import argparse
5
+ import json
6
+ import os
7
+ import sys
8
+ import urllib.error
9
+ import urllib.request
10
+
11
+
12
+ def main():
13
+ parser = argparse.ArgumentParser(description="Interact with the escape room")
14
+ parser.add_argument(
15
+ "action",
16
+ choices=[
17
+ "observe",
18
+ "state",
19
+ "investigate",
20
+ "tool-call",
21
+ "use-item",
22
+ "submit-answer",
23
+ ],
24
+ )
25
+ parser.add_argument("value", nargs="?")
26
+ parser.add_argument("--arguments-json", default="{}")
27
+ args = parser.parse_args()
28
+ base = os.environ.get("ESCAPE_URL", "http://puzzle:8000").rstrip("/")
29
+ if args.action in ("observe", "state"):
30
+ request = urllib.request.Request(
31
+ base + ("/observation" if args.action == "observe" else "/state")
32
+ )
33
+ else:
34
+ if args.value is None:
35
+ parser.error("node ID or answer is required")
36
+ payload = {"action": args.action.replace("-", "_")}
37
+ if args.action == "submit-answer":
38
+ payload["answer"] = args.value
39
+ else:
40
+ payload["node_id"] = args.value
41
+ if args.action in ("tool-call", "use-item"):
42
+ payload["arguments"] = json.loads(args.arguments_json)
43
+ request = urllib.request.Request(
44
+ base + "/action",
45
+ data=json.dumps(payload).encode(),
46
+ headers={"Content-Type": "application/json"},
47
+ )
48
+ try:
49
+ with urllib.request.urlopen(request, timeout=30) as response:
50
+ print(json.dumps(json.load(response), ensure_ascii=False))
51
+ except (urllib.error.URLError, ValueError) as exc:
52
+ print(json.dumps({"ok": False, "error": str(exc)}))
53
+ sys.exit(2)
54
+
55
+
56
+ if __name__ == "__main__":
57
+ main()
tasks/agentescape-10-skeleton-a4248b22/environment/docker-compose.yaml ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ services:
2
+ main:
3
+ image: agentescapebench-agent:aab05a0a9ddb
4
+ build:
5
+ context: ./agent
6
+ networks: [default, puzzle]
7
+ security_opt: [no-new-privileges:true]
8
+ depends_on:
9
+ puzzle:
10
+ condition: service_healthy
11
+ puzzle:
12
+ image: agentescapebench-puzzle:agentescape-10-skeleton-a4248b22-aab05a0a9ddb
13
+ build:
14
+ context: ./puzzle
15
+ networks: [puzzle, execution]
16
+ cap_drop: [ALL]
17
+ security_opt: [no-new-privileges:true]
18
+ pids_limit: 64
19
+ mem_limit: 512m
20
+ healthcheck:
21
+ test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"]
22
+ interval: 1s
23
+ timeout: 3s
24
+ retries: 30
25
+ depends_on:
26
+ worker:
27
+ condition: service_healthy
28
+ worker:
29
+ image: agentescapebench-worker:aab05a0a9ddb
30
+ build:
31
+ context: ./puzzle
32
+ dockerfile: worker.Dockerfile
33
+ networks: [execution]
34
+ read_only: true
35
+ tmpfs: ["/tmp:size=64m,mode=1777"]
36
+ cap_drop: [ALL]
37
+ cap_add: [SETUID, SETGID, KILL, CHOWN, DAC_OVERRIDE]
38
+ security_opt: [no-new-privileges:true]
39
+ pids_limit: 64
40
+ mem_limit: 384m
41
+ healthcheck:
42
+ test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8001/health')"]
43
+ interval: 1s
44
+ timeout: 3s
45
+ retries: 30
46
+ networks:
47
+ puzzle:
48
+ internal: true
49
+ execution:
50
+ internal: true
tasks/agentescape-10-skeleton-a4248b22/environment/puzzle/Dockerfile ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f
2
+ COPY requirements.txt /app/requirements.txt
3
+ RUN pip install --no-cache-dir -r /app/requirements.txt
4
+ WORKDIR /app
5
+ COPY upstream /app/upstream
6
+ COPY service.py export.py /app/
7
+ COPY scenario.json /private/scenario.json
8
+ ENV SCENARIO_PATH=/private/scenario.json EVIDENCE_DIR=/evidence WORKER_URL=http://worker:8001 MAX_ACTIONS=500
9
+ CMD ["uvicorn", "service:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000", "--workers", "1", "--no-access-log"]
tasks/agentescape-10-skeleton-a4248b22/environment/puzzle/child.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run the original Python tool after reducing privileges and blocking networking."""
2
+
3
+ import ctypes
4
+ import errno
5
+ import json
6
+ import resource
7
+ import sys
8
+
9
+ resource.setrlimit(resource.RLIMIT_CPU, (3, 3))
10
+ resource.setrlimit(resource.RLIMIT_AS, (256 * 1024 * 1024, 256 * 1024 * 1024))
11
+ resource.setrlimit(resource.RLIMIT_FSIZE, (65536, 65536))
12
+ resource.setrlimit(resource.RLIMIT_NOFILE, (32, 32))
13
+ resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
14
+
15
+ # Filters survive fork/exec. Fail closed if seccomp cannot be loaded.
16
+ lib = ctypes.CDLL("libseccomp.so.2", use_errno=True)
17
+ lib.seccomp_init.argtypes = [ctypes.c_uint32]
18
+ lib.seccomp_init.restype = ctypes.c_void_p
19
+ lib.seccomp_rule_add.argtypes = [
20
+ ctypes.c_void_p,
21
+ ctypes.c_uint32,
22
+ ctypes.c_int,
23
+ ctypes.c_uint,
24
+ ]
25
+ lib.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p]
26
+ lib.seccomp_load.argtypes = [ctypes.c_void_p]
27
+ lib.seccomp_release.argtypes = [ctypes.c_void_p]
28
+ ctx = lib.seccomp_init(0x7FFF0000) # SCMP_ACT_ALLOW
29
+ if not ctx:
30
+ raise RuntimeError("Cannot initialize execution isolation")
31
+ try:
32
+ for name in (
33
+ "socket",
34
+ "socketpair",
35
+ "connect",
36
+ "ptrace",
37
+ "process_vm_readv",
38
+ "process_vm_writev",
39
+ "mount",
40
+ "unshare",
41
+ "setns",
42
+ "bpf",
43
+ ):
44
+ number = lib.seccomp_syscall_resolve_name(name.encode())
45
+ if (
46
+ number >= 0
47
+ and lib.seccomp_rule_add(ctx, 0x00050000 | errno.EPERM, number, 0) != 0
48
+ ):
49
+ raise RuntimeError("Cannot install execution isolation rule")
50
+ if lib.seccomp_load(ctx) != 0:
51
+ raise RuntimeError("Cannot activate execution isolation")
52
+ finally:
53
+ lib.seccomp_release(ctx)
54
+
55
+ sys.path.insert(0, "/app")
56
+ from simulator import ToolSimulator # noqa: E402
57
+
58
+ request = json.load(sys.stdin)
59
+ json.dump(ToolSimulator().code_py_exec(request), sys.stdout)
tasks/agentescape-10-skeleton-a4248b22/environment/puzzle/export.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Harbor invokes this inside the puzzle service after stopping the agent."""
2
+
3
+ import json
4
+ import pathlib
5
+ import urllib.request
6
+
7
+ with urllib.request.urlopen("http://127.0.0.1:8000/state", timeout=10) as response:
8
+ state = json.load(response)
9
+ state["collected_from_live_service"] = True
10
+ target = pathlib.Path("/evidence/final.json")
11
+ temp = target.with_suffix(".tmp")
12
+ temp.write_text(json.dumps(state))
13
+ temp.replace(target)
tasks/agentescape-10-skeleton-a4248b22/environment/puzzle/requirements.txt ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ annotated-doc==0.0.5
2
+ # via fastapi
3
+ annotated-types==0.8.0
4
+ # via pydantic
5
+ anyio==4.16.0
6
+ # via starlette
7
+ certifi==2026.10.23
8
+ # via requests
9
+ cffi==2.1.1 ; platform_python_implementation != 'PyPy'
10
+ # via cryptography
11
+ charset-normalizer==3.5.2
12
+ # via requests
13
+ click==8.5.0
14
+ # via uvicorn
15
+ cryptography==50.0.2
16
+ # via agentescapebench-harbor
17
+ fastapi==0.162.0
18
+ # via agentescapebench-harbor
19
+ h11==0.16.0
20
+ # via uvicorn
21
+ idna==3.20
22
+ # via
23
+ # anyio
24
+ # requests
25
+ opentelemetry-api==1.45.2
26
+ # via fastapi
27
+ pycparser==3.12 ; implementation_name != 'PyPy' and platform_python_implementation != 'PyPy'
28
+ # via cffi
29
+ pydantic==2.14.2
30
+ # via
31
+ # agentescapebench-harbor
32
+ # fastapi
33
+ pydantic-core==2.50.2
34
+ # via pydantic
35
+ pytz==2025.2
36
+ # via agentescapebench-harbor
37
+ requests==2.34.2
38
+ # via agentescapebench-harbor
39
+ starlette==1.10.0
40
+ # via fastapi
41
+ typing-extensions==4.16.0
42
+ # via
43
+ # anyio
44
+ # fastapi
45
+ # opentelemetry-api
46
+ # pydantic
47
+ # pydantic-core
48
+ # starlette
49
+ # typing-inspection
50
+ typing-inspection==0.4.4
51
+ # via
52
+ # fastapi
53
+ # pydantic
54
+ urllib3==2.8.0
55
+ # via requests
56
+ uvicorn==0.54.0
57
+ # via agentescapebench-harbor
tasks/agentescape-10-skeleton-a4248b22/environment/puzzle/scenario.json ADDED
@@ -0,0 +1,717 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_nodes": 10,
4
+ "total_edges": 11,
5
+ "win_node_id": "regex_search",
6
+ "win_condition": {
7
+ "type": "tool_output",
8
+ "node_id": "regex_search",
9
+ "output_port": "matches",
10
+ "output_type": "Text_Generic",
11
+ "description": "Execute Regex Search and get the output from port 'matches'"
12
+ },
13
+ "source_init": {
14
+ "source_nodes": [
15
+ "regex_search",
16
+ "terminal_1",
17
+ "zip_unzip_file",
18
+ "json_get",
19
+ "calc_bigmul",
20
+ "terminal_1_ad07",
21
+ "graph_shortest_path"
22
+ ],
23
+ "by_node": {
24
+ "regex_search": {
25
+ "node_name": "Regex Search",
26
+ "node_type": "Tool",
27
+ "template_id": "regex_search",
28
+ "init_inputs": {},
29
+ "init_outputs": {
30
+ "matches": {
31
+ "type": "Text_Generic",
32
+ "description": "Found matches (List)"
33
+ }
34
+ }
35
+ },
36
+ "terminal_1": {
37
+ "node_name": "",
38
+ "node_type": "Tool",
39
+ "template_id": "terminal_1",
40
+ "init_inputs": {},
41
+ "init_outputs": {
42
+ "text_output": {
43
+ "type": "Text_Generic",
44
+ "description": "Text output when only slot_a is provided"
45
+ },
46
+ "hex_output": {
47
+ "type": "Hex_String",
48
+ "description": "Hex output when only slot_b is provided"
49
+ },
50
+ "item_dispenser": {
51
+ "type": "Item",
52
+ "description": "Item output when both slots are provided"
53
+ }
54
+ }
55
+ },
56
+ "zip_unzip_file": {
57
+ "node_name": "Zip Unzipper",
58
+ "node_type": "Tool",
59
+ "template_id": "zip_unzip_file",
60
+ "init_inputs": {
61
+ "zip_id": {
62
+ "type": "File_Id",
63
+ "description": "Zip file ID"
64
+ }
65
+ },
66
+ "init_outputs": {
67
+ "files": {
68
+ "type": "File_Id",
69
+ "description": "Extracted file ID"
70
+ }
71
+ }
72
+ },
73
+ "json_get": {
74
+ "node_name": "JSON Getter",
75
+ "node_type": "Tool",
76
+ "template_id": "json_get",
77
+ "init_inputs": {
78
+ "file_id": {
79
+ "type": "File_Id",
80
+ "description": "JSON file ID"
81
+ },
82
+ "jsonpath": {
83
+ "type": "Text_Generic",
84
+ "description": "JSONPath expression"
85
+ }
86
+ },
87
+ "init_outputs": {
88
+ "values": {
89
+ "type": "Text_Generic",
90
+ "description": "Extracted values"
91
+ }
92
+ }
93
+ },
94
+ "calc_bigmul": {
95
+ "node_name": "Big Number Multiplier",
96
+ "node_type": "Tool",
97
+ "template_id": "calc_bigmul",
98
+ "init_inputs": {
99
+ "b": {
100
+ "type": "Big_Int",
101
+ "description": "Second large integer"
102
+ }
103
+ },
104
+ "init_outputs": {}
105
+ },
106
+ "terminal_1_ad07": {
107
+ "node_name": "",
108
+ "node_type": "Tool",
109
+ "template_id": "terminal_1",
110
+ "init_inputs": {
111
+ "slot_a": {
112
+ "type": "Text_Generic",
113
+ "description": "Input Slot A"
114
+ },
115
+ "slot_b": {
116
+ "type": "Big_Int",
117
+ "description": "Input Slot B"
118
+ }
119
+ },
120
+ "init_outputs": {
121
+ "text_output": {
122
+ "type": "Text_Generic",
123
+ "description": "Text output when only slot_a is provided"
124
+ },
125
+ "hex_output": {
126
+ "type": "Hex_String",
127
+ "description": "Hex output when only slot_b is provided"
128
+ },
129
+ "item_dispenser": {
130
+ "type": "Item",
131
+ "description": "Item output when both slots are provided"
132
+ }
133
+ }
134
+ },
135
+ "graph_shortest_path": {
136
+ "node_name": "Shortest Path Finder",
137
+ "node_type": "Tool",
138
+ "template_id": "graph_shortest_path",
139
+ "init_inputs": {
140
+ "file_id": {
141
+ "type": "File_Id",
142
+ "description": "Graph JSON file ID"
143
+ },
144
+ "dst": {
145
+ "type": "Text_Generic",
146
+ "description": "Destination node"
147
+ }
148
+ },
149
+ "init_outputs": {
150
+ "path": {
151
+ "type": "Text_Generic",
152
+ "description": "Path list"
153
+ },
154
+ "cost": {
155
+ "type": "Big_Int",
156
+ "description": "Path cost"
157
+ }
158
+ }
159
+ }
160
+ }
161
+ },
162
+ "initial_values": {
163
+ "regex_search": {
164
+ "init_inputs": {},
165
+ "init_outputs": {
166
+ "matches": "[\"found_pattern_001\", \"found_pattern_002\", \"found_pattern_003\", \"found_pattern_004\", \"found_pattern_005\"]"
167
+ }
168
+ },
169
+ "terminal_1": {
170
+ "init_inputs": {},
171
+ "init_outputs": {
172
+ "text_output": "System initialization sequence complete. Ready for input.",
173
+ "hex_output": "a1b2c3d4e5f60718293a4b5c6d7e8f90",
174
+ "item_dispenser": "Standard Item Dispenser Unit Alpha"
175
+ }
176
+ },
177
+ "zip_unzip_file": {
178
+ "init_inputs": {
179
+ "zip_id": "secure_archive_data_2024.zip"
180
+ },
181
+ "init_outputs": {
182
+ "files": "extracted_payload_config.json"
183
+ }
184
+ },
185
+ "json_get": {
186
+ "init_inputs": {
187
+ "file_id": "user_records_database_v9.json",
188
+ "jsonpath": "$.store.book[*].author"
189
+ },
190
+ "init_outputs": {
191
+ "values": "[\"Nigel Rees\", \"Evelyn Waugh\", \"Herman Melville\", \"J. R. R. Tolkien\"]"
192
+ }
193
+ },
194
+ "calc_bigmul": {
195
+ "init_inputs": {
196
+ "b": "847362519405837261509483726150"
197
+ },
198
+ "init_outputs": {}
199
+ },
200
+ "terminal_1_ad07": {
201
+ "init_inputs": {
202
+ "slot_a": "Manual_Override_Sequence_Initiated",
203
+ "slot_b": "594837261502938475610293847561"
204
+ },
205
+ "init_outputs": {
206
+ "text_output": "SuperSecretPassword123!",
207
+ "hex_output": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d",
208
+ "item_dispenser": "Advanced Item Dispenser Unit Beta"
209
+ }
210
+ },
211
+ "graph_shortest_path": {
212
+ "init_inputs": {
213
+ "file_id": "city_traffic_network_graph.json",
214
+ "dst": "Sector_7_Terminal"
215
+ },
216
+ "init_outputs": {
217
+ "path": "[\"Central_Hub\", \"Gateway_North\", \"Route_66\", \"Check_Point_Alpha\", \"Sector_7_Terminal\"]",
218
+ "cost": "12548"
219
+ }
220
+ }
221
+ },
222
+ "intro_narrative": "You wake up in the dimly lit office of a renowned but missing private investigator. Dust motes dance in the pale light filtering through the blinds. The detective was close to solving a massive conspiracy, and the agency believes he left his final findings hidden within this very room. Time is running out before the perpetrators realize you are here. Your objective is to piece together his scattered tools, uncover the hidden evidence, and expose the truth before the shadowy syndicate returns to silence you for good.",
223
+ "narrative_style": "mystery"
224
+ },
225
+ "nodes": [
226
+ {
227
+ "id": "regex_search",
228
+ "name": "Regex Search",
229
+ "description": "Search regex in either raw text or a file.",
230
+ "type": "Tool",
231
+ "template_id": "regex_search",
232
+ "initial_visible": true,
233
+ "is_revealed": true,
234
+ "inputs": [
235
+ {
236
+ "name": "pattern",
237
+ "type": "Text_Generic",
238
+ "description": "Regex pattern",
239
+ "value": "System initialization sequence complete. Ready for input."
240
+ },
241
+ {
242
+ "name": "file_id",
243
+ "type": "File_Id",
244
+ "description": "File ID (optional)",
245
+ "value": "extracted_payload_config.json"
246
+ },
247
+ {
248
+ "name": "text",
249
+ "type": "Text_Generic",
250
+ "description": "Text (optional)",
251
+ "value": "[\"Nigel Rees\", \"Evelyn Waugh\", \"Herman Melville\", \"J. R. R. Tolkien\"]"
252
+ }
253
+ ],
254
+ "outputs": [
255
+ {
256
+ "name": "matches",
257
+ "type": "Text_Generic",
258
+ "description": "Found matches (List)",
259
+ "value": "[\"found_pattern_001\", \"found_pattern_002\", \"found_pattern_003\", \"found_pattern_004\", \"found_pattern_005\"]"
260
+ }
261
+ ],
262
+ "init": {
263
+ "inputs": {},
264
+ "outputs": {
265
+ "matches": "[\"found_pattern_001\", \"found_pattern_002\", \"found_pattern_003\", \"found_pattern_004\", \"found_pattern_005\"]"
266
+ }
267
+ },
268
+ "narrative": "A high-tech Evidence Scanner designed to find hidden anomalies. It requires inputs from the Mainframe Terminal, the Locked Briefcase, and the Archives Computer to function."
269
+ },
270
+ {
271
+ "id": "terminal_1",
272
+ "name": "",
273
+ "description": "",
274
+ "type": "Tool",
275
+ "template_id": "terminal_1",
276
+ "initial_visible": true,
277
+ "is_revealed": true,
278
+ "inputs": [
279
+ {
280
+ "name": "slot_a",
281
+ "type": "Text_Generic",
282
+ "description": "Input Slot A",
283
+ "value": "[\"Nigel Rees\", \"Evelyn Waugh\", \"Herman Melville\", \"J. R. R. Tolkien\"]"
284
+ },
285
+ {
286
+ "name": "slot_b",
287
+ "type": "Big_Int",
288
+ "description": "Input Slot B",
289
+ "value": "10632704893504445957421001795730200"
290
+ }
291
+ ],
292
+ "outputs": [
293
+ {
294
+ "name": "text_output",
295
+ "type": "Text_Generic",
296
+ "description": "Text output when only slot_a is provided",
297
+ "value": "System initialization sequence complete. Ready for input."
298
+ },
299
+ {
300
+ "name": "hex_output",
301
+ "type": "Hex_String",
302
+ "description": "Hex output when only slot_b is provided",
303
+ "value": "a1b2c3d4e5f60718293a4b5c6d7e8f90"
304
+ },
305
+ {
306
+ "name": "item_dispenser",
307
+ "type": "Item",
308
+ "description": "Item output when both slots are provided",
309
+ "value": "Standard Item Dispenser Unit Alpha"
310
+ }
311
+ ],
312
+ "init": {
313
+ "inputs": {},
314
+ "outputs": {
315
+ "text_output": "System initialization sequence complete. Ready for input.",
316
+ "hex_output": "a1b2c3d4e5f60718293a4b5c6d7e8f90",
317
+ "item_dispenser": "Standard Item Dispenser Unit Alpha"
318
+ }
319
+ },
320
+ "narrative": "The central Mainframe Terminal sits on a dusty desk. It requires inputs from both the Archives Computer and the Mechanical Calculator to process the data."
321
+ },
322
+ {
323
+ "id": "zip_unzip_file",
324
+ "name": "Zip Unzipper",
325
+ "description": "Unzip a password-protected zip file by id.",
326
+ "type": "Tool",
327
+ "template_id": "zip_unzip_file",
328
+ "initial_visible": true,
329
+ "is_revealed": true,
330
+ "inputs": [
331
+ {
332
+ "name": "zip_id",
333
+ "type": "File_Id",
334
+ "description": "Zip file ID",
335
+ "value": "secure_archive_data_2024.zip"
336
+ },
337
+ {
338
+ "name": "password",
339
+ "type": "Text_Generic",
340
+ "description": "Password",
341
+ "value": "SuperSecretPassword123!"
342
+ }
343
+ ],
344
+ "outputs": [
345
+ {
346
+ "name": "files",
347
+ "type": "File_Id",
348
+ "description": "Extracted file ID",
349
+ "value": "extracted_payload_config.json"
350
+ }
351
+ ],
352
+ "init": {
353
+ "inputs": {
354
+ "zip_id": "secure_archive_data_2024.zip"
355
+ },
356
+ "outputs": {
357
+ "files": "extracted_payload_config.json"
358
+ }
359
+ },
360
+ "narrative": "A Locked Briefcase holding classified documents. It requires input from the Security Keypad to unlock."
361
+ },
362
+ {
363
+ "id": "json_get",
364
+ "name": "JSON Getter",
365
+ "description": "Extract values by simple JSONPath.",
366
+ "type": "Tool",
367
+ "template_id": "json_get",
368
+ "initial_visible": false,
369
+ "is_revealed": false,
370
+ "inputs": [
371
+ {
372
+ "name": "trigger_hidden",
373
+ "type": "Hidden_Item",
374
+ "description": "Hidden item required to unlock this tool"
375
+ },
376
+ {
377
+ "name": "file_id",
378
+ "type": "File_Id",
379
+ "description": "JSON file ID",
380
+ "value": "user_records_database_v9.json"
381
+ },
382
+ {
383
+ "name": "jsonpath",
384
+ "type": "Text_Generic",
385
+ "description": "JSONPath expression",
386
+ "value": "$.store.book[*].author"
387
+ }
388
+ ],
389
+ "outputs": [
390
+ {
391
+ "name": "values",
392
+ "type": "Text_Generic",
393
+ "description": "Extracted values",
394
+ "value": "[\"Nigel Rees\", \"Evelyn Waugh\", \"Herman Melville\", \"J. R. R. Tolkien\"]"
395
+ }
396
+ ],
397
+ "init": {
398
+ "inputs": {
399
+ "file_id": "user_records_database_v9.json",
400
+ "jsonpath": "$.store.book[*].author"
401
+ },
402
+ "outputs": {
403
+ "values": "[\"Nigel Rees\", \"Evelyn Waugh\", \"Herman Melville\", \"J. R. R. Tolkien\"]"
404
+ }
405
+ },
406
+ "narrative": "An old Archives Computer containing digitized records from decades ago."
407
+ },
408
+ {
409
+ "id": "item_8",
410
+ "name": "",
411
+ "description": "",
412
+ "type": "Item",
413
+ "template_id": "item_8",
414
+ "initial_visible": false,
415
+ "is_revealed": false,
416
+ "inputs": [
417
+ {
418
+ "name": "source_tool",
419
+ "type": "Hidden_Item",
420
+ "description": "Produced by"
421
+ }
422
+ ],
423
+ "outputs": [
424
+ {
425
+ "name": "content",
426
+ "type": "Hidden_Item",
427
+ "description": "The integer"
428
+ }
429
+ ],
430
+ "narrative": "A Strange Lens that seems capable of revealing hidden ink or invisible markings."
431
+ },
432
+ {
433
+ "id": "item_16",
434
+ "name": "",
435
+ "description": "",
436
+ "type": "Item",
437
+ "template_id": "item_16",
438
+ "initial_visible": true,
439
+ "is_revealed": true,
440
+ "inputs": [
441
+ {
442
+ "name": "source_tool",
443
+ "type": "Item",
444
+ "description": "Produced by"
445
+ }
446
+ ],
447
+ "outputs": [
448
+ {
449
+ "name": "content",
450
+ "type": "Hidden_Item",
451
+ "description": "Timezone text"
452
+ }
453
+ ],
454
+ "narrative": "An Antique Compass with strange engravings on the back."
455
+ },
456
+ {
457
+ "id": "calc_bigmul",
458
+ "name": "Big Number Multiplier",
459
+ "description": "Multiply two (very large) decimal integers represented as strings.",
460
+ "type": "Tool",
461
+ "template_id": "calc_bigmul",
462
+ "initial_visible": true,
463
+ "is_revealed": true,
464
+ "inputs": [
465
+ {
466
+ "name": "trigger_hidden",
467
+ "type": "Hidden_Item",
468
+ "description": "Hidden item required to unlock this tool"
469
+ },
470
+ {
471
+ "name": "a",
472
+ "type": "Big_Int",
473
+ "description": "First large integer",
474
+ "value": "12548"
475
+ },
476
+ {
477
+ "name": "b",
478
+ "type": "Big_Int",
479
+ "description": "Second large integer",
480
+ "value": "847362519405837261509483726150"
481
+ }
482
+ ],
483
+ "outputs": [
484
+ {
485
+ "name": "product",
486
+ "type": "Big_Int",
487
+ "description": "Product result",
488
+ "value": "10632704893504445957421001795730200"
489
+ }
490
+ ],
491
+ "init": {
492
+ "inputs": {
493
+ "b": "847362519405837261509483726150"
494
+ },
495
+ "outputs": {}
496
+ },
497
+ "narrative": "A heavy Mechanical Calculator with intricate brass gears. It requires input from the City Map Board to compute the final coordinates."
498
+ },
499
+ {
500
+ "id": "terminal_1_ad07",
501
+ "name": "",
502
+ "description": "",
503
+ "type": "Tool",
504
+ "template_id": "terminal_1",
505
+ "initial_visible": true,
506
+ "is_revealed": true,
507
+ "inputs": [
508
+ {
509
+ "name": "slot_a",
510
+ "type": "Text_Generic",
511
+ "description": "Input Slot A",
512
+ "value": "Manual_Override_Sequence_Initiated"
513
+ },
514
+ {
515
+ "name": "slot_b",
516
+ "type": "Big_Int",
517
+ "description": "Input Slot B",
518
+ "value": "594837261502938475610293847561"
519
+ }
520
+ ],
521
+ "outputs": [
522
+ {
523
+ "name": "text_output",
524
+ "type": "Text_Generic",
525
+ "description": "Text output when only slot_a is provided",
526
+ "value": "SuperSecretPassword123!"
527
+ },
528
+ {
529
+ "name": "hex_output",
530
+ "type": "Hex_String",
531
+ "description": "Hex output when only slot_b is provided",
532
+ "value": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d"
533
+ },
534
+ {
535
+ "name": "item_dispenser",
536
+ "type": "Item",
537
+ "description": "Item output when both slots are provided",
538
+ "value": "Advanced Item Dispenser Unit Beta"
539
+ }
540
+ ],
541
+ "init": {
542
+ "inputs": {
543
+ "slot_a": "Manual_Override_Sequence_Initiated",
544
+ "slot_b": "594837261502938475610293847561"
545
+ },
546
+ "outputs": {
547
+ "text_output": "SuperSecretPassword123!",
548
+ "hex_output": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d",
549
+ "item_dispenser": "Advanced Item Dispenser Unit Beta"
550
+ }
551
+ },
552
+ "narrative": "A standard Security Keypad securely attached to the wall next to a reinforced door."
553
+ },
554
+ {
555
+ "id": "graph_shortest_path",
556
+ "name": "Shortest Path Finder",
557
+ "description": "Shortest path on graph json file with edges list.",
558
+ "type": "Tool",
559
+ "template_id": "graph_shortest_path",
560
+ "initial_visible": false,
561
+ "is_revealed": false,
562
+ "inputs": [
563
+ {
564
+ "name": "trigger_hidden",
565
+ "type": "Hidden_Item",
566
+ "description": "Hidden item required to unlock this tool"
567
+ },
568
+ {
569
+ "name": "file_id",
570
+ "type": "File_Id",
571
+ "description": "Graph JSON file ID",
572
+ "value": "city_traffic_network_graph.json"
573
+ },
574
+ {
575
+ "name": "src",
576
+ "type": "Text_Generic",
577
+ "description": "Source node",
578
+ "value": "[\"Nigel Rees\", \"Evelyn Waugh\", \"Herman Melville\", \"J. R. R. Tolkien\"]"
579
+ },
580
+ {
581
+ "name": "dst",
582
+ "type": "Text_Generic",
583
+ "description": "Destination node",
584
+ "value": "Sector_7_Terminal"
585
+ }
586
+ ],
587
+ "outputs": [
588
+ {
589
+ "name": "path",
590
+ "type": "Text_Generic",
591
+ "description": "Path list",
592
+ "value": "[\"Central_Hub\", \"Gateway_North\", \"Route_66\", \"Check_Point_Alpha\", \"Sector_7_Terminal\"]"
593
+ },
594
+ {
595
+ "name": "cost",
596
+ "type": "Big_Int",
597
+ "description": "Path cost",
598
+ "value": "12548"
599
+ }
600
+ ],
601
+ "init": {
602
+ "inputs": {
603
+ "file_id": "city_traffic_network_graph.json",
604
+ "dst": "Sector_7_Terminal"
605
+ },
606
+ "outputs": {
607
+ "path": "[\"Central_Hub\", \"Gateway_North\", \"Route_66\", \"Check_Point_Alpha\", \"Sector_7_Terminal\"]",
608
+ "cost": "12548"
609
+ }
610
+ },
611
+ "narrative": "A City Map Board covered in red strings and thumbtacks. It requires input from the Archives Computer to determine the correct route."
612
+ },
613
+ {
614
+ "id": "item_16_54c0",
615
+ "name": "",
616
+ "description": "",
617
+ "type": "Item",
618
+ "template_id": "item_16",
619
+ "initial_visible": true,
620
+ "is_revealed": true,
621
+ "inputs": [
622
+ {
623
+ "name": "source_tool",
624
+ "type": "Item",
625
+ "description": "Produced by"
626
+ }
627
+ ],
628
+ "outputs": [
629
+ {
630
+ "name": "content",
631
+ "type": "Hidden_Item",
632
+ "description": "Timezone text"
633
+ }
634
+ ],
635
+ "narrative": "A Dusty Pocket Watch showing multiple different timezones."
636
+ }
637
+ ],
638
+ "edges": [
639
+ {
640
+ "source_id": "terminal_1",
641
+ "target_id": "regex_search",
642
+ "connection_type": "Text_Generic",
643
+ "source_port": "text_output",
644
+ "target_port": "pattern"
645
+ },
646
+ {
647
+ "source_id": "zip_unzip_file",
648
+ "target_id": "regex_search",
649
+ "connection_type": "File_Id",
650
+ "source_port": "files",
651
+ "target_port": "file_id"
652
+ },
653
+ {
654
+ "source_id": "json_get",
655
+ "target_id": "regex_search",
656
+ "connection_type": "Text_Generic",
657
+ "source_port": "values",
658
+ "target_port": "text"
659
+ },
660
+ {
661
+ "source_id": "item_8",
662
+ "target_id": "json_get",
663
+ "connection_type": "Hidden_Item",
664
+ "source_port": "content",
665
+ "target_port": "trigger_hidden"
666
+ },
667
+ {
668
+ "source_id": "item_16",
669
+ "target_id": "item_8",
670
+ "connection_type": "Hidden_Item",
671
+ "source_port": "content",
672
+ "target_port": "source_tool"
673
+ },
674
+ {
675
+ "source_id": "json_get",
676
+ "target_id": "terminal_1",
677
+ "connection_type": "Text_Generic",
678
+ "source_port": "values",
679
+ "target_port": "slot_a"
680
+ },
681
+ {
682
+ "source_id": "calc_bigmul",
683
+ "target_id": "terminal_1",
684
+ "connection_type": "Big_Int",
685
+ "source_port": "product",
686
+ "target_port": "slot_b"
687
+ },
688
+ {
689
+ "source_id": "terminal_1_ad07",
690
+ "target_id": "zip_unzip_file",
691
+ "connection_type": "Text_Generic",
692
+ "source_port": "text_output",
693
+ "target_port": "password"
694
+ },
695
+ {
696
+ "source_id": "graph_shortest_path",
697
+ "target_id": "calc_bigmul",
698
+ "connection_type": "Big_Int",
699
+ "source_port": "cost",
700
+ "target_port": "a"
701
+ },
702
+ {
703
+ "source_id": "json_get",
704
+ "target_id": "graph_shortest_path",
705
+ "connection_type": "Text_Generic",
706
+ "source_port": "values",
707
+ "target_port": "src"
708
+ },
709
+ {
710
+ "source_id": "item_16_54c0",
711
+ "target_id": "graph_shortest_path",
712
+ "connection_type": "Hidden_Item",
713
+ "source_port": "content",
714
+ "target_port": "trigger_hidden"
715
+ }
716
+ ]
717
+ }
tasks/agentescape-10-skeleton-a4248b22/environment/puzzle/service.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Restricted facade over the unchanged, pinned upstream puzzle handlers."""
2
+
3
+ import hashlib
4
+ import json
5
+ import logging
6
+ import os
7
+ import sys
8
+ import threading
9
+ import urllib.request
10
+ import uuid
11
+ from pathlib import Path
12
+
13
+ from fastapi import FastAPI, HTTPException
14
+ from fastapi.responses import JSONResponse
15
+ from pydantic import BaseModel, ConfigDict
16
+
17
+ sys.path.insert(0, str(Path(__file__).parent / "upstream"))
18
+ import server as upstream # noqa: E402
19
+
20
+ log = logging.getLogger(__name__)
21
+
22
+
23
+ def public(value):
24
+ """Keep upstream agent-internal template hints out of the public response."""
25
+ if isinstance(value, dict):
26
+ return {k: public(v) for k, v in value.items() if not k.startswith("_")}
27
+ if isinstance(value, list):
28
+ return [public(v) for v in value]
29
+ return value
30
+
31
+
32
+ class Action(BaseModel):
33
+ model_config = ConfigDict(extra="forbid", strict=True)
34
+ action: str
35
+ node_id: str | None = None
36
+ arguments: dict | None = None
37
+ answer: str | None = None
38
+
39
+
40
+ class Episode:
41
+ def __init__(
42
+ self, scenario_path, max_actions=500, evidence_dir=None, worker_url=None
43
+ ):
44
+ if max_actions < 1:
45
+ raise ValueError("max_actions must be positive")
46
+ self.lock = threading.Lock()
47
+ self.max_actions = max_actions
48
+ self.count = 0
49
+ self.won = False
50
+ self.reason = None
51
+ self.evidence_dir = Path(evidence_dir) if evidence_dir else None
52
+ self.scenario_hash = hashlib.sha256(
53
+ Path(scenario_path).read_bytes()
54
+ ).hexdigest()
55
+ self.initial = upstream.reset_case(
56
+ case_file_path=str(scenario_path), session_id=uuid.uuid4().hex
57
+ )
58
+ self.case_id = self.initial["case_id"]
59
+ # Hide source file paths; no upstream reset/stats/routes are mounted.
60
+ self.initial.pop("message", None)
61
+ simulator = upstream.SIMULATORS[self.case_id]
62
+ if worker_url is None:
63
+
64
+ def no_worker(_inputs):
65
+ self.reason = "infrastructure_error"
66
+ raise RuntimeError("isolated Python worker is not configured")
67
+
68
+ simulator.tool_map["code_py_exec"] = no_worker
69
+ else:
70
+
71
+ def execute_python(inputs):
72
+ request = urllib.request.Request(
73
+ worker_url + "/execute",
74
+ data=json.dumps({"code": inputs.get("code", "")}).encode(),
75
+ headers={"Content-Type": "application/json"},
76
+ )
77
+ try:
78
+ with urllib.request.urlopen(request, timeout=12) as response:
79
+ result = json.load(response)
80
+ if not isinstance(result.get("stdout"), str):
81
+ raise RuntimeError("Invalid Python worker response")
82
+ return result
83
+ except Exception:
84
+ self.reason = "infrastructure_error"
85
+ raise
86
+
87
+ simulator.tool_map["code_py_exec"] = execute_python
88
+ self.save()
89
+ if self.evidence_dir is not None:
90
+ (self.evidence_dir / "trace.jsonl").touch()
91
+
92
+ def state(self):
93
+ return {
94
+ "scenario_sha256": self.scenario_hash,
95
+ "action_count": self.count,
96
+ "max_actions": self.max_actions,
97
+ "won": self.won,
98
+ "termination_reason": self.reason,
99
+ }
100
+
101
+ def save(self, action=None, result=None):
102
+ if self.evidence_dir is None:
103
+ return
104
+ self.evidence_dir.mkdir(parents=True, exist_ok=True)
105
+ target = self.evidence_dir / "outcome.json"
106
+ temp = target.with_suffix(".tmp")
107
+ temp.write_text(json.dumps(self.state()))
108
+ temp.replace(target)
109
+ if action is not None:
110
+ with (self.evidence_dir / "trace.jsonl").open("a") as handle:
111
+ handle.write(
112
+ json.dumps(
113
+ {"index": self.count, "action": action, "result": result}
114
+ )
115
+ + "\n"
116
+ )
117
+
118
+ def dispatch(self, payload):
119
+ with self.lock:
120
+ if self.reason is not None:
121
+ return {
122
+ "ok": False,
123
+ "error": "Episode has ended",
124
+ "episode": self.state(),
125
+ }
126
+ self.count += 1
127
+ try:
128
+ action = Action.model_validate(payload)
129
+ if action.action == "submit_answer" and action.answer is not None:
130
+ result = upstream.submit_answer(
131
+ self.case_id, upstream.SubmitAnswerRequest(answer=action.answer)
132
+ )
133
+ if result.get("is_win"):
134
+ self.won = True
135
+ self.reason = "success"
136
+ elif action.action == "investigate" and action.node_id is not None:
137
+ result = upstream.investigate(
138
+ self.case_id,
139
+ upstream.InvestigateRequest(node_id=action.node_id),
140
+ )
141
+ elif (
142
+ action.action in ("tool_call", "use_item")
143
+ and action.node_id is not None
144
+ ):
145
+ request_type, handler = (
146
+ (upstream.ToolCallRequest, upstream.tool_call)
147
+ if action.action == "tool_call"
148
+ else (upstream.UseItemRequest, upstream.use_item)
149
+ )
150
+ result = handler(
151
+ self.case_id,
152
+ request_type(
153
+ node_id=action.node_id, arguments=action.arguments or {}
154
+ ),
155
+ )
156
+ else:
157
+ result = {
158
+ "ok": False,
159
+ "error": "Unknown action or missing action parameter",
160
+ }
161
+ except HTTPException as exc:
162
+ result = {"ok": False, "error": exc.detail}
163
+ except ValueError:
164
+ result = {"ok": False, "error": "Malformed action"}
165
+ except Exception:
166
+ log.exception("Puzzle service failure")
167
+ self.reason = "infrastructure_error"
168
+ self.save()
169
+ raise
170
+ if self.reason is None and self.count >= self.max_actions:
171
+ self.reason = "action_budget_exhausted"
172
+ result = public(result)
173
+ result["episode"] = self.state()
174
+ self.save(payload, result)
175
+ return result
176
+
177
+
178
+ def create_app(
179
+ scenario_path=None, max_actions=None, evidence_dir=None, worker_url=None
180
+ ):
181
+ episode = Episode(
182
+ scenario_path or os.environ["SCENARIO_PATH"],
183
+ max_actions or int(os.environ.get("MAX_ACTIONS", "500")),
184
+ evidence_dir if evidence_dir is not None else os.environ.get("EVIDENCE_DIR"),
185
+ worker_url if worker_url is not None else os.environ.get("WORKER_URL"),
186
+ )
187
+ app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
188
+ app.state.episode = episode
189
+
190
+ @app.get("/health")
191
+ def health():
192
+ return {"ok": True}
193
+
194
+ @app.get("/observation")
195
+ def observation():
196
+ return {**public(episode.initial), "episode": episode.state()}
197
+
198
+ @app.get("/state")
199
+ def state():
200
+ return episode.state()
201
+
202
+ @app.post("/action")
203
+ def action(payload: dict):
204
+ try:
205
+ return episode.dispatch(payload)
206
+ except Exception:
207
+ return JSONResponse(
208
+ status_code=503,
209
+ content={"ok": False, "error": "Puzzle infrastructure failure"},
210
+ )
211
+
212
+ return app
tasks/agentescape-10-skeleton-a4248b22/environment/puzzle/upstream/models.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from enum import Enum
2
+ from typing import List, Dict, Any, Optional
3
+ from pydantic import BaseModel, Field
4
+
5
+ # 1. 细粒度接口类型定义
6
+ class InterfaceType(str, Enum):
7
+ '''
8
+ BIG_INT
9
+ TEXT_GENERIC
10
+ HEX_STRING
11
+ FILE_ID
12
+ HEX_STRING_KEY_AES
13
+ HEX_STRING_IV_AES
14
+ CODE_PYTHON
15
+ HIDDEN_ITEM
16
+ ITEM
17
+ '''
18
+ # --- 基础类型 ---
19
+ TEXT_GENERIC = "Text_Generic"
20
+ BIG_INT = "Big_Int"
21
+
22
+ # --- 编码/格式化字符串 ---
23
+ HEX_STRING = "Hex_String" # 通用 Hex
24
+
25
+ # --- 特定用途的 Hex 字符串 (用于精确匹配) ---
26
+ HEX_STRING_KEY_AES = "Hex_String_Key_AES"
27
+ HEX_STRING_IV_AES = "Hex_String_IV_AES"
28
+
29
+ # --- 文件类型 ---
30
+ FILE_ID = "File_Id"
31
+
32
+ # --- 代码/脚本 ---
33
+ CODE_PYTHON = "Code_Python"
34
+
35
+ # --- 实体交互类型 (严格命名) ---
36
+ ITEM = "Item" # 主动掉落接口 (Tool -> Item)
37
+ HIDDEN_ITEM = "Hidden_Item" # 被动掉落接口 (Item -> Item)
38
+
39
+ # 3. 端口定义
40
+ class Port(BaseModel):
41
+ name: str
42
+ type: InterfaceType
43
+ description: str
44
+
45
+ # 4. 统一节点定义 (融合工具和物品)
46
+ class Node(BaseModel):
47
+ id: str
48
+ name: str
49
+ description: str
50
+ type: str # "Tool" or "Item"
51
+
52
+ # 接口定义
53
+ inputs: List[Port] = []
54
+ outputs: List[Port] = []
55
+
56
+ # 状态字段
57
+ content: Optional[Any] = None # 物品有内容,工具为None
58
+ if_success: Optional[bool] = None # 工具初始为False,物品为None
59
+ initial_visible: bool = False
60
+
61
+ # 运行时状态 (Server维护)
62
+ is_revealed: bool = False
63
+
64
+ # 标记该 Tool 节点是否有待触发的 HIDDEN_ITEM 掉落
65
+ # 当 Tool 按照 golden_input 正确执行且有 HIDDEN_ITEM 输出边时设为 True
66
+ # 在 investigate 该 Tool 时触发掉落并重置为 False
67
+ has_hidden_item_ready: bool = False
68
+
69
+ # 初始输入值 (metadata.initial_values.init_inputs,用于渐进式暴露判断)
70
+ init_input_values: Dict[str, Any] = {}
71
+
72
+ # Golden 输入值 (nodes[].inputs[].value,用于评测验证)
73
+ golden_input_values: Dict[str, Any] = {}
74
+
75
+ # Golden 输出值 (nodes[].outputs[].value,用于评测验证和 Item 节点的 content)
76
+ golden_output_values: Dict[str, Any] = {}
77
+
78
+ # 实际获得的输出值历史 (工具每次执行后实际返回的输出列表,用于渐进式暴露判断)
79
+ # 格式: List[Dict[str, Any]],每个元素是一次执行的输出字典
80
+ actual_outputs_history: List[Dict[str, Any]] = []
81
+
82
+ # 逻辑规则 (用于终端机等复杂物品)
83
+ logic_rules: Optional[Dict[str, Any]] = None
84
+
85
+ def copy(self, **kwargs):
86
+ """Helper to create a copy with updated fields."""
87
+ data = self.dict()
88
+ data.update(kwargs)
89
+ return Node(**data)
90
+
91
+ # 5. 边定义 (拓扑结构)
92
+ class Edge(BaseModel):
93
+ source_id: str
94
+ target_id: str
95
+ connection_type: InterfaceType # 直接使用 InterfaceType
96
+ # 如果是 Data_Flow,指定端口对应关系
97
+ source_port: Optional[str] = None
98
+ target_port: Optional[str] = None
99
+
100
+ # 6. 完整图定义
101
+ class GraphScenario(BaseModel):
102
+ case_id: str
103
+ title: str
104
+ intro_narrative: str
105
+ nodes: Dict[str, Node]
106
+ edges: List[Edge]
107
+ difficulty: int
108
+ win_node_id: str # 标记哪个节点是最终目标(通常是一个提交工具或最终物品)
tasks/agentescape-10-skeleton-a4248b22/environment/puzzle/upstream/server.py ADDED
@@ -0,0 +1,1490 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import time
4
+ import logging
5
+ import random
6
+ from pathlib import Path
7
+ from typing import Dict, Any, List, Optional
8
+ from datetime import datetime
9
+ from collections import defaultdict
10
+ from fastapi import FastAPI, HTTPException, Request
11
+ from fastapi.responses import JSONResponse
12
+ from fastapi.middleware.cors import CORSMiddleware
13
+ from pydantic import BaseModel, Field
14
+
15
+ from models import GraphScenario, Node, InterfaceType
16
+ # from generator import ScenarioGenerator
17
+ from simulator import ToolSimulator
18
+ import uvicorn
19
+
20
+ # 配置日志
21
+ logging.basicConfig(
22
+ level=logging.INFO,
23
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
24
+ handlers=[
25
+ logging.FileHandler('server.log'),
26
+ logging.StreamHandler()
27
+ ]
28
+ )
29
+ logger = logging.getLogger(__name__)
30
+
31
+ app = FastAPI(
32
+ title="AgentEscapeBench Universal Server",
33
+ version="1.0.0",
34
+ description="Industrial-grade evaluation server for escape room AI agents"
35
+ )
36
+
37
+ # 添加 CORS 支持
38
+ app.add_middleware(
39
+ CORSMiddleware,
40
+ allow_origins=["*"],
41
+ allow_credentials=True,
42
+ allow_methods=["*"],
43
+ allow_headers=["*"],
44
+ )
45
+
46
+ # In-memory State
47
+ SCENARIOS: Dict[str, GraphScenario] = {}
48
+ SIMULATORS: Dict[str, ToolSimulator] = {} # case_id -> ToolSimulator
49
+ RAW_NODES_DATA: Dict[str, Dict[str, Any]] = {} # case_id -> node_id -> raw node data (for template_id)
50
+ FILE_METADATA: Dict[str, Dict[str, Any]] = {} # case_id -> metadata (for initial_values access)
51
+
52
+ # Performance monitoring
53
+ STATS: Dict[str, Any] = {
54
+ "total_requests": 0,
55
+ "successful_requests": 0,
56
+ "failed_requests": 0,
57
+ "tool_calls": defaultdict(int),
58
+ "investigates": defaultdict(int),
59
+ "use_items": defaultdict(int),
60
+ "case_loads": 0,
61
+ "start_time": datetime.now()
62
+ }
63
+
64
+ # Request timing middleware
65
+ @app.middleware("http")
66
+ async def add_process_time_header(request: Request, call_next):
67
+ start_time = time.time()
68
+ STATS["total_requests"] += 1
69
+
70
+ try:
71
+ response = await call_next(request)
72
+ STATS["successful_requests"] += 1
73
+ process_time = time.time() - start_time
74
+ response.headers["X-Process-Time"] = str(process_time)
75
+ logger.info(f"{request.method} {request.url.path} - {response.status_code} - {process_time:.3f}s")
76
+ return response
77
+ except Exception as e:
78
+ STATS["failed_requests"] += 1
79
+ logger.error(f"{request.method} {request.url.path} - Error: {str(e)}")
80
+ raise
81
+
82
+ # Exception handler
83
+ @app.exception_handler(Exception)
84
+ async def global_exception_handler(request: Request, exc: Exception):
85
+ logger.error(f"Unhandled exception: {exc}", exc_info=True)
86
+ return JSONResponse(
87
+ status_code=500,
88
+ content={
89
+ "ok": False,
90
+ "error": "Internal server error",
91
+ "detail": str(exc) if os.getenv("DEBUG") else "An error occurred"
92
+ }
93
+ )
94
+
95
+ # Health check endpoint
96
+ @app.get("/health")
97
+ def health_check():
98
+ """健康检查端点"""
99
+ uptime = (datetime.now() - STATS["start_time"]).total_seconds()
100
+ return {
101
+ "status": "healthy",
102
+ "version": "1.0.0",
103
+ "uptime_seconds": uptime,
104
+ "loaded_cases": len(SCENARIOS),
105
+ "stats": {
106
+ "total_requests": STATS["total_requests"],
107
+ "successful_requests": STATS["successful_requests"],
108
+ "failed_requests": STATS["failed_requests"],
109
+ "success_rate": STATS["successful_requests"] / max(STATS["total_requests"], 1)
110
+ }
111
+ }
112
+
113
+ # Statistics endpoint
114
+ @app.get("/stats")
115
+ def get_stats():
116
+ """获取详细统计信息"""
117
+ return {
118
+ "stats": STATS,
119
+ "loaded_cases": list(SCENARIOS.keys()),
120
+ "uptime": str(datetime.now() - STATS["start_time"])
121
+ }
122
+
123
+ def _apply_progressive_reveal_at_init(scenario: GraphScenario):
124
+ """
125
+ 在初始化时应用渐进式暴露机制(基于ITEM/HIDDEN_ITEM边)
126
+
127
+ 新逻辑:
128
+ - 如果一个节点没有 ITEM/HIDDEN_ITEM 类型的入边,它就是初始可见的
129
+ - 如果一个节点有 ITEM/HIDDEN_ITEM 类型的入边,它初始不可见,需要等待上游触发
130
+
131
+ Args:
132
+ scenario: 场景对象
133
+ """
134
+ # 收集所有有 ITEM/HIDDEN_ITEM 入边的节点
135
+ nodes_with_item_edges = set()
136
+ for edge in scenario.edges:
137
+ if edge.connection_type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]:
138
+ nodes_with_item_edges.add(edge.target_id)
139
+
140
+ logger.info(f"Nodes with ITEM/HIDDEN_ITEM incoming edges: {nodes_with_item_edges}")
141
+
142
+ # 设置初始可见性:没有 ITEM/HIDDEN_ITEM 入边的节点初始可见
143
+ initially_visible_count = 0
144
+ for node_id, node in scenario.nodes.items():
145
+ if node_id not in nodes_with_item_edges:
146
+ node.is_revealed = True
147
+ initially_visible_count += 1
148
+ logger.info(f"Initial visible (no ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})")
149
+ else:
150
+ node.is_revealed = False
151
+ logger.debug(f"Initial hidden (has ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})")
152
+
153
+ logger.info(f"Progressive reveal initialized: {initially_visible_count}/{len(scenario.nodes)} nodes initially visible")
154
+
155
+
156
+ def _check_inputs_match_golden(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> bool:
157
+ """
158
+ 检查实际输入参数是否与 golden inputs 完全匹配
159
+
160
+ Args:
161
+ arguments: 实际调用时传入的参数
162
+ golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value)
163
+
164
+ Returns:
165
+ True 表示所有 golden inputs 都存在且值匹配
166
+ """
167
+ if not golden_inputs:
168
+ return True # 如果没有 golden inputs,认为匹配
169
+
170
+ for key, expected_value in golden_inputs.items():
171
+ actual_value = arguments.get(key)
172
+ # 转换为字符串比较,避免类型问题(如 int vs str)
173
+ if str(actual_value) != str(expected_value):
174
+ logger.debug(f"Input mismatch for '{key}': expected '{expected_value}', got '{actual_value}'")
175
+ return False
176
+
177
+ return True
178
+
179
+
180
+ def _get_parameter_validation_feedback(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> Dict[str, Any]:
181
+ """
182
+ 对源头节点的参数进行详细验证,返回验证反馈
183
+
184
+ 注意:不返回期望值(expected),避免泄漏答案
185
+
186
+ Args:
187
+ arguments: 实际调用时传入的参数
188
+ golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value)
189
+
190
+ Returns:
191
+ 包含验证结果的字典:
192
+ - all_correct: bool - 所有参数是否正确
193
+ - correct_params: List[str] - 正确的参数名列表
194
+ - incorrect_params: List[str] - 错误的参数名列表(不包含期望值)
195
+ """
196
+ if not golden_inputs:
197
+ return {
198
+ "all_correct": True,
199
+ "correct_params": [],
200
+ "incorrect_params": []
201
+ }
202
+
203
+ correct_params = []
204
+ incorrect_params = []
205
+
206
+ for key, actual_value in arguments.items():
207
+ # 只对用户实际提交的参数给反馈,未提交的参数不评价
208
+ if key not in golden_inputs:
209
+ continue # 该参数不在 golden 中,跳过(如 _golden_inputs 等内部参数)
210
+ expected_value = golden_inputs[key]
211
+ # 转换为字符串比较,避免类型问题(如 int vs str)
212
+ if str(actual_value) == str(expected_value):
213
+ correct_params.append(key)
214
+ else:
215
+ # 只记录参数名,不包含期望值,避免泄漏答案
216
+ incorrect_params.append(key)
217
+
218
+ # all_correct:用户提交的所有参数都正确,且覆盖了全部 golden 参数
219
+ all_provided_correct = len(incorrect_params) == 0
220
+ all_golden_covered = all(k in arguments for k in golden_inputs)
221
+ return {
222
+ "all_correct": all_provided_correct and all_golden_covered,
223
+ "correct_params": correct_params,
224
+ "incorrect_params": incorrect_params
225
+ }
226
+
227
+
228
+ def _is_source_node(node_id: str, scenario: GraphScenario) -> bool:
229
+ """
230
+ 判断节点是否是源头节点(完全没有任何入边的节点)
231
+
232
+ 源头节点定义:
233
+ - 没有任何类型的入边(包括 DATA、ITEM、HIDDEN_ITEM)
234
+ - 即没有任何上游节点
235
+
236
+ Args:
237
+ node_id: 节点ID
238
+ scenario: 场景对象
239
+
240
+ Returns:
241
+ True 表示是源头节点
242
+ """
243
+ for edge in scenario.edges:
244
+ if edge.target_id == node_id:
245
+ # 只要有任何入边,就不是源头节点
246
+ return False
247
+
248
+ return True
249
+
250
+
251
+ def _check_and_reveal_ready_nodes(scenario: GraphScenario, recent_outputs: Dict[str, Any], source_node_id: str) -> List[Dict[str, Any]]:
252
+ """
253
+ 检查并释放参数齐全的隐藏节点(渐进式暴露机制)
254
+
255
+ 核心逻辑:
256
+ 1. 维护"可见值集合":包含所有被测模型当前可以看到的值
257
+ - init_inputs 的值(初始可见)
258
+ - 工具执行后的实际输出值(运行时获得)
259
+ - 可见 Item 的输出值
260
+ 2. 检查隐藏节点:该节点的所有 golden_input 值是否都在可见值集合中
261
+ 3. 如果是,则释放该节点
262
+
263
+ Args:
264
+ scenario: 场景对象
265
+ recent_outputs: 最近执行的工具的输出
266
+ source_node_id: 刚执行的工具节点ID
267
+
268
+ Returns:
269
+ 新释放的节点列表
270
+ """
271
+ newly_revealed = []
272
+
273
+ # 构建"可见值集合"(Set of visible values)
274
+ # 存储格式:set of values (转为字符串)
275
+ visible_values = set()
276
+
277
+ # 1. 添加有意义的 init_inputs 值到可见值集合
278
+ # Item 的 init_inputs 不应该加入,因为它们在密室中完全用不到
279
+ for node_id, node in scenario.nodes.items():
280
+ # 跳过源头 Item 节点(没有入边的 Item)
281
+ if node.type == "Item":
282
+ has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges)
283
+ if not has_incoming_edge:
284
+ # 这是源头 Item,跳过其 init_inputs
285
+ continue
286
+
287
+ # 添加其他节点的 init_inputs
288
+ for port_name, init_value in node.init_input_values.items():
289
+ if init_value:
290
+ visible_values.add(str(init_value))
291
+
292
+ # 2. 添加已执行工具的所有历史输出值
293
+ for node_id, node in scenario.nodes.items():
294
+ if node.type == "Tool" and node.if_success and node.actual_outputs_history:
295
+ # 遍历所有历史执行记录
296
+ for output_dict in node.actual_outputs_history:
297
+ for output_port_name, output_value in output_dict.items():
298
+ if output_value:
299
+ visible_values.add(str(output_value))
300
+
301
+ # 3. 添加已被 investigate 的 Item 的 golden 输出值
302
+ # 注意:Item 可见不等于其输出值可见,需要 investigate 后才能获得
303
+ # 这里我们使用 actual_outputs_history 来标记 Item 是否已被 investigate
304
+ for node_id, node in scenario.nodes.items():
305
+ if node.type == "Item" and node.is_revealed and node.actual_outputs_history:
306
+ # Item 通常只会被 investigate 一次,但为了一致性也使用历史列表
307
+ for output_dict in node.actual_outputs_history:
308
+ for port_name, port_value in output_dict.items():
309
+ if port_value:
310
+ visible_values.add(str(port_value))
311
+
312
+ # 遍历所有隐藏的节点,检查其 golden_input 是否都在可见值集合中
313
+ for node_id, node in scenario.nodes.items():
314
+ # 跳过已可见的节点
315
+ if node.is_revealed:
316
+ continue
317
+
318
+ # 只检查工具节点(物品节点由 ITEM 输出触发)
319
+ if node.type != "Tool":
320
+ continue
321
+
322
+ # 检查该节点的所有 golden_input 值是否都在可见值集合中
323
+ all_inputs_ready = True
324
+ missing_values = []
325
+
326
+ for input_port_name, golden_input_value in node.golden_input_values.items():
327
+ # 检查这个 golden 值是否在可见值集合中
328
+ if str(golden_input_value) not in visible_values:
329
+ all_inputs_ready = False
330
+ missing_values.append(f"{input_port_name}={golden_input_value}")
331
+
332
+ # 如果所有 golden_input 值都在可见值集合中,释放该节点
333
+ if all_inputs_ready and len(node.golden_input_values) > 0:
334
+ logger.info(f"All golden inputs ready for {node_id}: {list(node.golden_input_values.values())}")
335
+
336
+ # 如果所有输入都齐全,释放该节点
337
+ if all_inputs_ready:
338
+ node.is_revealed = True
339
+
340
+ # 构建节点信息返回给模型
341
+ node_info = {
342
+ "id": node.id,
343
+ "type": node.type,
344
+ "can_investigate": True,
345
+ "hint": "This tool's input parameters are now complete, you can use investigate to view detailed information"
346
+ }
347
+
348
+ # if node.name:
349
+ # node_info["name"] = node.name
350
+ if node.description:
351
+ node_info["description"] = node.description
352
+
353
+ newly_revealed.append(node_info)
354
+ logger.info(f"Progressive reveal: {node_id} is now ready (all inputs satisfied)")
355
+
356
+ return newly_revealed
357
+
358
+
359
+ def _initialize_node_values(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]):
360
+ """
361
+ Initialize node state and load values from port value fields.
362
+ 应用渐进式暴露机制:初始时只显示参数齐全的节点(源头节点)
363
+
364
+ 重要区分:
365
+ 1. input_values: 只加载 metadata.initial_values 中的 init_inputs(真正的初始值)
366
+ 2. output_values: 加载 nodes[].outputs[].value(golden 输出,用于验证)
367
+ """
368
+ # 第一步:加载所有节点的值,并将所有节点初始设为隐藏
369
+ initial_values = metadata.get('initial_values', {})
370
+
371
+ for node_id, node in scenario.nodes.items():
372
+ # 忽略 initial_visible 字段,初始全部隐藏
373
+ # 由渐进式暴露机制根据参数齐全情况决定是否显示
374
+ node.is_revealed = False
375
+
376
+ if node.type == "Tool":
377
+ node.if_success = False
378
+ node.actual_outputs_history = [] # 清空历史输出
379
+ elif node.type == "Item":
380
+ node.if_success = False
381
+ node.actual_outputs_history = [] # 清空历史输出
382
+
383
+ # 从 JSON 加载值
384
+ if node_id in raw_nodes_data:
385
+ node_data = raw_nodes_data[node_id] # node_data是json文件中nodes中的字典
386
+
387
+ # 【重要】只加载 metadata.initial_values 中的初始输入值
388
+ if node_id in initial_values:
389
+ init_data = initial_values[node_id]
390
+ # 加载初始输入值(用于渐进式暴露判断)
391
+ for port_name, port_value in init_data.get('init_inputs', {}).items():
392
+ node.init_input_values[port_name] = port_value
393
+
394
+ # 【评测用】加载 golden 输入值(用于验证模型传入的参数是否正确)
395
+ for input_port_data in node_data.get('inputs', []):
396
+ if 'value' in input_port_data:
397
+ node.golden_input_values[input_port_data['name']] = input_port_data['value']
398
+
399
+ # 【评测用】加载 golden 输出值(用于验证工具调用是否正确,以及 Item 节点的 content)
400
+ for output_port_data in node_data.get('outputs', []):
401
+ if 'value' in output_port_data:
402
+ node.golden_output_values[output_port_data['name']] = output_port_data['value']
403
+
404
+ # For Items, set content from golden_output_values
405
+ if node.type == "Item" and node.golden_output_values:
406
+ # Item 的 content 是其第一个 golden 输出值
407
+ node.content = list(node.golden_output_values.values())[0]
408
+
409
+ # 第二步:应用渐进式暴露机制
410
+ # 检查所有节点,根据参数齐全情况释放源头节点(工具 + Item)
411
+ _apply_progressive_reveal_at_init(scenario)
412
+
413
+ def _build_node_info(node: Node, raw_nodes_data: Dict[str, Any]) -> Dict[str, Any]:
414
+ """
415
+ 构建节点信息(工具或物品)
416
+
417
+ Args:
418
+ node: 节点对象
419
+ raw_nodes_data: 原始节点数据(用于获取 template_id 等)
420
+
421
+ Returns:
422
+ 节点信息字典
423
+ """
424
+ if node.type == "Tool":
425
+ # 过滤掉输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口)
426
+ # 这些端口仅用于控制掉落机制,不应暴露给 Agent
427
+ # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到)
428
+ tool_info = {
429
+ "id": node.id,
430
+ # "name": node.name,
431
+ "description": node.description,
432
+ "type": "Tool",
433
+ "inputs": [{"name": p.name, "type": p.type, "description": p.description}
434
+ for p in node.inputs if p.type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]],
435
+ "outputs": [{"name": p.name, "type": p.type, "description": p.description}
436
+ for p in node.outputs]
437
+ }
438
+
439
+ # 添加 template_id(工具的标准名称)
440
+ if node.id in raw_nodes_data:
441
+ node_data = raw_nodes_data[node.id]
442
+ template_id = node_data.get('template_id')
443
+ if template_id:
444
+ tool_info['template_id'] = template_id
445
+
446
+ return tool_info
447
+
448
+ elif node.type == "Item":
449
+ return {
450
+ "id": node.id,
451
+ # "name": node.name,
452
+ "description": node.description,
453
+ "type": "Item"
454
+ }
455
+
456
+ else:
457
+ return {
458
+ "id": node.id,
459
+ # "name": node.name,
460
+ "type": node.type
461
+ }
462
+
463
+ def _get_initial_observation(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]) -> Dict[str, Any]:
464
+ """
465
+ Generate initial observation for the agent (what they see when entering the room).
466
+
467
+ 策略:
468
+ - Tools: 只显示名称和描述,不显示接口定义。需要 investigate 才能获得详细接口信息。
469
+ - Items: 只显示存在,不显示内容。需要 investigate 才能获得内容值。
470
+ - init_inputs: 作为"可用信息"告诉模型,这些是可以用作工具参数的初始值。
471
+ - init_outputs: 不告诉模型(这些是答案,需要模型通过调用工具获得)。
472
+ """
473
+ available_entities = [] # 统一的实体列表(Tools 和 Items)
474
+ available_information = [] # 可用的初始信息(来自 init_inputs)
475
+
476
+ # 从 metadata.initial_values 提取 init_inputs 作为可用信息
477
+ # 只提供值本身,不透露这些值对应哪个节点的哪个参数,让模型自己推理
478
+ # 注意:跳过源头 Item(没有入边的 Item)的 init_inputs,因为它们在密室中完全用不到
479
+ initial_values = metadata.get('initial_values', {})
480
+ # initial_values字段的格式
481
+ # "initial_values": {
482
+ # "terminal_1": {
483
+ # "init_inputs": {},
484
+ # "init_outputs": {
485
+ # "text_output": "System initialization complete.",
486
+ # "hex_output": "48656c6c6f20576f726c64",
487
+ # "item_dispenser": "掉落了一张纸条,上面写着“请勿随意触摸终端”"
488
+ # }
489
+ # }
490
+ # }
491
+ for node_id, init_data in initial_values.items():
492
+ # 获取节点信息,判断是否为源头 Item
493
+ node = scenario.nodes.get(node_id)
494
+ if node and node.type == "Item":
495
+ # 检查是否为源头 Item(没有入边)
496
+ has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges)
497
+ if not has_incoming_edge:
498
+ # 这是源头 Item,检查是否有 init_inputs
499
+ init_inputs = init_data.get('init_inputs', {})
500
+ if init_inputs:
501
+ # 有 init_inputs,需要暴露这些参数
502
+ for param_name, param_value in init_inputs.items():
503
+ available_information.append({
504
+ "value": param_value
505
+ })
506
+ # 处理完后跳过后续的通用逻辑
507
+ continue
508
+
509
+ init_inputs = init_data.get('init_inputs', {})
510
+ if init_inputs:
511
+ # 为每个 init_input 值创建一个信息条目(不包含 source_node 和 parameter 信息)
512
+ for param_name, param_value in init_inputs.items():
513
+ available_information.append({
514
+ "value": param_value
515
+ })
516
+
517
+ for node in scenario.nodes.values():
518
+ if node.is_revealed:
519
+ # Tools: 只显示基本信息,提示可以 investigate 查看详细接口
520
+ if node.type == "Tool":
521
+ tool_info = {
522
+ "id": node.id, # 这里只有id而没有template_id
523
+ "type": "Tool",
524
+ "can_investigate": True, # 可以被 investigate
525
+ "hint": "You can use investigate to view the tool's detailed interface information for calling"
526
+ }
527
+ # 只在 name 非空时添加
528
+ # if node.name:
529
+ # tool_info["name"] = node.name
530
+ # 只在 description 非空时添加
531
+ if node.description:
532
+ tool_info["description"] = node.description
533
+
534
+ available_entities.append(tool_info)
535
+
536
+ # Items: 只显示基本信息,提示可以 investigate 查看内容
537
+ elif node.type == "Item":
538
+ item_info = {
539
+ "id": node.id, # 这里只有id而没有template_id
540
+ "type": "Item",
541
+ "can_investigate": True, # 可以被 investigate
542
+ "hint": "You can use investigate to view the item's content"
543
+ }
544
+ # 只在 name 非空时添加
545
+ # if node.name:
546
+ # item_info["name"] = node.name
547
+ # 只在 description 非空时添加
548
+ if node.description:
549
+ item_info["description"] = node.description
550
+
551
+ available_entities.append(item_info)
552
+
553
+ return {
554
+ "narrative": scenario.intro_narrative,
555
+ "available_entities": available_entities, # 使用统一的实体列表
556
+ "available_information": available_information, # 可用的初始信息(只包含 init_inputs)
557
+ "win_node_id": scenario.win_node_id # 胜利节点ID,让模型知道需要关注哪个节点
558
+ }
559
+
560
+ @app.post("/env/reset")
561
+ def reset_case(case_id: str = None, case_file_path: str = None, session_id: str = None):
562
+ """Loads a specific case from file and resets it.
563
+
564
+ Args:
565
+ case_id: Optional case ID for resetting an existing case
566
+ case_file_path: Path to case file for loading a new case
567
+ session_id: Optional session ID to ensure isolation between concurrent evaluations
568
+ """
569
+ logger.info(f"Reset request - case_id: {case_id}, case_file_path: {case_file_path}, session_id: {session_id}")
570
+ STATS["case_loads"] += 1
571
+
572
+ if case_file_path:
573
+ if not os.path.exists(case_file_path):
574
+ logger.error(f"Case file not found: {case_file_path}")
575
+ raise HTTPException(status_code=404, detail=f"File not found: {case_file_path}")
576
+ try:
577
+ with open(case_file_path, "r", encoding="utf-8") as f:
578
+ file_data = json.load(f)
579
+
580
+ # 转换格式:从 DAG executor 生成的格式转换为 GraphScenario 格式
581
+ # 1. 提取 metadata
582
+ metadata = file_data.get('metadata', {})
583
+
584
+ # 2. 生成 case_id, title, intro_narrative
585
+ # 【修复】为每个评测会话生成唯一的 case_id,防止并发评测时状态污染
586
+ base_name = os.path.basename(case_file_path).replace('.json', '').replace('_full', '').replace('_full2', '')
587
+
588
+ if session_id:
589
+ # 如果提供了 session_id,使用它来确保唯一性
590
+ case_id = f"{base_name}_{session_id}"
591
+ else:
592
+ # 否则使用时间戳和随机数确保唯一性
593
+ unique_suffix = f"{int(time.time() * 1000)}_{random.randint(1000, 9999)}"
594
+ case_id = f"{base_name}_{unique_suffix}"
595
+
596
+ file_data['case_id'] = case_id
597
+ logger.info(f"Generated unique case_id: {case_id} (base: {base_name}, session: {session_id})")
598
+
599
+ if 'title' not in file_data:
600
+ file_data['title'] = f"Escape Room: {file_data['case_id']}"
601
+
602
+ if 'intro_narrative' not in file_data: # 目前的json文件中已经有了intro_narrative字段,不会使用下面一行的内容,而是使用每个评测问题的json文件中的对应字段
603
+ file_data['intro_narrative'] = 'You are trapped in a locked room. There may be tools and items in the environment - explore them and find a way to escape. You need to find a victory string to escape. When you obtain the victory string and submit it correctly, the system will clearly indicate: "🎉 Congratulations on successfully escaping the room! Your answer is correct: [your answer]".'
604
+
605
+ # 3. 转换 nodes 列表为字典(DAG executor 生成的文件中 nodes 是列表格式)
606
+ nodes_dict = {}
607
+ for node_data in file_data['nodes']:
608
+ nodes_dict[node_data['id']] = node_data # 这里的id是template_id之后可能添加一个后缀
609
+ file_data['nodes'] = nodes_dict # 把列表转成一个字典
610
+
611
+ # 4. 添加缺失的字段
612
+ if 'difficulty' not in file_data:
613
+ file_data['difficulty'] = metadata.get('total_nodes', 5)
614
+
615
+ if 'win_node_id' not in file_data:
616
+ file_data['win_node_id'] = metadata.get('win_node_id', '')
617
+
618
+ scenario = GraphScenario(**file_data)
619
+
620
+ # Extract raw nodes data for template_id access
621
+ # nodes 已经在上面转换为字典格式
622
+ raw_nodes_data = file_data.get('nodes', {})
623
+ RAW_NODES_DATA[scenario.case_id] = raw_nodes_data
624
+
625
+ # Store metadata for initial values access
626
+ FILE_METADATA[scenario.case_id] = metadata
627
+
628
+ logger.info(f"Successfully parsed case file: {scenario.case_id}, nodes: {len(scenario.nodes)}, edges: {len(scenario.edges)}")
629
+ except Exception as e:
630
+ logger.error(f"Failed to load case file: {str(e)}", exc_info=True)
631
+ raise HTTPException(status_code=500, detail=f"Failed to load case file: {str(e)}")
632
+
633
+ # Initialize node state and load values
634
+ _initialize_node_values(scenario, raw_nodes_data, metadata)
635
+
636
+ SCENARIOS[scenario.case_id] = scenario
637
+ simulator = ToolSimulator()
638
+ SIMULATORS[scenario.case_id] = simulator
639
+
640
+ logger.info(f"Case {scenario.case_id} initialized successfully - tools: {len([n for n in scenario.nodes.values() if n.type == 'Tool'])}, items: {len([n for n in scenario.nodes.values() if n.type == 'Item'])}")
641
+
642
+ # 生成初始观察信息(进入密室后看到的环境)
643
+ initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata)
644
+ '''
645
+ initial_observation的格式:
646
+ {
647
+ "narrative": scenario.intro_narrative,
648
+ "available_entities": available_entities # 使用统一的实体列表
649
+ "available_information": available_information # 可用的初始信息(只包含 init_inputs)
650
+ }
651
+ '''
652
+
653
+ return {
654
+ "ok": True,
655
+ "message": f"Case loaded from {case_file_path}",
656
+ "case_id": scenario.case_id,
657
+ **initial_observation # 直接展开初始观察信息
658
+ }
659
+
660
+ # 如果没有提供 case_file_path,但提供了 case_id,则尝试从内存重置
661
+ if case_id and case_id in SCENARIOS:
662
+ scenario = SCENARIOS[case_id]
663
+ raw_nodes_data = RAW_NODES_DATA.get(case_id, {})
664
+ metadata = FILE_METADATA.get(case_id, {})
665
+
666
+ # Reset dynamic fields and re-apply progressive reveal
667
+ # 重新初始化节点状态(包括渐进式暴露)
668
+ _initialize_node_values(scenario, raw_nodes_data, metadata)
669
+
670
+ logger.info(f"Case {case_id} reset - tools: {len([n for n in scenario.nodes.values() if n.type == 'Tool'])}, items: {len([n for n in scenario.nodes.values() if n.type == 'Item'])}")
671
+
672
+ # 生成初始观察信息
673
+ initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata)
674
+
675
+ return {
676
+ "ok": True,
677
+ "message": f"Case {case_id} reset.",
678
+ "case_id": case_id,
679
+ **initial_observation # 直接展开初始观察信息
680
+ }
681
+
682
+ # 如果既没有 case_file_path,也没有在内存中找到,返回错误
683
+ raise HTTPException(
684
+ status_code=400,
685
+ detail="Must provide case_file_path to load a new case, or use case_id to reset an existing case."
686
+ )
687
+
688
+ class InvestigateRequest(BaseModel):
689
+ node_id: str
690
+
691
+ @app.post("/env/{case_id}/investigate")
692
+ def investigate(case_id: str, req: InvestigateRequest):
693
+ """
694
+ Investigates a Tool or Item to reveal detailed information.
695
+
696
+ - For Tools: Returns detailed interface information (inputs/outputs) needed to call the tool
697
+ - For Items: Returns content value and triggers hidden item drops
698
+ """
699
+ logger.info(f"Investigate request - case_id: {case_id}, node_id: {req.node_id}")
700
+ STATS["investigates"][case_id] += 1
701
+
702
+ if case_id not in SCENARIOS:
703
+ logger.error(f"Case not found: {case_id}")
704
+ raise HTTPException(status_code=404, detail="Case not found")
705
+
706
+ scenario = SCENARIOS[case_id]
707
+ if req.node_id not in scenario.nodes:
708
+ logger.error(f"Node not found: {req.node_id} in case {case_id}")
709
+ raise HTTPException(status_code=404, detail="Node not found")
710
+
711
+ node = scenario.nodes[req.node_id]
712
+
713
+ if not node.is_revealed:
714
+ logger.warning(f"Attempt to investigate hidden node: {req.node_id}")
715
+ return {"ok": False, "error": "Node is not visible yet."}
716
+
717
+ raw_nodes_data = RAW_NODES_DATA.get(case_id, {})
718
+ newly_revealed = []
719
+
720
+ # 处理 Tool 的 investigate
721
+ if node.type == "Tool":
722
+ logger.info(f"Investigating tool: {req.node_id}")
723
+
724
+ # 返回工具的详细接口信息
725
+ # id 字段使用 node.id(节点唯一标识),agent 用这个字段识别和调用具体的节点
726
+ # template_id 是工具类型标识符,Agent 内部用于判断工具特性(如 terminal 类工具参数可选)
727
+ # 注意:只过滤输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口),这些端口仅用于控制掉落,不应暴露给 Agent
728
+ # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到)
729
+ # 【端口上游依赖提示 & 初始值直接给出】
730
+ # 针对参数语义模糊(全为数字类型)的工具,在 investigate 返回信息中标注
731
+ # 哪个输入端口来自哪个上游节点(upstream_from)。
732
+ # 对于所有工具:若该节点不是纯源头节点(有任意数据流入边),
733
+ # 且某个端口没有上游入边(值来自初始可见参数),则直接给出该端口的 golden input 值。
734
+ AMBIGUOUS_TOOLS = {
735
+ "num_base_convert", "calc_modexp", "calc_modexp_int",
736
+ "calc_inv_mod", "calc_inv_mod_int", "crypto_rsa_decrypt_hex", "geo_haversine"
737
+ }
738
+ # Terminal 类工具自带参数对错反馈机制,玩家/模型可自行试错,
739
+ # 无需在 investigate 时直接暴露 init_value
740
+ SELF_FEEDBACK_TOOLS = {
741
+ "terminal_1", "terminal_2",
742
+ "Logic Terminal", "Math Terminal", "Encryption Terminal", "Sequence Terminal"
743
+ }
744
+ _template_id_for_hint = raw_nodes_data.get(node.id, {}).get("template_id", "")
745
+ # 构建数据流入边映射(对所有工具):{target_port -> (source_node_id, source_port)}
746
+ _upstream_map = {}
747
+ for _edge in scenario.edges:
748
+ if (_edge.target_id == node.id
749
+ and _edge.connection_type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]
750
+ and _edge.target_port is not None):
751
+ _upstream_map[_edge.target_port] = (_edge.source_id, _edge.source_port)
752
+ # 判断该节点是否有任意数据流入边(即不是纯源头节点)
753
+ _has_any_upstream = len(_upstream_map) > 0
754
+ # 判断该节点是否有任意入边(包括 ITEM/HIDDEN_ITEM 掉落边)
755
+ # 有任意入边(含掉落边)但无数据流入边的节点,其输入来自初始可见参数,应直接给出
756
+ _has_any_edge = any(_edge.target_id == node.id for _edge in scenario.edges)
757
+ # 构建 inputs 列表
758
+ _inputs_list = []
759
+ for p in node.inputs:
760
+ if p.type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]:
761
+ continue
762
+ port_dict = {"name": p.name, "type": p.type, "description": p.description}
763
+ if p.name in _upstream_map:
764
+ # 该端口有上游数据流依赖,且属于语义模糊工具 → 标注来源
765
+ if _template_id_for_hint in AMBIGUOUS_TOOLS:
766
+ src_node_id, src_port = _upstream_map[p.name]
767
+ port_dict["upstream_from"] = f"{src_node_id}.{src_port}" if src_port else src_node_id
768
+ elif _has_any_edge and _template_id_for_hint not in SELF_FEEDBACK_TOOLS:
769
+ # 该节点有任意入边,但此端口没有数据流入边 → 值来自初始可见参数,直接给出
770
+ # 排除自带反馈机制的 terminal 类工具(它们通过执行结果反馈对错,无需提前暴露参数值)
771
+ golden_val = node.golden_input_values.get(p.name)
772
+ if golden_val is not None:
773
+ port_dict["init_value"] = golden_val
774
+ _inputs_list.append(port_dict)
775
+
776
+ tool_details = {
777
+ "id": node.id, # 节点 ID,用于唯一标识和调用这个具体节点
778
+ "type": "Tool",
779
+ "inputs": _inputs_list,
780
+ "outputs": [{"name": p.name, "type": p.type, "description": p.description}
781
+ for p in node.outputs]
782
+ }
783
+
784
+ # 添加 template_id 用于 Agent 内部判断工具类型(不会展示给被测模型)
785
+ if node.id in raw_nodes_data:
786
+ template_id = raw_nodes_data[node.id].get('template_id')
787
+ if template_id:
788
+ tool_details["_template_id"] = template_id # 使用下划线前缀标记为内部字段
789
+
790
+ # 只在 name 非空时添加
791
+ # if node.name:
792
+ # tool_details["name"] = node.name
793
+ # 只在 description 非空时添加
794
+ if node.description:
795
+ tool_details["description"] = node.description
796
+
797
+ # 添加 narrative 字段(如果存在)
798
+ if node.id in raw_nodes_data:
799
+ narrative = raw_nodes_data[node.id].get('narrative')
800
+ if narrative:
801
+ tool_details['narrative'] = narrative
802
+
803
+ # 不再返回 init_values,避免泄漏答案
804
+ # investigate 只应该返回工具的接口定义,不应该暴露初始值
805
+
806
+ # 【新增】检查该 Tool 是否有待触发的 HIDDEN_ITEM 掉落
807
+ # 如果该工具已按照 golden_input 正确执行,且有 HIDDEN_ITEM 输出边,则触发掉落
808
+ if node.has_hidden_item_ready:
809
+ logger.info(f"Tool has HIDDEN_ITEM ready - triggering passive drop for: {req.node_id}")
810
+
811
+ # 遍历该工具的所有 HIDDEN_ITEM 输出边
812
+ for edge in scenario.edges:
813
+ if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM:
814
+ target_node = scenario.nodes[edge.target_id]
815
+
816
+ if not target_node.is_revealed:
817
+ target_node.is_revealed = True
818
+ # 构建基本节点信息(不包含详细内容)
819
+ node_info = {
820
+ "id": target_node.id,
821
+ "type": target_node.type,
822
+ "can_investigate": True,
823
+ "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content"
824
+ }
825
+ # 只在 name 非空时添加
826
+ # if target_node.name:
827
+ # node_info["name"] = target_node.name
828
+ # 只在 description 非空时添加
829
+ if target_node.description:
830
+ node_info["description"] = target_node.description
831
+
832
+ newly_revealed.append(node_info)
833
+ logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)")
834
+
835
+ # 重置标志,已经触发过了,避免重复
836
+ node.has_hidden_item_ready = False
837
+
838
+ logger.info(f"Tool investigation successful - node: {req.node_id}, revealed: {len(newly_revealed)}")
839
+
840
+ # 构建返回结果
841
+ result = {
842
+ "ok": True,
843
+ "entity_type": "Tool",
844
+ "details": tool_details
845
+ }
846
+
847
+ # 如果有新掉落的节点,添加到响应中
848
+ if newly_revealed:
849
+ result["newly_revealed"] = newly_revealed
850
+
851
+ return result
852
+
853
+ # 处理 Item 的 investigate
854
+ elif node.type == "Item":
855
+ logger.info(f"Investigating item: {req.node_id}")
856
+
857
+ # 【第一步】检查该 Item 是否有需要参数的输入端口
858
+ # 如果有,且尚未通过 use_item 验证,则不返回内容,只返回参数要求
859
+ required_inputs = []
860
+ if node.id in raw_nodes_data:
861
+ raw_node = raw_nodes_data[node.id]
862
+ inputs_info = raw_node.get('inputs', [])
863
+ required_inputs = [
864
+ {
865
+ "name": inp.get("name"),
866
+ "type": inp.get("type"),
867
+ "description": inp.get("description", "")
868
+ }
869
+ for inp in inputs_info
870
+ if inp.get("type") not in ["Item", "Hidden_Item"]
871
+ ]
872
+
873
+ # 如果有 required_inputs 且尚未通过 use_item 验证(if_success == False)
874
+ # 则不返回内容,只返回参数要求提示
875
+ if required_inputs and not node.if_success:
876
+ logger.info(f"Item has required inputs and not yet unlocked: {req.node_id}")
877
+ result = {
878
+ "ok": True,
879
+ "entity_type": "Item",
880
+ "required_inputs": required_inputs
881
+ }
882
+
883
+ # 添加 narrative
884
+ if node.id in raw_nodes_data:
885
+ raw_node = raw_nodes_data[node.id]
886
+ narrative = raw_node.get('narrative')
887
+ if narrative:
888
+ result['narrative'] = narrative
889
+
890
+ param_names = ', '.join([inp['name'] for inp in required_inputs])
891
+ result["hint"] = f"This item requires parameters to unlock. Use the use_item operation with the following exact parameter names (do not change or translate): {param_names}"
892
+
893
+ return result
894
+
895
+ # 【新增】如果有 required_inputs 且已经通过 use_item 验证(if_success == True)
896
+ # 则返回提示:该节点已经被成功解决
897
+ if required_inputs and node.if_success:
898
+ logger.info(f"Item has required inputs and already unlocked: {req.node_id}")
899
+ result = {
900
+ "ok": True,
901
+ "entity_type": "Item",
902
+ "message": "This item has already been successfully unlocked by you."
903
+ }
904
+ return result
905
+
906
+ # 【第二步】该 Item 没有 required_inputs 或已通过验证,返回内容
907
+ # 1. 返回 Item 的 golden_output_values(即 Item 的内容)
908
+ # 注意:某些 Item 仅用于触发 HIDDEN_ITEM 掉落,没有实际内容
909
+ has_actual_content = bool(node.golden_output_values) or node.content is not None
910
+ content = node.golden_output_values if node.golden_output_values else node.content
911
+
912
+ # 【关键】将 golden_output_values 追加到 actual_outputs_history,标记该 Item 已被 investigate
913
+ # 这样在渐进式暴露时,这些值才会被加入可见值集合
914
+ # 即使是空字典(仅触发 HIDDEN_ITEM 的 Item),也要记录,以便渐进式暴露逻辑知道该 Item 已被调查
915
+ if node.golden_output_values is not None:
916
+ node.actual_outputs_history.append(dict(node.golden_output_values))
917
+
918
+ # 2. Trigger Hidden Item Drops (Passive Drop)
919
+ for edge in scenario.edges:
920
+ if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM:
921
+ target_node = scenario.nodes[edge.target_id]
922
+ if not target_node.is_revealed:
923
+ target_node.is_revealed = True
924
+ # 构建基本节点信息(不包含详细内容)
925
+ node_info = {
926
+ "id": target_node.id,
927
+ "type": target_node.type,
928
+ "can_investigate": True,
929
+ "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content"
930
+ }
931
+ # 只在 name 非空时添加
932
+ # if target_node.name:
933
+ # node_info["name"] = target_node.name
934
+ # 只在 description 非空时添加
935
+ if target_node.description:
936
+ node_info["description"] = target_node.description
937
+
938
+ newly_revealed.append(node_info)
939
+ logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)")
940
+
941
+ logger.info(f"Item investigation successful - node: {req.node_id}, has_content: {has_actual_content}, revealed: {len(newly_revealed)}")
942
+
943
+ # 【渐进式暴露】旧机制(基于 golden_input)已禁用
944
+ # 现在完全由 ITEM/HIDDEN_ITEM 边触发控制节点可见性
945
+ # 上面的 HIDDEN_ITEM 掉落逻辑已经处理了节点释放
946
+ # progressive_revealed = _check_and_reveal_ready_nodes(scenario, node.golden_output_values or {}, node.id)
947
+ # if progressive_revealed:
948
+ # # 合并到 newly_revealed 中
949
+ # if newly_revealed:
950
+ # newly_revealed.extend(progressive_revealed)
951
+ # else:
952
+ # newly_revealed = progressive_revealed
953
+ # logger.info(f"Progressive reveal after Item investigate: {len(progressive_revealed)} nodes now ready")
954
+
955
+ # 构建返回结果
956
+ result = {
957
+ "ok": True,
958
+ "entity_type": "Item"
959
+ }
960
+
961
+ # 只在有实际内容时才添加 content 字段
962
+ # 对于仅触发 HIDDEN_ITEM 掉落的 Item,不返回 content 字段,避免返回 None 或空字典让模型困惑
963
+ if has_actual_content:
964
+ result["content"] = content
965
+
966
+ # 添加 narrative
967
+ if node.id in raw_nodes_data:
968
+ raw_node = raw_nodes_data[node.id]
969
+ narrative = raw_node.get('narrative')
970
+ if narrative:
971
+ result['narrative'] = narrative
972
+
973
+ if newly_revealed:
974
+ result["newly_revealed"] = newly_revealed
975
+
976
+ # 不再主动提示胜利字符串,让模型自己判断
977
+ # 模型通过 investigate 获得内容后,需要自己识别这是否是胜利字符串
978
+
979
+ return result
980
+
981
+ else:
982
+ logger.warning(f"Attempt to investigate unknown node type: {req.node_id} (type: {node.type})")
983
+ return {"ok": False, "error": f"Cannot investigate node type: {node.type}"}
984
+
985
+ class ToolCallRequest(BaseModel):
986
+ node_id: str # 使用 node_id 精确指定要调用的节点
987
+ arguments: Dict[str, Any]
988
+
989
+ @app.post("/env/{case_id}/tool_call")
990
+ def tool_call(case_id: str, req: ToolCallRequest):
991
+ """Executes a tool and triggers item drops."""
992
+ logger.info(f"Tool call request - case_id: {case_id}, node_id: {req.node_id}, args: {list(req.arguments.keys())}")
993
+ STATS["tool_calls"][case_id] += 1
994
+
995
+ if case_id not in SCENARIOS:
996
+ logger.error(f"Case not found: {case_id}")
997
+ raise HTTPException(status_code=404, detail="Case not found")
998
+
999
+ scenario = SCENARIOS[case_id]
1000
+ raw_nodes_data = RAW_NODES_DATA.get(case_id, {})
1001
+
1002
+ # 通过 node_id 精确查找节点
1003
+ node_id = req.node_id
1004
+ if node_id not in scenario.nodes:
1005
+ logger.error(f"Node not found: {node_id} in case {case_id}")
1006
+ raise HTTPException(status_code=404, detail="Node not found")
1007
+
1008
+ tool_node = scenario.nodes[node_id]
1009
+
1010
+ if not tool_node:
1011
+ logger.error(f"Tool not found: {node_id} in case {case_id}")
1012
+ raise HTTPException(status_code=404, detail="Tool not found")
1013
+
1014
+ if not tool_node.is_revealed:
1015
+ logger.warning(f"Attempt to call hidden tool: {node_id}")
1016
+ return {"ok": False, "error": "Tool is not visible yet."}
1017
+
1018
+ if tool_node.type != "Tool":
1019
+ logger.warning(f"Attempt to call non-tool node: {node_id} (type: {tool_node.type})")
1020
+ return {"ok": False, "error": "Only tools can be called."}
1021
+
1022
+ # 1. Execute Tool (Real Execution via Simulator)
1023
+ simulator = SIMULATORS[case_id]
1024
+
1025
+ # Get tool name from template_id if available, otherwise use node name
1026
+ tool_name = tool_node.name
1027
+ if case_id in RAW_NODES_DATA and node_id in RAW_NODES_DATA[case_id]:
1028
+ template_id = RAW_NODES_DATA[case_id][node_id].get('template_id')
1029
+ if template_id:
1030
+ tool_name = template_id
1031
+
1032
+ # 文件处理工具和 Terminal 需要验证输入并返回预先计算的输出
1033
+ # 传递节点的实际输入输出值(从 DAG 执行后填充的数据)
1034
+ tool_arguments = dict(req.arguments) # Make a copy
1035
+
1036
+ # 传递节点的 golden values(从 JSON 的 inputs[].value 和 outputs[].value 加载)
1037
+ # 用于在评测阶段验证被测模型传入的参数是否正确
1038
+ if tool_node.golden_input_values:
1039
+ tool_arguments['_golden_inputs'] = tool_node.golden_input_values
1040
+ if tool_node.golden_output_values:
1041
+ tool_arguments['_golden_outputs'] = tool_node.golden_output_values
1042
+
1043
+ logger.debug(f"Executing tool {tool_name} (node: {tool_node.name}) with args {tool_arguments}")
1044
+
1045
+ try:
1046
+ output_values = simulator.execute(tool_name, tool_arguments)
1047
+ logger.info(f"Tool invoked - {tool_name}: {list(output_values.keys())}")
1048
+ except Exception as e:
1049
+ logger.error(f"Tool execution failed - {tool_name}: {str(e)}", exc_info=True)
1050
+ return {"ok": False, "error": f"Tool execution failed: {str(e)}"}
1051
+
1052
+ # 检查验证结果(精细化错误反馈)
1053
+ validation = output_values.pop("_validation", {"valid": True})
1054
+
1055
+ if not validation["valid"]:
1056
+ # 根据错误类型构造友好的错误消息
1057
+ error_type = validation.get("error_type")
1058
+
1059
+ if error_type == "missing_required":
1060
+ missing = validation.get("missing_params", [])
1061
+ error_msg = f"Error: Missing required parameters {', '.join(missing)}"
1062
+
1063
+ elif error_type == "type_error":
1064
+ param = validation.get("param_name")
1065
+ message = validation.get("message", "Parameter type error")
1066
+ error_msg = f"Error: {message}"
1067
+
1068
+ elif error_type == "incomplete_optional":
1069
+ provided = validation.get("provided_params", [])
1070
+ missing = validation.get("missing_params", [])
1071
+ error_msg = (
1072
+ f"Hint: You provided some parameters ({', '.join(provided)}), "
1073
+ f"but may also need: {', '.join(missing)}.\n"
1074
+ f"Trying to provide these parameters together might yield better results."
1075
+ )
1076
+
1077
+ elif error_type == "value_mismatch":
1078
+ param = validation.get("param_name")
1079
+ hint = validation.get("hint", "Parameter value may be incorrect")
1080
+ error_msg = f"Hint: {hint}.\nPlease check if this parameter value meets the requirements."
1081
+
1082
+ else:
1083
+ error_msg = validation.get("hint") or validation.get("message", "Parameter validation failed")
1084
+
1085
+ logger.info(f"Tool validation failed - {tool_name}: {error_type}")
1086
+ return {
1087
+ "ok": False,
1088
+ "error": error_msg,
1089
+ "error_type": error_type
1090
+ }
1091
+
1092
+ # Simulate success
1093
+ tool_node.if_success = True
1094
+
1095
+ # 【关键】将本次执行的输出值追加到历史列表(用于渐进式暴露判断)
1096
+ # 每次调用都会记录,不会覆盖之前的执行结果
1097
+ tool_node.actual_outputs_history.append(dict(output_values))
1098
+
1099
+ # 2. 检查是否应该触发掉落(只有输入参数正确时才掉落)
1100
+ # 验证输入参数是否与 golden_input_values 匹配
1101
+ inputs_match_golden = _check_inputs_match_golden(req.arguments, tool_node.golden_input_values)
1102
+
1103
+ newly_revealed = []
1104
+ investigate_hints = [] # 提示模型哪些节点可以 investigate 来发现隐藏内容
1105
+
1106
+ if inputs_match_golden:
1107
+ logger.info(f"✓ Tool inputs match golden - node: {node_id}, triggering drops")
1108
+
1109
+ # 检查该工具是否有 ITEM 或 HIDDEN_ITEM 输出边
1110
+ for edge in scenario.edges:
1111
+ if edge.source_id == tool_node.id:
1112
+ target_node = scenario.nodes[edge.target_id]
1113
+
1114
+ # ITEM 边:立即掉落(主动掉落)
1115
+ if edge.connection_type == InterfaceType.ITEM:
1116
+ if not target_node.is_revealed:
1117
+ target_node.is_revealed = True
1118
+ # 构建基本节点信息(不包含详细内容)
1119
+ node_info = {
1120
+ "id": target_node.id,
1121
+ "type": target_node.type,
1122
+ "can_investigate": True,
1123
+ "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content"
1124
+ }
1125
+ # 只在 name 非空时添加
1126
+ # if target_node.name:
1127
+ # node_info["name"] = target_node.name
1128
+ # 只在 description 非空时添加
1129
+ if target_node.description:
1130
+ node_info["description"] = target_node.description
1131
+
1132
+ newly_revealed.append(node_info)
1133
+ logger.info(f"ITEM drop triggered: {target_node.id} (from {node_id})")
1134
+
1135
+ # HIDDEN_ITEM 边:不立即掉落,标记并提示(被动掉落)
1136
+ elif edge.connection_type == InterfaceType.HIDDEN_ITEM:
1137
+ # 标记该工具有待触发的 HIDDEN_ITEM 掉落
1138
+ tool_node.has_hidden_item_ready = True
1139
+
1140
+ # 提示模型可以 investigate 这个工具来发现隐藏内容
1141
+ hint_info = {
1142
+ "tool_id": tool_node.id,
1143
+ "hint": f"Tool '{tool_node.id}' seems to hide something, try investigating it to discover more information"
1144
+ }
1145
+ # if tool_node.name:
1146
+ # hint_info["tool_name"] = tool_node.name
1147
+
1148
+ investigate_hints.append(hint_info)
1149
+ logger.info(f"HIDDEN_ITEM ready: {tool_node.id} -> {target_node.id} (will drop on investigate)")
1150
+ else:
1151
+ logger.info(f"✗ Tool inputs do NOT match golden - node: {node_id}, no drops triggered")
1152
+
1153
+ response = {
1154
+ "ok": True,
1155
+ "message": "Tool invoked",
1156
+ "output_values": output_values # Return raw outputs to Agent
1157
+ }
1158
+
1159
+ # 【新增】对源头节点进行参数验证反馈
1160
+ # 源头节点:没有数据流入边的节点,这些节点的参数需要模型自己推理
1161
+ # 验证模型使用的参数是否正确,并提供明确的反馈
1162
+ if _is_source_node(node_id, scenario) and tool_node.golden_input_values:
1163
+ validation_feedback = _get_parameter_validation_feedback(req.arguments, tool_node.golden_input_values)
1164
+
1165
+ if validation_feedback["all_correct"]:
1166
+ # 用户提交了全部 golden 参数且全部正确
1167
+ response["parameter_feedback"] = {
1168
+ "status": "correct",
1169
+ "message": f"✓ All parameters are correct! This tool has been successfully solved. You can now proceed to explore downstream nodes that depend on this tool's output."
1170
+ }
1171
+ logger.info(f"✓ Source node parameters all correct - node: {node_id}")
1172
+ elif validation_feedback["incorrect_params"]:
1173
+ # 有提交了但值错误的参数,只对这些参数给出反馈
1174
+ incorrect_list = []
1175
+ for param_name in validation_feedback["incorrect_params"]:
1176
+ incorrect_list.append(f" - Parameter '{param_name}' is incorrect")
1177
+
1178
+ correct_info = ""
1179
+ if validation_feedback["correct_params"]:
1180
+ correct_info = f"\n✓ Correct parameters: {', '.join(validation_feedback['correct_params'])}"
1181
+
1182
+ response["parameter_feedback"] = {
1183
+ "status": "incorrect",
1184
+ "message": (
1185
+ f"⚠️ Some parameters are incorrect:\n" +
1186
+ "\n".join(incorrect_list) +
1187
+ correct_info +
1188
+ f"\n\nHint: This is a source node. You need to reason about the correct parameter values from the available parameters. Please try using different parameter values."
1189
+ ),
1190
+ "incorrect_params": validation_feedback["incorrect_params"],
1191
+ "correct_params": validation_feedback["correct_params"]
1192
+ }
1193
+ logger.info(f"✗ Source node parameters incorrect - node: {node_id}, incorrect: {validation_feedback['incorrect_params']}")
1194
+ # else: 部分提交且全部正确 → 不给任何 parameter_feedback,避免对未提交的参数发表意见
1195
+
1196
+ # 检查工具调用是否完全正确(输出与 golden outputs 匹配)
1197
+ # 用于给模型正向反馈,让它知道这个工具已经正确调用过,避免重复调用
1198
+ # 注意:只有当输出完全匹配时才标记为 correct,不会在错误时提供具体错误信息
1199
+ # if tool_node.golden_output_values and output_values:
1200
+ # is_correct = True
1201
+ # for port_name, expected_value in tool_node.golden_output_values.items():
1202
+ # actual_value = output_values.get(port_name)
1203
+ # if str(actual_value) != str(expected_value):
1204
+ # is_correct = False
1205
+ # break
1206
+
1207
+ # if is_correct:
1208
+ # response["tool_call_correct"] = True
1209
+ # logger.info(f"✓ Tool called with correct result - node: {node_id}")
1210
+
1211
+ # 只在有新内容掉落时才返回 newly_revealed
1212
+ if newly_revealed:
1213
+ response["newly_revealed"] = newly_revealed
1214
+
1215
+ # 添加 investigate 提示(对于有待触发 HIDDEN_ITEM 掉落的工具)
1216
+ if investigate_hints:
1217
+ response["investigate_hints"] = investigate_hints
1218
+
1219
+ # 3. 渐进式暴露机制 - 现在完全由 ITEM/HIDDEN_ITEM 边控制
1220
+ # 旧机制(基于 golden_input 检查)已被禁用
1221
+ # 新机制中,节点的可见性只由 ITEM/HIDDEN_ITEM 边触发决定
1222
+ # 上面的 ITEM/HIDDEN_ITEM 掉落逻辑已经处理了节点释放
1223
+ # progressive_revealed = _check_and_reveal_ready_nodes(scenario, output_values, tool_node.id)
1224
+ # if progressive_revealed:
1225
+ # # 合并到 newly_revealed 中
1226
+ # if newly_revealed:
1227
+ # newly_revealed.extend(progressive_revealed)
1228
+ # else:
1229
+ # newly_revealed = progressive_revealed
1230
+ # response["newly_revealed"] = newly_revealed
1231
+ # logger.info(f"Progressive reveal: {len(progressive_revealed)} nodes now ready")
1232
+
1233
+ # Check if this is the win node
1234
+ if node_id == scenario.win_node_id:
1235
+ # 验证输出值是否等于预期的胜利值
1236
+ # 从节点的 golden_output_values 中获取预期值(在 _initialize_node_values 时从 JSON 加载)
1237
+ expected_outputs = tool_node.golden_output_values
1238
+
1239
+ # 检查实际输出是否与预期输出匹配
1240
+ is_correct = False
1241
+ victory_string = None
1242
+ mismatch_info = []
1243
+
1244
+ if expected_outputs and output_values:
1245
+ # 检查每个预期输出端口的值是否匹配
1246
+ is_correct = True
1247
+ for port_name, expected_value in expected_outputs.items():
1248
+ actual_value = output_values.get(port_name)
1249
+ if actual_value != expected_value:
1250
+ is_correct = False
1251
+ mismatch_info.append(f"Port '{port_name}': expected '{expected_value}', actual '{actual_value}'")
1252
+ logger.warning(f"Win node output mismatch - port: {port_name}, expected: {expected_value}, actual: {actual_value}")
1253
+
1254
+ # 如果所有输出都匹配,使用第一个输出作为胜利字符串
1255
+ if is_correct and output_values:
1256
+ victory_string = list(output_values.values())[0]
1257
+ else:
1258
+ logger.warning(f"Win node called but missing output values - expected: {expected_outputs}, actual: {output_values}")
1259
+
1260
+ # 不再主动提示胜利字符串,让模型自己判断
1261
+ # 模型调用工具获得输出后,需要自己识别这是否是胜利字符串并提交
1262
+ if is_correct:
1263
+ logger.info(f"🎯 Win node called with correct output - case: {case_id}, node: {node_id}, victory: {victory_string}")
1264
+ else:
1265
+ logger.info(f"❌ Win node called with incorrect output - case: {case_id}, node: {node_id}")
1266
+
1267
+ return response
1268
+
1269
+ class UseItemRequest(BaseModel):
1270
+ node_id: str = Field(..., description="The ID of the Item node to use (must be Item type)")
1271
+ arguments: Dict[str, Any] = Field(default_factory=dict, description="Input arguments to provide to the item")
1272
+
1273
+ @app.post("/env/{case_id}/use_item")
1274
+ def use_item(case_id: str, req: UseItemRequest):
1275
+ """
1276
+ Use an Item node by providing input arguments.
1277
+
1278
+ This is specifically for Item nodes that require parameters to be "unlocked" or "activated",
1279
+ such as containers that need a password/fingerprint.
1280
+
1281
+ - Validates that the node is of type Item
1282
+ - Checks if provided arguments match the item's golden_input_values
1283
+ - If match: triggers ITEM-type edge drops and returns the item's content
1284
+ - If not match: returns error message
1285
+ """
1286
+ logger.info(f"Use item request - case_id: {case_id}, node_id: {req.node_id}, args: {req.arguments}")
1287
+ STATS["use_items"][case_id] += 1
1288
+
1289
+ if case_id not in SCENARIOS:
1290
+ logger.error(f"Case not found: {case_id}")
1291
+ raise HTTPException(status_code=404, detail="Case not found")
1292
+
1293
+ scenario = SCENARIOS[case_id]
1294
+ if req.node_id not in scenario.nodes:
1295
+ logger.error(f"Node not found: {req.node_id} in case {case_id}")
1296
+ raise HTTPException(status_code=404, detail="Node not found")
1297
+
1298
+ item_node = scenario.nodes[req.node_id]
1299
+
1300
+ if not item_node.is_revealed:
1301
+ logger.warning(f"Attempt to use hidden item: {req.node_id}")
1302
+ return {"ok": False, "error": "Item is not visible yet."}
1303
+
1304
+ if item_node.type != "Item":
1305
+ logger.warning(f"Attempt to use non-item node: {req.node_id} (type: {item_node.type})")
1306
+ return {"ok": False, "error": "Only Item nodes can be used with use_item. Tools should be called with tool_call."}
1307
+
1308
+ # 【新增】检查该 Item 是否已经被成功解锁
1309
+ # 如果已经被正确使用过,直接返回成功提示
1310
+ if item_node.if_success:
1311
+ logger.info(f"Item already unlocked, returning success message: {req.node_id}")
1312
+ return {
1313
+ "ok": True,
1314
+ "message": "This item has already been successfully unlocked by you."
1315
+ }
1316
+
1317
+ # 检查该 Item 是否真的需要通过 use_item 提供参数
1318
+ # 只有当 Item 有非 Item/Hidden_Item 类型的输入时,才应该使用 use_item
1319
+ raw_nodes_data = RAW_NODES_DATA.get(case_id, {})
1320
+ if req.node_id in raw_nodes_data:
1321
+ raw_node = raw_nodes_data[req.node_id]
1322
+ inputs_info = raw_node.get('inputs', [])
1323
+ non_hidden_inputs = [
1324
+ inp for inp in inputs_info
1325
+ if inp.get("type") not in ["Item", "Hidden_Item"]
1326
+ ]
1327
+
1328
+ if not non_hidden_inputs:
1329
+ # 该 Item 不需要参数,应该只使用 investigate
1330
+ logger.warning(f"Attempt to use_item on a node that doesn't require parameters: {req.node_id}")
1331
+ return {
1332
+ "ok": False,
1333
+ "error": "This item does not require parameters. Please use investigate to examine the item directly."
1334
+ }
1335
+
1336
+ # 验证输入参数是否与 golden_input_values 匹配
1337
+ inputs_match_golden = _check_inputs_match_golden(req.arguments, item_node.golden_input_values)
1338
+
1339
+ if not inputs_match_golden:
1340
+ logger.info(f"✗ Item inputs do NOT match golden - node: {req.node_id}")
1341
+ # 提供更详细的错误信息,帮助 Agent 理解问题
1342
+ # 只显示非 Item/Hidden_Item 类型的参数(Hidden_Item 由系统自动处理)
1343
+ expected_params = []
1344
+ if req.node_id in raw_nodes_data:
1345
+ raw_node = raw_nodes_data[req.node_id]
1346
+ inputs_info = raw_node.get('inputs', [])
1347
+ expected_params = [
1348
+ inp.get("name") for inp in inputs_info
1349
+ if inp.get("type") not in ["Item", "Hidden_Item"]
1350
+ ]
1351
+
1352
+ provided_params = list(req.arguments.keys()) if req.arguments else []
1353
+
1354
+ # 检查参数名是否匹配
1355
+ if set(expected_params) == set(provided_params):
1356
+ # 参数名正确但值不匹配 - 不泄漏正确的值
1357
+ error_msg = f"Parameter names are correct, but the parameter values are incorrect. Please try using different parameter values."
1358
+ else:
1359
+ error_msg = f"Parameter names do not match. Expected parameter names: {expected_params}, you provided: {provided_params}."
1360
+
1361
+ return {
1362
+ "ok": False,
1363
+ "error": error_msg
1364
+ }
1365
+
1366
+ logger.info(f"✓ Item inputs match golden - node: {req.node_id}, activating item")
1367
+
1368
+ # 标记该 Item 已被正确使用
1369
+ item_node.if_success = True
1370
+
1371
+ # 将 golden_output_values 追加到 actual_outputs_history
1372
+ if item_node.golden_output_values:
1373
+ item_node.actual_outputs_history.append(dict(item_node.golden_output_values))
1374
+
1375
+ # 触发 ITEM 类型边的掉落
1376
+ newly_revealed = []
1377
+ for edge in scenario.edges:
1378
+ if edge.source_id == item_node.id and edge.connection_type == InterfaceType.ITEM:
1379
+ target_node = scenario.nodes[edge.target_id]
1380
+
1381
+ if not target_node.is_revealed:
1382
+ target_node.is_revealed = True
1383
+ # 构建基本节点信息(不包含详细内容)
1384
+ node_info = {
1385
+ "id": target_node.id,
1386
+ "type": target_node.type,
1387
+ "can_investigate": True,
1388
+ "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content"
1389
+ }
1390
+ # 只在 name 非空时添加
1391
+ # if target_node.name:
1392
+ # node_info["name"] = target_node.name
1393
+ # 只在 description 非空时添加
1394
+ if target_node.description:
1395
+ node_info["description"] = target_node.description
1396
+
1397
+ newly_revealed.append(node_info)
1398
+ logger.info(f"ITEM drop triggered: {target_node.id} (from use_item on {req.node_id})")
1399
+
1400
+ # 检查是否为 Win Node
1401
+ win_node_id = scenario.win_node_id
1402
+ is_win_node = (req.node_id == win_node_id)
1403
+
1404
+ # 构建返回结果
1405
+ result = {
1406
+ "ok": True,
1407
+ "message": "Item used successfully.",
1408
+ "content": item_node.golden_output_values if item_node.golden_output_values else None
1409
+ }
1410
+
1411
+ # 获取 narrative(如果存在)
1412
+ raw_nodes_data = RAW_NODES_DATA.get(case_id, {})
1413
+ if req.node_id in raw_nodes_data:
1414
+ narrative = raw_nodes_data[req.node_id].get('narrative')
1415
+ if narrative:
1416
+ result['narrative'] = narrative
1417
+
1418
+ if newly_revealed:
1419
+ result["newly_revealed"] = newly_revealed
1420
+
1421
+ # 不再主动提示胜利字符串,让模型自己判断
1422
+ # 如果是 Win Node,只记录日志
1423
+ if is_win_node:
1424
+ logger.info(f"Win node (Item) unlocked via use_item - case: {case_id}, node: {req.node_id}")
1425
+
1426
+ return result
1427
+
1428
+
1429
+ class SubmitAnswerRequest(BaseModel):
1430
+ answer: str = Field(..., description="The victory string to submit")
1431
+
1432
+ @app.post("/env/{case_id}/submit_answer")
1433
+ def submit_answer(case_id: str, req: SubmitAnswerRequest):
1434
+ """
1435
+ 提交答案接口
1436
+ 被测模型在获得胜利字符串提示后,需要调用此接口提交答案
1437
+ """
1438
+ logger.info(f"Submit answer request - case_id: {case_id}, answer: {req.answer}")
1439
+
1440
+ if case_id not in SCENARIOS:
1441
+ logger.error(f"Case not found: {case_id}")
1442
+ raise HTTPException(status_code=404, detail="Case not found")
1443
+
1444
+ scenario = SCENARIOS[case_id]
1445
+
1446
+ # 获取 win_node 的 golden_output_values
1447
+ if not scenario.win_node_id:
1448
+ logger.error(f"No win node defined for case: {case_id}")
1449
+ return {
1450
+ "ok": False,
1451
+ "error": "This case has no victory node defined"
1452
+ }
1453
+
1454
+ win_node = scenario.nodes.get(scenario.win_node_id)
1455
+ if not win_node:
1456
+ logger.error(f"Win node not found: {scenario.win_node_id}")
1457
+ return {
1458
+ "ok": False,
1459
+ "error": "Victory node does not exist"
1460
+ }
1461
+
1462
+ # 获取正确的胜利字符串(取第一个 golden_output_value)
1463
+ if win_node.golden_output_values:
1464
+ correct_answer = list(win_node.golden_output_values.values())[0]
1465
+ else:
1466
+ logger.error(f"Win node has no golden_output_values: {scenario.win_node_id}")
1467
+ return {
1468
+ "ok": False,
1469
+ "error": "Victory node has no correct answer"
1470
+ }
1471
+
1472
+ # 验证提交的答案
1473
+ if req.answer == correct_answer:
1474
+ logger.info(f"🎉 CORRECT ANSWER SUBMITTED - case: {case_id}, answer: {req.answer}")
1475
+ return {
1476
+ "ok": True,
1477
+ "is_win": True,
1478
+ "victory_message": f"🎉 Congratulations on successfully escaping the room! Your answer is correct: {req.answer}"
1479
+ }
1480
+ else:
1481
+ logger.info(f"❌ INCORRECT ANSWER SUBMITTED - case: {case_id}, submitted: {req.answer}, correct: {correct_answer}")
1482
+ return {
1483
+ "ok": True,
1484
+ "is_win": False,
1485
+ "error": f"The submitted answer is incorrect. You submitted: {req.answer}"
1486
+ }
1487
+
1488
+ if __name__ == "__main__":
1489
+
1490
+ uvicorn.run(app, host="0.0.0.0", port=8000)
tasks/agentescape-10-skeleton-a4248b22/environment/puzzle/upstream/simulator.py ADDED
The diff for this file is too large to render. See raw diff
 
tasks/agentescape-10-skeleton-a4248b22/environment/puzzle/worker.Dockerfile ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f
2
+ RUN apt-get update && apt-get install -y --no-install-recommends libseccomp2 && rm -rf /var/lib/apt/lists/*
3
+ COPY requirements.txt /app/requirements.txt
4
+ RUN pip install --no-cache-dir -r /app/requirements.txt
5
+ WORKDIR /app
6
+ COPY worker.py child.py /app/
7
+ COPY upstream/simulator.py /app/simulator.py
8
+ CMD ["uvicorn", "worker:app", "--host", "0.0.0.0", "--port", "8001", "--workers", "1", "--no-access-log"]
tasks/agentescape-10-skeleton-a4248b22/environment/puzzle/worker.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stateless Python tool worker. Never receives a scenario or reference values."""
2
+
3
+ import json
4
+ import os
5
+ import signal
6
+ import subprocess
7
+ import sys
8
+ import tempfile
9
+ import threading
10
+
11
+ from fastapi import FastAPI
12
+ from pydantic import BaseModel, ConfigDict
13
+
14
+ app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
15
+ lock = threading.Lock()
16
+
17
+
18
+ class Execution(BaseModel):
19
+ model_config = ConfigDict(extra="forbid", strict=True)
20
+ code: str
21
+
22
+
23
+ @app.get("/health")
24
+ def health():
25
+ return {"ok": True}
26
+
27
+
28
+ @app.post("/execute")
29
+ def execute(request: Execution):
30
+ if len(request.code.encode()) > 65536:
31
+ return {"stdout": "Error: code exceeds 64 KiB limit"}
32
+ with lock, tempfile.TemporaryDirectory(prefix="escape-code-") as directory:
33
+ os.chown(directory, 65534, 65534)
34
+ with tempfile.TemporaryFile() as output:
35
+ process = subprocess.Popen(
36
+ [sys.executable, "-I", "/app/child.py"],
37
+ stdin=subprocess.PIPE,
38
+ stdout=output,
39
+ stderr=subprocess.DEVNULL,
40
+ cwd=directory,
41
+ user=65534,
42
+ group=65534,
43
+ extra_groups=[],
44
+ start_new_session=True,
45
+ env={"PATH": "/usr/local/bin:/usr/bin:/bin"},
46
+ )
47
+ try:
48
+ process.communicate(
49
+ json.dumps({"code": request.code}).encode(), timeout=5
50
+ )
51
+ except subprocess.TimeoutExpired:
52
+ os.killpg(process.pid, signal.SIGKILL)
53
+ process.wait()
54
+ return {"stdout": "Error: Python execution timed out"}
55
+ finally:
56
+ # Also remove children still in the process group after normal exit.
57
+ try:
58
+ os.killpg(process.pid, signal.SIGKILL)
59
+ except ProcessLookupError:
60
+ pass
61
+ output.seek(0)
62
+ value = output.read(65537)
63
+ if len(value) > 65536 or process.returncode != 0:
64
+ return {
65
+ "stdout": "Error: Python execution exceeded a resource limit or failed"
66
+ }
67
+ try:
68
+ result = json.loads(value)
69
+ if not isinstance(result.get("stdout"), str):
70
+ raise ValueError("Invalid worker response")
71
+ return result
72
+ except (ValueError, AttributeError):
73
+ return {"stdout": "Error: Python execution returned invalid output"}
tasks/agentescape-10-skeleton-a4248b22/instruction.md ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Escape the room
2
+
3
+ Discover the victory string and submit it with `escape submit-answer`.
4
+ Start with `escape observe`. This returns the room, available information, visible entities, and victory node ID.
5
+
6
+ Use these commands (JSON responses):
7
+
8
+ ```sh
9
+ escape investigate NODE_ID
10
+ escape tool-call NODE_ID --arguments-json '{"parameter": "value"}'
11
+ escape use-item NODE_ID --arguments-json '{"parameter": "value"}'
12
+ escape submit-answer 'exact victory string'
13
+ escape state
14
+ ```
15
+
16
+ Investigate tools to learn their interfaces and clues. Investigate items for their contents; items requiring parameters use `use-item`. Tool calls can reveal new entities. A hidden-item hint means investigate that tool again. Use node IDs and parameter names exactly as returned. Carry outputs into subsequent calls; do not guess intermediate values. The victory string can be code, a number encoded as text, or other arbitrary text.
17
+
18
+ Only successful answer submission completes the task. Wrong submissions allow another attempt. You have **500 puzzle actions**; invalid actions count. `observe` and `state` do not count. This action limit differs from the original evaluator's model-turn limit. Do not reset or replace the environment.
tasks/agentescape-10-skeleton-a4248b22/solution/oracle.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Reference solver: use trusted inputs, but obtain the answer through public actions."""
2
+
3
+ import json
4
+ import urllib.request
5
+ from pathlib import Path
6
+
7
+
8
+ def http_action(base_url, payload):
9
+ request = urllib.request.Request(
10
+ base_url + "/action",
11
+ data=json.dumps(payload).encode(),
12
+ headers={"Content-Type": "application/json"},
13
+ )
14
+ with urllib.request.urlopen(request, timeout=30) as response:
15
+ return json.load(response)
16
+
17
+
18
+ def solve(scenario, act, observe):
19
+ nodes = {node["id"]: node for node in scenario["nodes"]}
20
+ visible = {entity["id"] for entity in observe["available_entities"]}
21
+ solved = set()
22
+ seen_outputs = {}
23
+ action_count = 0
24
+
25
+ def call(payload):
26
+ nonlocal action_count
27
+ action_count += 1
28
+ response = act(payload)
29
+ visible.update(entity["id"] for entity in response.get("newly_revealed", []))
30
+ if (
31
+ response.get("episode", {}).get("termination_reason")
32
+ == "infrastructure_error"
33
+ ):
34
+ raise RuntimeError("Infrastructure failure")
35
+ return response
36
+
37
+ for _round in range(len(nodes) + 2):
38
+ progress = False
39
+ for node_id, node in nodes.items():
40
+ if node_id not in visible or node_id in solved:
41
+ continue
42
+ # Preserve graph order for data inputs; trigger/drop edges express visibility.
43
+ predecessors = [
44
+ edge["source_id"]
45
+ for edge in scenario["edges"]
46
+ if edge["target_id"] == node_id
47
+ and edge["connection_type"] not in ("Item", "Hidden_Item")
48
+ ]
49
+ if any(pred not in solved for pred in predecessors):
50
+ continue
51
+ info = call({"action": "investigate", "node_id": node_id})
52
+ if not info.get("ok"):
53
+ raise RuntimeError(f"Investigation failed: {node_id}: {info}")
54
+ inputs = {
55
+ port["name"]: port["value"]
56
+ for port in node.get("inputs", [])
57
+ if "value" in port
58
+ }
59
+ if node["type"] == "Tool":
60
+ result = call(
61
+ {"action": "tool_call", "node_id": node_id, "arguments": inputs}
62
+ )
63
+ if not result.get("ok") or result.get("output_values", {}).get("error"):
64
+ raise RuntimeError(f"Tool failed: {node_id}: {result}")
65
+ output = result.get("output_values", {})
66
+ if node.get("template_id") in ("terminal_1", "terminal_2"):
67
+ slots = {
68
+ port["name"]: inputs[port["name"]]
69
+ for port in node["inputs"]
70
+ if port["type"] not in ("Item", "Hidden_Item")
71
+ and port["name"] in inputs
72
+ }
73
+ triggers = {
74
+ key: value for key, value in inputs.items() if key not in slots
75
+ }
76
+ for key, value in slots.items():
77
+ partial = call(
78
+ {
79
+ "action": "tool_call",
80
+ "node_id": node_id,
81
+ "arguments": {**triggers, key: value},
82
+ }
83
+ )
84
+ if partial.get("ok"):
85
+ output.update(partial.get("output_values", {}))
86
+ # HIDDEN_ITEM tool drops only occur on subsequent investigation.
87
+ call({"action": "investigate", "node_id": node_id})
88
+ elif info.get("required_inputs"):
89
+ result = call(
90
+ {"action": "use_item", "node_id": node_id, "arguments": inputs}
91
+ )
92
+ if not result.get("ok"):
93
+ raise RuntimeError(f"Item failed: {node_id}: {result}")
94
+ output = result.get("content")
95
+ else:
96
+ output = info.get("content")
97
+ seen_outputs[node_id] = output
98
+ solved.add(node_id)
99
+ progress = True
100
+ win_id = scenario["metadata"]["win_node_id"]
101
+ if win_id in solved and (len(solved) == len(nodes) or not progress):
102
+ outputs = seen_outputs[win_id]
103
+ if not outputs:
104
+ raise RuntimeError(f"Victory node returned no output: {win_id}")
105
+ # Upstream grades its first stored output port, independent of response order.
106
+ victory_port = next(
107
+ port["name"] for port in nodes[win_id]["outputs"] if "value" in port
108
+ )
109
+ answer = outputs[victory_port] if isinstance(outputs, dict) else outputs
110
+ result = call({"action": "submit_answer", "answer": answer})
111
+ if not result.get("is_win"):
112
+ raise RuntimeError(f"Victory submission failed: {result}")
113
+ return {"won": True, "actions": action_count, "visited_nodes": len(solved)}
114
+ if not progress:
115
+ raise RuntimeError(f"No progress: visible={visible}, solved={solved}")
116
+ raise RuntimeError("Reference solver exceeded graph traversal limit")
117
+
118
+
119
+ if __name__ == "__main__":
120
+ import os
121
+
122
+ base = os.environ.get("ESCAPE_URL", "http://puzzle:8000")
123
+ with urllib.request.urlopen(base + "/observation", timeout=20) as response:
124
+ observation = json.load(response)
125
+ print(
126
+ json.dumps(
127
+ solve(
128
+ json.loads(Path("/solution/scenario.json").read_text()),
129
+ lambda payload: http_action(base, payload),
130
+ observation,
131
+ )
132
+ )
133
+ )
tasks/agentescape-10-skeleton-a4248b22/solution/scenario.json ADDED
@@ -0,0 +1,717 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_nodes": 10,
4
+ "total_edges": 11,
5
+ "win_node_id": "regex_search",
6
+ "win_condition": {
7
+ "type": "tool_output",
8
+ "node_id": "regex_search",
9
+ "output_port": "matches",
10
+ "output_type": "Text_Generic",
11
+ "description": "Execute Regex Search and get the output from port 'matches'"
12
+ },
13
+ "source_init": {
14
+ "source_nodes": [
15
+ "regex_search",
16
+ "terminal_1",
17
+ "zip_unzip_file",
18
+ "json_get",
19
+ "calc_bigmul",
20
+ "terminal_1_ad07",
21
+ "graph_shortest_path"
22
+ ],
23
+ "by_node": {
24
+ "regex_search": {
25
+ "node_name": "Regex Search",
26
+ "node_type": "Tool",
27
+ "template_id": "regex_search",
28
+ "init_inputs": {},
29
+ "init_outputs": {
30
+ "matches": {
31
+ "type": "Text_Generic",
32
+ "description": "Found matches (List)"
33
+ }
34
+ }
35
+ },
36
+ "terminal_1": {
37
+ "node_name": "",
38
+ "node_type": "Tool",
39
+ "template_id": "terminal_1",
40
+ "init_inputs": {},
41
+ "init_outputs": {
42
+ "text_output": {
43
+ "type": "Text_Generic",
44
+ "description": "Text output when only slot_a is provided"
45
+ },
46
+ "hex_output": {
47
+ "type": "Hex_String",
48
+ "description": "Hex output when only slot_b is provided"
49
+ },
50
+ "item_dispenser": {
51
+ "type": "Item",
52
+ "description": "Item output when both slots are provided"
53
+ }
54
+ }
55
+ },
56
+ "zip_unzip_file": {
57
+ "node_name": "Zip Unzipper",
58
+ "node_type": "Tool",
59
+ "template_id": "zip_unzip_file",
60
+ "init_inputs": {
61
+ "zip_id": {
62
+ "type": "File_Id",
63
+ "description": "Zip file ID"
64
+ }
65
+ },
66
+ "init_outputs": {
67
+ "files": {
68
+ "type": "File_Id",
69
+ "description": "Extracted file ID"
70
+ }
71
+ }
72
+ },
73
+ "json_get": {
74
+ "node_name": "JSON Getter",
75
+ "node_type": "Tool",
76
+ "template_id": "json_get",
77
+ "init_inputs": {
78
+ "file_id": {
79
+ "type": "File_Id",
80
+ "description": "JSON file ID"
81
+ },
82
+ "jsonpath": {
83
+ "type": "Text_Generic",
84
+ "description": "JSONPath expression"
85
+ }
86
+ },
87
+ "init_outputs": {
88
+ "values": {
89
+ "type": "Text_Generic",
90
+ "description": "Extracted values"
91
+ }
92
+ }
93
+ },
94
+ "calc_bigmul": {
95
+ "node_name": "Big Number Multiplier",
96
+ "node_type": "Tool",
97
+ "template_id": "calc_bigmul",
98
+ "init_inputs": {
99
+ "b": {
100
+ "type": "Big_Int",
101
+ "description": "Second large integer"
102
+ }
103
+ },
104
+ "init_outputs": {}
105
+ },
106
+ "terminal_1_ad07": {
107
+ "node_name": "",
108
+ "node_type": "Tool",
109
+ "template_id": "terminal_1",
110
+ "init_inputs": {
111
+ "slot_a": {
112
+ "type": "Text_Generic",
113
+ "description": "Input Slot A"
114
+ },
115
+ "slot_b": {
116
+ "type": "Big_Int",
117
+ "description": "Input Slot B"
118
+ }
119
+ },
120
+ "init_outputs": {
121
+ "text_output": {
122
+ "type": "Text_Generic",
123
+ "description": "Text output when only slot_a is provided"
124
+ },
125
+ "hex_output": {
126
+ "type": "Hex_String",
127
+ "description": "Hex output when only slot_b is provided"
128
+ },
129
+ "item_dispenser": {
130
+ "type": "Item",
131
+ "description": "Item output when both slots are provided"
132
+ }
133
+ }
134
+ },
135
+ "graph_shortest_path": {
136
+ "node_name": "Shortest Path Finder",
137
+ "node_type": "Tool",
138
+ "template_id": "graph_shortest_path",
139
+ "init_inputs": {
140
+ "file_id": {
141
+ "type": "File_Id",
142
+ "description": "Graph JSON file ID"
143
+ },
144
+ "dst": {
145
+ "type": "Text_Generic",
146
+ "description": "Destination node"
147
+ }
148
+ },
149
+ "init_outputs": {
150
+ "path": {
151
+ "type": "Text_Generic",
152
+ "description": "Path list"
153
+ },
154
+ "cost": {
155
+ "type": "Big_Int",
156
+ "description": "Path cost"
157
+ }
158
+ }
159
+ }
160
+ }
161
+ },
162
+ "initial_values": {
163
+ "regex_search": {
164
+ "init_inputs": {},
165
+ "init_outputs": {
166
+ "matches": "[\"found_pattern_001\", \"found_pattern_002\", \"found_pattern_003\", \"found_pattern_004\", \"found_pattern_005\"]"
167
+ }
168
+ },
169
+ "terminal_1": {
170
+ "init_inputs": {},
171
+ "init_outputs": {
172
+ "text_output": "System initialization sequence complete. Ready for input.",
173
+ "hex_output": "a1b2c3d4e5f60718293a4b5c6d7e8f90",
174
+ "item_dispenser": "Standard Item Dispenser Unit Alpha"
175
+ }
176
+ },
177
+ "zip_unzip_file": {
178
+ "init_inputs": {
179
+ "zip_id": "secure_archive_data_2024.zip"
180
+ },
181
+ "init_outputs": {
182
+ "files": "extracted_payload_config.json"
183
+ }
184
+ },
185
+ "json_get": {
186
+ "init_inputs": {
187
+ "file_id": "user_records_database_v9.json",
188
+ "jsonpath": "$.store.book[*].author"
189
+ },
190
+ "init_outputs": {
191
+ "values": "[\"Nigel Rees\", \"Evelyn Waugh\", \"Herman Melville\", \"J. R. R. Tolkien\"]"
192
+ }
193
+ },
194
+ "calc_bigmul": {
195
+ "init_inputs": {
196
+ "b": "847362519405837261509483726150"
197
+ },
198
+ "init_outputs": {}
199
+ },
200
+ "terminal_1_ad07": {
201
+ "init_inputs": {
202
+ "slot_a": "Manual_Override_Sequence_Initiated",
203
+ "slot_b": "594837261502938475610293847561"
204
+ },
205
+ "init_outputs": {
206
+ "text_output": "SuperSecretPassword123!",
207
+ "hex_output": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d",
208
+ "item_dispenser": "Advanced Item Dispenser Unit Beta"
209
+ }
210
+ },
211
+ "graph_shortest_path": {
212
+ "init_inputs": {
213
+ "file_id": "city_traffic_network_graph.json",
214
+ "dst": "Sector_7_Terminal"
215
+ },
216
+ "init_outputs": {
217
+ "path": "[\"Central_Hub\", \"Gateway_North\", \"Route_66\", \"Check_Point_Alpha\", \"Sector_7_Terminal\"]",
218
+ "cost": "12548"
219
+ }
220
+ }
221
+ },
222
+ "intro_narrative": "You wake up in the dimly lit office of a renowned but missing private investigator. Dust motes dance in the pale light filtering through the blinds. The detective was close to solving a massive conspiracy, and the agency believes he left his final findings hidden within this very room. Time is running out before the perpetrators realize you are here. Your objective is to piece together his scattered tools, uncover the hidden evidence, and expose the truth before the shadowy syndicate returns to silence you for good.",
223
+ "narrative_style": "mystery"
224
+ },
225
+ "nodes": [
226
+ {
227
+ "id": "regex_search",
228
+ "name": "Regex Search",
229
+ "description": "Search regex in either raw text or a file.",
230
+ "type": "Tool",
231
+ "template_id": "regex_search",
232
+ "initial_visible": true,
233
+ "is_revealed": true,
234
+ "inputs": [
235
+ {
236
+ "name": "pattern",
237
+ "type": "Text_Generic",
238
+ "description": "Regex pattern",
239
+ "value": "System initialization sequence complete. Ready for input."
240
+ },
241
+ {
242
+ "name": "file_id",
243
+ "type": "File_Id",
244
+ "description": "File ID (optional)",
245
+ "value": "extracted_payload_config.json"
246
+ },
247
+ {
248
+ "name": "text",
249
+ "type": "Text_Generic",
250
+ "description": "Text (optional)",
251
+ "value": "[\"Nigel Rees\", \"Evelyn Waugh\", \"Herman Melville\", \"J. R. R. Tolkien\"]"
252
+ }
253
+ ],
254
+ "outputs": [
255
+ {
256
+ "name": "matches",
257
+ "type": "Text_Generic",
258
+ "description": "Found matches (List)",
259
+ "value": "[\"found_pattern_001\", \"found_pattern_002\", \"found_pattern_003\", \"found_pattern_004\", \"found_pattern_005\"]"
260
+ }
261
+ ],
262
+ "init": {
263
+ "inputs": {},
264
+ "outputs": {
265
+ "matches": "[\"found_pattern_001\", \"found_pattern_002\", \"found_pattern_003\", \"found_pattern_004\", \"found_pattern_005\"]"
266
+ }
267
+ },
268
+ "narrative": "A high-tech Evidence Scanner designed to find hidden anomalies. It requires inputs from the Mainframe Terminal, the Locked Briefcase, and the Archives Computer to function."
269
+ },
270
+ {
271
+ "id": "terminal_1",
272
+ "name": "",
273
+ "description": "",
274
+ "type": "Tool",
275
+ "template_id": "terminal_1",
276
+ "initial_visible": true,
277
+ "is_revealed": true,
278
+ "inputs": [
279
+ {
280
+ "name": "slot_a",
281
+ "type": "Text_Generic",
282
+ "description": "Input Slot A",
283
+ "value": "[\"Nigel Rees\", \"Evelyn Waugh\", \"Herman Melville\", \"J. R. R. Tolkien\"]"
284
+ },
285
+ {
286
+ "name": "slot_b",
287
+ "type": "Big_Int",
288
+ "description": "Input Slot B",
289
+ "value": "10632704893504445957421001795730200"
290
+ }
291
+ ],
292
+ "outputs": [
293
+ {
294
+ "name": "text_output",
295
+ "type": "Text_Generic",
296
+ "description": "Text output when only slot_a is provided",
297
+ "value": "System initialization sequence complete. Ready for input."
298
+ },
299
+ {
300
+ "name": "hex_output",
301
+ "type": "Hex_String",
302
+ "description": "Hex output when only slot_b is provided",
303
+ "value": "a1b2c3d4e5f60718293a4b5c6d7e8f90"
304
+ },
305
+ {
306
+ "name": "item_dispenser",
307
+ "type": "Item",
308
+ "description": "Item output when both slots are provided",
309
+ "value": "Standard Item Dispenser Unit Alpha"
310
+ }
311
+ ],
312
+ "init": {
313
+ "inputs": {},
314
+ "outputs": {
315
+ "text_output": "System initialization sequence complete. Ready for input.",
316
+ "hex_output": "a1b2c3d4e5f60718293a4b5c6d7e8f90",
317
+ "item_dispenser": "Standard Item Dispenser Unit Alpha"
318
+ }
319
+ },
320
+ "narrative": "The central Mainframe Terminal sits on a dusty desk. It requires inputs from both the Archives Computer and the Mechanical Calculator to process the data."
321
+ },
322
+ {
323
+ "id": "zip_unzip_file",
324
+ "name": "Zip Unzipper",
325
+ "description": "Unzip a password-protected zip file by id.",
326
+ "type": "Tool",
327
+ "template_id": "zip_unzip_file",
328
+ "initial_visible": true,
329
+ "is_revealed": true,
330
+ "inputs": [
331
+ {
332
+ "name": "zip_id",
333
+ "type": "File_Id",
334
+ "description": "Zip file ID",
335
+ "value": "secure_archive_data_2024.zip"
336
+ },
337
+ {
338
+ "name": "password",
339
+ "type": "Text_Generic",
340
+ "description": "Password",
341
+ "value": "SuperSecretPassword123!"
342
+ }
343
+ ],
344
+ "outputs": [
345
+ {
346
+ "name": "files",
347
+ "type": "File_Id",
348
+ "description": "Extracted file ID",
349
+ "value": "extracted_payload_config.json"
350
+ }
351
+ ],
352
+ "init": {
353
+ "inputs": {
354
+ "zip_id": "secure_archive_data_2024.zip"
355
+ },
356
+ "outputs": {
357
+ "files": "extracted_payload_config.json"
358
+ }
359
+ },
360
+ "narrative": "A Locked Briefcase holding classified documents. It requires input from the Security Keypad to unlock."
361
+ },
362
+ {
363
+ "id": "json_get",
364
+ "name": "JSON Getter",
365
+ "description": "Extract values by simple JSONPath.",
366
+ "type": "Tool",
367
+ "template_id": "json_get",
368
+ "initial_visible": false,
369
+ "is_revealed": false,
370
+ "inputs": [
371
+ {
372
+ "name": "trigger_hidden",
373
+ "type": "Hidden_Item",
374
+ "description": "Hidden item required to unlock this tool"
375
+ },
376
+ {
377
+ "name": "file_id",
378
+ "type": "File_Id",
379
+ "description": "JSON file ID",
380
+ "value": "user_records_database_v9.json"
381
+ },
382
+ {
383
+ "name": "jsonpath",
384
+ "type": "Text_Generic",
385
+ "description": "JSONPath expression",
386
+ "value": "$.store.book[*].author"
387
+ }
388
+ ],
389
+ "outputs": [
390
+ {
391
+ "name": "values",
392
+ "type": "Text_Generic",
393
+ "description": "Extracted values",
394
+ "value": "[\"Nigel Rees\", \"Evelyn Waugh\", \"Herman Melville\", \"J. R. R. Tolkien\"]"
395
+ }
396
+ ],
397
+ "init": {
398
+ "inputs": {
399
+ "file_id": "user_records_database_v9.json",
400
+ "jsonpath": "$.store.book[*].author"
401
+ },
402
+ "outputs": {
403
+ "values": "[\"Nigel Rees\", \"Evelyn Waugh\", \"Herman Melville\", \"J. R. R. Tolkien\"]"
404
+ }
405
+ },
406
+ "narrative": "An old Archives Computer containing digitized records from decades ago."
407
+ },
408
+ {
409
+ "id": "item_8",
410
+ "name": "",
411
+ "description": "",
412
+ "type": "Item",
413
+ "template_id": "item_8",
414
+ "initial_visible": false,
415
+ "is_revealed": false,
416
+ "inputs": [
417
+ {
418
+ "name": "source_tool",
419
+ "type": "Hidden_Item",
420
+ "description": "Produced by"
421
+ }
422
+ ],
423
+ "outputs": [
424
+ {
425
+ "name": "content",
426
+ "type": "Hidden_Item",
427
+ "description": "The integer"
428
+ }
429
+ ],
430
+ "narrative": "A Strange Lens that seems capable of revealing hidden ink or invisible markings."
431
+ },
432
+ {
433
+ "id": "item_16",
434
+ "name": "",
435
+ "description": "",
436
+ "type": "Item",
437
+ "template_id": "item_16",
438
+ "initial_visible": true,
439
+ "is_revealed": true,
440
+ "inputs": [
441
+ {
442
+ "name": "source_tool",
443
+ "type": "Item",
444
+ "description": "Produced by"
445
+ }
446
+ ],
447
+ "outputs": [
448
+ {
449
+ "name": "content",
450
+ "type": "Hidden_Item",
451
+ "description": "Timezone text"
452
+ }
453
+ ],
454
+ "narrative": "An Antique Compass with strange engravings on the back."
455
+ },
456
+ {
457
+ "id": "calc_bigmul",
458
+ "name": "Big Number Multiplier",
459
+ "description": "Multiply two (very large) decimal integers represented as strings.",
460
+ "type": "Tool",
461
+ "template_id": "calc_bigmul",
462
+ "initial_visible": true,
463
+ "is_revealed": true,
464
+ "inputs": [
465
+ {
466
+ "name": "trigger_hidden",
467
+ "type": "Hidden_Item",
468
+ "description": "Hidden item required to unlock this tool"
469
+ },
470
+ {
471
+ "name": "a",
472
+ "type": "Big_Int",
473
+ "description": "First large integer",
474
+ "value": "12548"
475
+ },
476
+ {
477
+ "name": "b",
478
+ "type": "Big_Int",
479
+ "description": "Second large integer",
480
+ "value": "847362519405837261509483726150"
481
+ }
482
+ ],
483
+ "outputs": [
484
+ {
485
+ "name": "product",
486
+ "type": "Big_Int",
487
+ "description": "Product result",
488
+ "value": "10632704893504445957421001795730200"
489
+ }
490
+ ],
491
+ "init": {
492
+ "inputs": {
493
+ "b": "847362519405837261509483726150"
494
+ },
495
+ "outputs": {}
496
+ },
497
+ "narrative": "A heavy Mechanical Calculator with intricate brass gears. It requires input from the City Map Board to compute the final coordinates."
498
+ },
499
+ {
500
+ "id": "terminal_1_ad07",
501
+ "name": "",
502
+ "description": "",
503
+ "type": "Tool",
504
+ "template_id": "terminal_1",
505
+ "initial_visible": true,
506
+ "is_revealed": true,
507
+ "inputs": [
508
+ {
509
+ "name": "slot_a",
510
+ "type": "Text_Generic",
511
+ "description": "Input Slot A",
512
+ "value": "Manual_Override_Sequence_Initiated"
513
+ },
514
+ {
515
+ "name": "slot_b",
516
+ "type": "Big_Int",
517
+ "description": "Input Slot B",
518
+ "value": "594837261502938475610293847561"
519
+ }
520
+ ],
521
+ "outputs": [
522
+ {
523
+ "name": "text_output",
524
+ "type": "Text_Generic",
525
+ "description": "Text output when only slot_a is provided",
526
+ "value": "SuperSecretPassword123!"
527
+ },
528
+ {
529
+ "name": "hex_output",
530
+ "type": "Hex_String",
531
+ "description": "Hex output when only slot_b is provided",
532
+ "value": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d"
533
+ },
534
+ {
535
+ "name": "item_dispenser",
536
+ "type": "Item",
537
+ "description": "Item output when both slots are provided",
538
+ "value": "Advanced Item Dispenser Unit Beta"
539
+ }
540
+ ],
541
+ "init": {
542
+ "inputs": {
543
+ "slot_a": "Manual_Override_Sequence_Initiated",
544
+ "slot_b": "594837261502938475610293847561"
545
+ },
546
+ "outputs": {
547
+ "text_output": "SuperSecretPassword123!",
548
+ "hex_output": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d",
549
+ "item_dispenser": "Advanced Item Dispenser Unit Beta"
550
+ }
551
+ },
552
+ "narrative": "A standard Security Keypad securely attached to the wall next to a reinforced door."
553
+ },
554
+ {
555
+ "id": "graph_shortest_path",
556
+ "name": "Shortest Path Finder",
557
+ "description": "Shortest path on graph json file with edges list.",
558
+ "type": "Tool",
559
+ "template_id": "graph_shortest_path",
560
+ "initial_visible": false,
561
+ "is_revealed": false,
562
+ "inputs": [
563
+ {
564
+ "name": "trigger_hidden",
565
+ "type": "Hidden_Item",
566
+ "description": "Hidden item required to unlock this tool"
567
+ },
568
+ {
569
+ "name": "file_id",
570
+ "type": "File_Id",
571
+ "description": "Graph JSON file ID",
572
+ "value": "city_traffic_network_graph.json"
573
+ },
574
+ {
575
+ "name": "src",
576
+ "type": "Text_Generic",
577
+ "description": "Source node",
578
+ "value": "[\"Nigel Rees\", \"Evelyn Waugh\", \"Herman Melville\", \"J. R. R. Tolkien\"]"
579
+ },
580
+ {
581
+ "name": "dst",
582
+ "type": "Text_Generic",
583
+ "description": "Destination node",
584
+ "value": "Sector_7_Terminal"
585
+ }
586
+ ],
587
+ "outputs": [
588
+ {
589
+ "name": "path",
590
+ "type": "Text_Generic",
591
+ "description": "Path list",
592
+ "value": "[\"Central_Hub\", \"Gateway_North\", \"Route_66\", \"Check_Point_Alpha\", \"Sector_7_Terminal\"]"
593
+ },
594
+ {
595
+ "name": "cost",
596
+ "type": "Big_Int",
597
+ "description": "Path cost",
598
+ "value": "12548"
599
+ }
600
+ ],
601
+ "init": {
602
+ "inputs": {
603
+ "file_id": "city_traffic_network_graph.json",
604
+ "dst": "Sector_7_Terminal"
605
+ },
606
+ "outputs": {
607
+ "path": "[\"Central_Hub\", \"Gateway_North\", \"Route_66\", \"Check_Point_Alpha\", \"Sector_7_Terminal\"]",
608
+ "cost": "12548"
609
+ }
610
+ },
611
+ "narrative": "A City Map Board covered in red strings and thumbtacks. It requires input from the Archives Computer to determine the correct route."
612
+ },
613
+ {
614
+ "id": "item_16_54c0",
615
+ "name": "",
616
+ "description": "",
617
+ "type": "Item",
618
+ "template_id": "item_16",
619
+ "initial_visible": true,
620
+ "is_revealed": true,
621
+ "inputs": [
622
+ {
623
+ "name": "source_tool",
624
+ "type": "Item",
625
+ "description": "Produced by"
626
+ }
627
+ ],
628
+ "outputs": [
629
+ {
630
+ "name": "content",
631
+ "type": "Hidden_Item",
632
+ "description": "Timezone text"
633
+ }
634
+ ],
635
+ "narrative": "A Dusty Pocket Watch showing multiple different timezones."
636
+ }
637
+ ],
638
+ "edges": [
639
+ {
640
+ "source_id": "terminal_1",
641
+ "target_id": "regex_search",
642
+ "connection_type": "Text_Generic",
643
+ "source_port": "text_output",
644
+ "target_port": "pattern"
645
+ },
646
+ {
647
+ "source_id": "zip_unzip_file",
648
+ "target_id": "regex_search",
649
+ "connection_type": "File_Id",
650
+ "source_port": "files",
651
+ "target_port": "file_id"
652
+ },
653
+ {
654
+ "source_id": "json_get",
655
+ "target_id": "regex_search",
656
+ "connection_type": "Text_Generic",
657
+ "source_port": "values",
658
+ "target_port": "text"
659
+ },
660
+ {
661
+ "source_id": "item_8",
662
+ "target_id": "json_get",
663
+ "connection_type": "Hidden_Item",
664
+ "source_port": "content",
665
+ "target_port": "trigger_hidden"
666
+ },
667
+ {
668
+ "source_id": "item_16",
669
+ "target_id": "item_8",
670
+ "connection_type": "Hidden_Item",
671
+ "source_port": "content",
672
+ "target_port": "source_tool"
673
+ },
674
+ {
675
+ "source_id": "json_get",
676
+ "target_id": "terminal_1",
677
+ "connection_type": "Text_Generic",
678
+ "source_port": "values",
679
+ "target_port": "slot_a"
680
+ },
681
+ {
682
+ "source_id": "calc_bigmul",
683
+ "target_id": "terminal_1",
684
+ "connection_type": "Big_Int",
685
+ "source_port": "product",
686
+ "target_port": "slot_b"
687
+ },
688
+ {
689
+ "source_id": "terminal_1_ad07",
690
+ "target_id": "zip_unzip_file",
691
+ "connection_type": "Text_Generic",
692
+ "source_port": "text_output",
693
+ "target_port": "password"
694
+ },
695
+ {
696
+ "source_id": "graph_shortest_path",
697
+ "target_id": "calc_bigmul",
698
+ "connection_type": "Big_Int",
699
+ "source_port": "cost",
700
+ "target_port": "a"
701
+ },
702
+ {
703
+ "source_id": "json_get",
704
+ "target_id": "graph_shortest_path",
705
+ "connection_type": "Text_Generic",
706
+ "source_port": "values",
707
+ "target_port": "src"
708
+ },
709
+ {
710
+ "source_id": "item_16_54c0",
711
+ "target_id": "graph_shortest_path",
712
+ "connection_type": "Hidden_Item",
713
+ "source_port": "content",
714
+ "target_port": "trigger_hidden"
715
+ }
716
+ ]
717
+ }
tasks/agentescape-10-skeleton-a4248b22/solution/solve.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/bin/sh
2
+ set -eu
3
+ python -I /solution/oracle.py
tasks/agentescape-10-skeleton-a4248b22/task.toml ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ schema_version = "1.4"
2
+ source = "https://github.com/AGI-Eval-Official/Repo-of-AgentEscapeBench"
3
+
4
+ [[artifacts]]
5
+ source = "/evidence/final.json"
6
+ service = "puzzle"
7
+
8
+ [[artifacts]]
9
+ source = "/evidence/trace.jsonl"
10
+ service = "puzzle"
11
+
12
+ [task]
13
+ name = "edbeeching/agentescape-10-skeleton-a4248b22"
14
+ version = "0.1.0"
15
+
16
+ [metadata]
17
+ difficulty = 10
18
+ source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7"
19
+ scenario_sha256 = "086b33a73d0ce6233d137c8eafe6fb7c351b88583ee2aab213b17a370a11067e"
20
+ protocol = "harbor-cli-action-budget-v1"
21
+ max_actions = 500
22
+
23
+ [agent]
24
+ timeout_sec = 1200
25
+
26
+ [environment]
27
+ build_timeout_sec = 900
28
+ cpus = 1
29
+ memory_mb = 1024
30
+
31
+ [verifier]
32
+ environment_mode = "separate"
33
+ timeout_sec = 60
34
+
35
+ [[verifier.collect]]
36
+ service = "puzzle"
37
+ command = "python -I /app/export.py"
38
+ timeout_sec = 15
tasks/agentescape-10-skeleton-a4248b22/tests/Dockerfile ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f
2
+ COPY . /tests/
tasks/agentescape-10-skeleton-a4248b22/tests/expected.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"scenario_sha256": "086b33a73d0ce6233d137c8eafe6fb7c351b88583ee2aab213b17a370a11067e", "max_actions": 500}
tasks/agentescape-10-skeleton-a4248b22/tests/grade.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Grade only Harbor-collected sidecar evidence in a fresh verifier container."""
2
+
3
+ import json
4
+ from pathlib import Path
5
+
6
+ expected = json.loads(Path("/tests/expected.json").read_text())
7
+ state = json.loads(Path("/evidence/final.json").read_text())
8
+ assert state["collected_from_live_service"] is True, "Missing trusted service export"
9
+ assert state["scenario_sha256"] == expected["scenario_sha256"], (
10
+ "Wrong scenario evidence"
11
+ )
12
+ assert state["max_actions"] == expected["max_actions"], "Wrong budget"
13
+ assert type(state["won"]) is bool
14
+ assert 0 <= state["action_count"] <= state["max_actions"]
15
+ assert state["termination_reason"] != "infrastructure_error", (
16
+ "Infrastructure failure is not a puzzle failure"
17
+ )
18
+ assert not state["won"] or state["termination_reason"] == "success"
19
+ Path("/logs/verifier").mkdir(parents=True, exist_ok=True)
20
+ Path("/logs/verifier/state.json").write_text(json.dumps(state, indent=2))
21
+ Path("/logs/verifier/reward.txt").write_text("1.0\n" if state["won"] else "0.0\n")
tasks/agentescape-10-skeleton-a4248b22/tests/test.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/bin/sh
2
+ set -eu
3
+ python -I /tests/grade.py
tasks/agentescape-10-skeleton-ac5cd29c/environment/Dockerfile ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f
2
+ RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/*
3
+ COPY cli.py /usr/local/bin/escape
4
+ RUN chmod 755 /usr/local/bin/escape
5
+ WORKDIR /workspace
tasks/agentescape-10-skeleton-ac5cd29c/environment/agent/Dockerfile ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f
2
+ RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/*
3
+ COPY cli.py /usr/local/bin/escape
4
+ RUN chmod 755 /usr/local/bin/escape
5
+ WORKDIR /workspace
tasks/agentescape-10-skeleton-ac5cd29c/environment/agent/cli.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Public agent client; depends only on the Python standard library."""
3
+
4
+ import argparse
5
+ import json
6
+ import os
7
+ import sys
8
+ import urllib.error
9
+ import urllib.request
10
+
11
+
12
+ def main():
13
+ parser = argparse.ArgumentParser(description="Interact with the escape room")
14
+ parser.add_argument(
15
+ "action",
16
+ choices=[
17
+ "observe",
18
+ "state",
19
+ "investigate",
20
+ "tool-call",
21
+ "use-item",
22
+ "submit-answer",
23
+ ],
24
+ )
25
+ parser.add_argument("value", nargs="?")
26
+ parser.add_argument("--arguments-json", default="{}")
27
+ args = parser.parse_args()
28
+ base = os.environ.get("ESCAPE_URL", "http://puzzle:8000").rstrip("/")
29
+ if args.action in ("observe", "state"):
30
+ request = urllib.request.Request(
31
+ base + ("/observation" if args.action == "observe" else "/state")
32
+ )
33
+ else:
34
+ if args.value is None:
35
+ parser.error("node ID or answer is required")
36
+ payload = {"action": args.action.replace("-", "_")}
37
+ if args.action == "submit-answer":
38
+ payload["answer"] = args.value
39
+ else:
40
+ payload["node_id"] = args.value
41
+ if args.action in ("tool-call", "use-item"):
42
+ payload["arguments"] = json.loads(args.arguments_json)
43
+ request = urllib.request.Request(
44
+ base + "/action",
45
+ data=json.dumps(payload).encode(),
46
+ headers={"Content-Type": "application/json"},
47
+ )
48
+ try:
49
+ with urllib.request.urlopen(request, timeout=30) as response:
50
+ print(json.dumps(json.load(response), ensure_ascii=False))
51
+ except (urllib.error.URLError, ValueError) as exc:
52
+ print(json.dumps({"ok": False, "error": str(exc)}))
53
+ sys.exit(2)
54
+
55
+
56
+ if __name__ == "__main__":
57
+ main()
tasks/agentescape-10-skeleton-ac5cd29c/environment/docker-compose.yaml ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ services:
2
+ main:
3
+ image: agentescapebench-agent:aab05a0a9ddb
4
+ build:
5
+ context: ./agent
6
+ networks: [default, puzzle]
7
+ security_opt: [no-new-privileges:true]
8
+ depends_on:
9
+ puzzle:
10
+ condition: service_healthy
11
+ puzzle:
12
+ image: agentescapebench-puzzle:agentescape-10-skeleton-ac5cd29c-aab05a0a9ddb
13
+ build:
14
+ context: ./puzzle
15
+ networks: [puzzle, execution]
16
+ cap_drop: [ALL]
17
+ security_opt: [no-new-privileges:true]
18
+ pids_limit: 64
19
+ mem_limit: 512m
20
+ healthcheck:
21
+ test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"]
22
+ interval: 1s
23
+ timeout: 3s
24
+ retries: 30
25
+ depends_on:
26
+ worker:
27
+ condition: service_healthy
28
+ worker:
29
+ image: agentescapebench-worker:aab05a0a9ddb
30
+ build:
31
+ context: ./puzzle
32
+ dockerfile: worker.Dockerfile
33
+ networks: [execution]
34
+ read_only: true
35
+ tmpfs: ["/tmp:size=64m,mode=1777"]
36
+ cap_drop: [ALL]
37
+ cap_add: [SETUID, SETGID, KILL, CHOWN, DAC_OVERRIDE]
38
+ security_opt: [no-new-privileges:true]
39
+ pids_limit: 64
40
+ mem_limit: 384m
41
+ healthcheck:
42
+ test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8001/health')"]
43
+ interval: 1s
44
+ timeout: 3s
45
+ retries: 30
46
+ networks:
47
+ puzzle:
48
+ internal: true
49
+ execution:
50
+ internal: true
tasks/agentescape-10-skeleton-ac5cd29c/environment/puzzle/Dockerfile ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f
2
+ COPY requirements.txt /app/requirements.txt
3
+ RUN pip install --no-cache-dir -r /app/requirements.txt
4
+ WORKDIR /app
5
+ COPY upstream /app/upstream
6
+ COPY service.py export.py /app/
7
+ COPY scenario.json /private/scenario.json
8
+ ENV SCENARIO_PATH=/private/scenario.json EVIDENCE_DIR=/evidence WORKER_URL=http://worker:8001 MAX_ACTIONS=500
9
+ CMD ["uvicorn", "service:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000", "--workers", "1", "--no-access-log"]
tasks/agentescape-10-skeleton-ac5cd29c/environment/puzzle/child.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run the original Python tool after reducing privileges and blocking networking."""
2
+
3
+ import ctypes
4
+ import errno
5
+ import json
6
+ import resource
7
+ import sys
8
+
9
+ resource.setrlimit(resource.RLIMIT_CPU, (3, 3))
10
+ resource.setrlimit(resource.RLIMIT_AS, (256 * 1024 * 1024, 256 * 1024 * 1024))
11
+ resource.setrlimit(resource.RLIMIT_FSIZE, (65536, 65536))
12
+ resource.setrlimit(resource.RLIMIT_NOFILE, (32, 32))
13
+ resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
14
+
15
+ # Filters survive fork/exec. Fail closed if seccomp cannot be loaded.
16
+ lib = ctypes.CDLL("libseccomp.so.2", use_errno=True)
17
+ lib.seccomp_init.argtypes = [ctypes.c_uint32]
18
+ lib.seccomp_init.restype = ctypes.c_void_p
19
+ lib.seccomp_rule_add.argtypes = [
20
+ ctypes.c_void_p,
21
+ ctypes.c_uint32,
22
+ ctypes.c_int,
23
+ ctypes.c_uint,
24
+ ]
25
+ lib.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p]
26
+ lib.seccomp_load.argtypes = [ctypes.c_void_p]
27
+ lib.seccomp_release.argtypes = [ctypes.c_void_p]
28
+ ctx = lib.seccomp_init(0x7FFF0000) # SCMP_ACT_ALLOW
29
+ if not ctx:
30
+ raise RuntimeError("Cannot initialize execution isolation")
31
+ try:
32
+ for name in (
33
+ "socket",
34
+ "socketpair",
35
+ "connect",
36
+ "ptrace",
37
+ "process_vm_readv",
38
+ "process_vm_writev",
39
+ "mount",
40
+ "unshare",
41
+ "setns",
42
+ "bpf",
43
+ ):
44
+ number = lib.seccomp_syscall_resolve_name(name.encode())
45
+ if (
46
+ number >= 0
47
+ and lib.seccomp_rule_add(ctx, 0x00050000 | errno.EPERM, number, 0) != 0
48
+ ):
49
+ raise RuntimeError("Cannot install execution isolation rule")
50
+ if lib.seccomp_load(ctx) != 0:
51
+ raise RuntimeError("Cannot activate execution isolation")
52
+ finally:
53
+ lib.seccomp_release(ctx)
54
+
55
+ sys.path.insert(0, "/app")
56
+ from simulator import ToolSimulator # noqa: E402
57
+
58
+ request = json.load(sys.stdin)
59
+ json.dump(ToolSimulator().code_py_exec(request), sys.stdout)
tasks/agentescape-10-skeleton-ac5cd29c/environment/puzzle/export.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Harbor invokes this inside the puzzle service after stopping the agent."""
2
+
3
+ import json
4
+ import pathlib
5
+ import urllib.request
6
+
7
+ with urllib.request.urlopen("http://127.0.0.1:8000/state", timeout=10) as response:
8
+ state = json.load(response)
9
+ state["collected_from_live_service"] = True
10
+ target = pathlib.Path("/evidence/final.json")
11
+ temp = target.with_suffix(".tmp")
12
+ temp.write_text(json.dumps(state))
13
+ temp.replace(target)
tasks/agentescape-10-skeleton-ac5cd29c/environment/puzzle/requirements.txt ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ annotated-doc==0.0.5
2
+ # via fastapi
3
+ annotated-types==0.8.0
4
+ # via pydantic
5
+ anyio==4.16.0
6
+ # via starlette
7
+ certifi==2026.10.23
8
+ # via requests
9
+ cffi==2.1.1 ; platform_python_implementation != 'PyPy'
10
+ # via cryptography
11
+ charset-normalizer==3.5.2
12
+ # via requests
13
+ click==8.5.0
14
+ # via uvicorn
15
+ cryptography==50.0.2
16
+ # via agentescapebench-harbor
17
+ fastapi==0.162.0
18
+ # via agentescapebench-harbor
19
+ h11==0.16.0
20
+ # via uvicorn
21
+ idna==3.20
22
+ # via
23
+ # anyio
24
+ # requests
25
+ opentelemetry-api==1.45.2
26
+ # via fastapi
27
+ pycparser==3.12 ; implementation_name != 'PyPy' and platform_python_implementation != 'PyPy'
28
+ # via cffi
29
+ pydantic==2.14.2
30
+ # via
31
+ # agentescapebench-harbor
32
+ # fastapi
33
+ pydantic-core==2.50.2
34
+ # via pydantic
35
+ pytz==2025.2
36
+ # via agentescapebench-harbor
37
+ requests==2.34.2
38
+ # via agentescapebench-harbor
39
+ starlette==1.10.0
40
+ # via fastapi
41
+ typing-extensions==4.16.0
42
+ # via
43
+ # anyio
44
+ # fastapi
45
+ # opentelemetry-api
46
+ # pydantic
47
+ # pydantic-core
48
+ # starlette
49
+ # typing-inspection
50
+ typing-inspection==0.4.4
51
+ # via
52
+ # fastapi
53
+ # pydantic
54
+ urllib3==2.8.0
55
+ # via requests
56
+ uvicorn==0.54.0
57
+ # via agentescapebench-harbor
tasks/agentescape-10-skeleton-ac5cd29c/environment/puzzle/scenario.json ADDED
@@ -0,0 +1,511 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_nodes": 10,
4
+ "total_edges": 9,
5
+ "win_node_id": "item_8",
6
+ "win_condition": {
7
+ "type": "item_content",
8
+ "node_id": "item_8",
9
+ "description": "Obtain the content of "
10
+ },
11
+ "source_init": {
12
+ "source_nodes": [
13
+ "item_8",
14
+ "terminal_1",
15
+ "calc_gcd",
16
+ "num_base_convert"
17
+ ],
18
+ "by_node": {
19
+ "item_8": {
20
+ "node_name": "",
21
+ "node_type": "Item",
22
+ "template_id": "item_8",
23
+ "init_inputs": {},
24
+ "init_outputs": {
25
+ "content": {
26
+ "type": "Hidden_Item",
27
+ "description": "The integer"
28
+ }
29
+ }
30
+ },
31
+ "terminal_1": {
32
+ "node_name": "",
33
+ "node_type": "Tool",
34
+ "template_id": "terminal_1",
35
+ "init_inputs": {
36
+ "slot_a": {
37
+ "type": "Text_Generic",
38
+ "description": "Input Slot A"
39
+ }
40
+ },
41
+ "init_outputs": {
42
+ "text_output": {
43
+ "type": "Text_Generic",
44
+ "description": "Text output when only slot_a is provided"
45
+ },
46
+ "hex_output": {
47
+ "type": "Hex_String",
48
+ "description": "Hex output when only slot_b is provided"
49
+ },
50
+ "item_dispenser": {
51
+ "type": "Item",
52
+ "description": "Item output when both slots are provided"
53
+ }
54
+ }
55
+ },
56
+ "calc_gcd": {
57
+ "node_name": "BigInt GCD Calculator",
58
+ "node_type": "Tool",
59
+ "template_id": "calc_gcd",
60
+ "init_inputs": {
61
+ "b": {
62
+ "type": "Big_Int",
63
+ "description": "Second integer"
64
+ }
65
+ },
66
+ "init_outputs": {}
67
+ },
68
+ "num_base_convert": {
69
+ "node_name": "Base Converter",
70
+ "node_type": "Tool",
71
+ "template_id": "num_base_convert",
72
+ "init_inputs": {
73
+ "s": {
74
+ "type": "Big_Int",
75
+ "description": "Input integer value"
76
+ },
77
+ "from_base": {
78
+ "type": "Big_Int",
79
+ "description": "From base"
80
+ },
81
+ "to_base": {
82
+ "type": "Big_Int",
83
+ "description": "To base"
84
+ }
85
+ },
86
+ "init_outputs": {}
87
+ }
88
+ }
89
+ },
90
+ "initial_values": {
91
+ "item_8": {
92
+ "init_inputs": {},
93
+ "init_outputs": {
94
+ "content": "437481758470817328469123657125"
95
+ }
96
+ },
97
+ "terminal_1": {
98
+ "init_inputs": {
99
+ "slot_a": "Standard input for terminal verification."
100
+ },
101
+ "init_outputs": {
102
+ "text_output": "Operation complete. Terminal is ready for input.",
103
+ "hex_output": "deadbeef12345678deadbeef12345678",
104
+ "item_dispenser": "A dusty box containing absolutely nothing of value."
105
+ }
106
+ },
107
+ "calc_gcd": {
108
+ "init_inputs": {
109
+ "b": "4857201938475629103847"
110
+ },
111
+ "init_outputs": {}
112
+ },
113
+ "num_base_convert": {
114
+ "init_inputs": {
115
+ "s": "2938475610293847561029",
116
+ "from_base": "10",
117
+ "to_base": "10"
118
+ },
119
+ "init_outputs": {}
120
+ }
121
+ },
122
+ "intro_narrative": "The sudden disappearance of private investigator Arthur Black has left the city's underbelly in chaos. You've broken into his abandoned office, a room thick with dust and the smell of stale tobacco. Arthur was on the verge of cracking a massive case involving a local smuggling ring, but his crucial findings are locked away behind a series of cryptic devices and hidden safes. The clock is ticking—the same dangerous people who made Arthur disappear are likely coming to destroy his files. Your objective is to follow his trail of breadcrumbs, piece together his scattered evidence, and recover his final, damning document before the truth is lost forever.",
123
+ "narrative_style": "mystery"
124
+ },
125
+ "nodes": [
126
+ {
127
+ "id": "item_8",
128
+ "name": "",
129
+ "description": "",
130
+ "type": "Item",
131
+ "template_id": "item_8",
132
+ "initial_visible": false,
133
+ "is_revealed": false,
134
+ "inputs": [
135
+ {
136
+ "name": "source_tool",
137
+ "type": "Hidden_Item",
138
+ "description": "Produced by"
139
+ }
140
+ ],
141
+ "outputs": [
142
+ {
143
+ "name": "content",
144
+ "type": "Hidden_Item",
145
+ "description": "The integer",
146
+ "value": "437481758470817328469123657125"
147
+ }
148
+ ],
149
+ "init": {
150
+ "inputs": {},
151
+ "outputs": {
152
+ "content": "437481758470817328469123657125"
153
+ }
154
+ },
155
+ "narrative": "The final Confession Letter, sealed with a wax stamp. It holds the ultimate truth of the mystery."
156
+ },
157
+ {
158
+ "id": "item_8_9e9c",
159
+ "name": "",
160
+ "description": "",
161
+ "type": "Item",
162
+ "template_id": "item_8",
163
+ "initial_visible": false,
164
+ "is_revealed": false,
165
+ "inputs": [
166
+ {
167
+ "name": "source_tool",
168
+ "type": "Hidden_Item",
169
+ "description": "Produced by"
170
+ }
171
+ ],
172
+ "outputs": [
173
+ {
174
+ "name": "content",
175
+ "type": "Hidden_Item",
176
+ "description": "The integer"
177
+ }
178
+ ],
179
+ "narrative": "A heavily redacted police report detailing the initial raid on the warehouse."
180
+ },
181
+ {
182
+ "id": "item_8_e7fd",
183
+ "name": "",
184
+ "description": "",
185
+ "type": "Item",
186
+ "template_id": "item_8",
187
+ "initial_visible": false,
188
+ "is_revealed": false,
189
+ "inputs": [
190
+ {
191
+ "name": "source_tool",
192
+ "type": "Hidden_Item",
193
+ "description": "Produced by"
194
+ }
195
+ ],
196
+ "outputs": [
197
+ {
198
+ "name": "content",
199
+ "type": "Hidden_Item",
200
+ "description": "The integer"
201
+ }
202
+ ],
203
+ "narrative": "A hasty witness statement scribbled on the back of a greasy diner napkin."
204
+ },
205
+ {
206
+ "id": "item_8_4200",
207
+ "name": "",
208
+ "description": "",
209
+ "type": "Item",
210
+ "template_id": "item_8",
211
+ "initial_visible": false,
212
+ "is_revealed": false,
213
+ "inputs": [
214
+ {
215
+ "name": "source_tool",
216
+ "type": "Hidden_Item",
217
+ "description": "Produced by"
218
+ }
219
+ ],
220
+ "outputs": [
221
+ {
222
+ "name": "content",
223
+ "type": "Hidden_Item",
224
+ "description": "The integer"
225
+ }
226
+ ],
227
+ "narrative": "A blurry photograph of a shadowy figure standing near the docks at midnight."
228
+ },
229
+ {
230
+ "id": "item_16",
231
+ "name": "",
232
+ "description": "",
233
+ "type": "Item",
234
+ "template_id": "item_16",
235
+ "initial_visible": false,
236
+ "is_revealed": false,
237
+ "inputs": [
238
+ {
239
+ "name": "source_tool",
240
+ "type": "Item",
241
+ "description": "Produced by"
242
+ }
243
+ ],
244
+ "outputs": [
245
+ {
246
+ "name": "content",
247
+ "type": "Hidden_Item",
248
+ "description": "Timezone text"
249
+ }
250
+ ],
251
+ "narrative": "A torn travel itinerary that lists flights across multiple timezones."
252
+ },
253
+ {
254
+ "id": "container_4",
255
+ "name": "",
256
+ "description": "",
257
+ "type": "Item",
258
+ "template_id": "container_4",
259
+ "initial_visible": false,
260
+ "is_revealed": false,
261
+ "inputs": [
262
+ {
263
+ "name": "container",
264
+ "type": "Hidden_Item",
265
+ "description": "Inside"
266
+ },
267
+ {
268
+ "name": "fingerprint_input",
269
+ "type": "Text_Generic",
270
+ "description": "Fingerprint Hash",
271
+ "value": "Operation complete. Terminal is ready for input."
272
+ }
273
+ ],
274
+ "outputs": [
275
+ {
276
+ "name": "inner_space",
277
+ "type": "Item",
278
+ "description": "Contents"
279
+ }
280
+ ],
281
+ "narrative": "A reinforced Evidence Safe hidden behind a dusty bookshelf. It requires input from the Detective's Computer to authorize access and unlock."
282
+ },
283
+ {
284
+ "id": "item_16_d0f0",
285
+ "name": "",
286
+ "description": "",
287
+ "type": "Item",
288
+ "template_id": "item_16",
289
+ "initial_visible": true,
290
+ "is_revealed": true,
291
+ "inputs": [
292
+ {
293
+ "name": "source_tool",
294
+ "type": "Item",
295
+ "description": "Produced by"
296
+ }
297
+ ],
298
+ "outputs": [
299
+ {
300
+ "name": "content",
301
+ "type": "Hidden_Item",
302
+ "description": "Timezone text"
303
+ }
304
+ ],
305
+ "narrative": "A cracked pocket watch recovered from the crime scene, its hands suspiciously frozen in time."
306
+ },
307
+ {
308
+ "id": "terminal_1",
309
+ "name": "",
310
+ "description": "",
311
+ "type": "Tool",
312
+ "template_id": "terminal_1",
313
+ "initial_visible": true,
314
+ "is_revealed": true,
315
+ "inputs": [
316
+ {
317
+ "name": "slot_a",
318
+ "type": "Text_Generic",
319
+ "description": "Input Slot A",
320
+ "value": "Standard input for terminal verification."
321
+ },
322
+ {
323
+ "name": "slot_b",
324
+ "type": "Big_Int",
325
+ "description": "Input Slot B",
326
+ "value": "1"
327
+ }
328
+ ],
329
+ "outputs": [
330
+ {
331
+ "name": "text_output",
332
+ "type": "Text_Generic",
333
+ "description": "Text output when only slot_a is provided",
334
+ "value": "Operation complete. Terminal is ready for input."
335
+ },
336
+ {
337
+ "name": "hex_output",
338
+ "type": "Hex_String",
339
+ "description": "Hex output when only slot_b is provided",
340
+ "value": "deadbeef12345678deadbeef12345678"
341
+ },
342
+ {
343
+ "name": "item_dispenser",
344
+ "type": "Item",
345
+ "description": "Item output when both slots are provided",
346
+ "value": "A dusty box containing absolutely nothing of value."
347
+ }
348
+ ],
349
+ "init": {
350
+ "inputs": {
351
+ "slot_a": "Standard input for terminal verification."
352
+ },
353
+ "outputs": {
354
+ "text_output": "Operation complete. Terminal is ready for input.",
355
+ "hex_output": "deadbeef12345678deadbeef12345678",
356
+ "item_dispenser": "A dusty box containing absolutely nothing of value."
357
+ }
358
+ },
359
+ "narrative": "The Detective's Computer sitting quietly on the mahogany desk. It requires input from the Frequency Analyzer to bypass its lock screen."
360
+ },
361
+ {
362
+ "id": "calc_gcd",
363
+ "name": "BigInt GCD Calculator",
364
+ "description": "Greatest common divisor of two large decimal integers.",
365
+ "type": "Tool",
366
+ "template_id": "calc_gcd",
367
+ "initial_visible": true,
368
+ "is_revealed": true,
369
+ "inputs": [
370
+ {
371
+ "name": "a",
372
+ "type": "Big_Int",
373
+ "description": "First integer",
374
+ "value": "2938475610293847561029"
375
+ },
376
+ {
377
+ "name": "b",
378
+ "type": "Big_Int",
379
+ "description": "Second integer",
380
+ "value": "4857201938475629103847"
381
+ }
382
+ ],
383
+ "outputs": [
384
+ {
385
+ "name": "gcd",
386
+ "type": "Big_Int",
387
+ "description": "GCD result",
388
+ "value": "1"
389
+ }
390
+ ],
391
+ "init": {
392
+ "inputs": {
393
+ "b": "4857201938475629103847"
394
+ },
395
+ "outputs": {}
396
+ },
397
+ "narrative": "A heavy, brass-fitted Frequency Analyzer. It requires input from the Signal Decoder to isolate the correct frequency hidden in the noise."
398
+ },
399
+ {
400
+ "id": "num_base_convert",
401
+ "name": "Base Converter",
402
+ "description": "Convert integer between bases (2..36).",
403
+ "type": "Tool",
404
+ "template_id": "num_base_convert",
405
+ "initial_visible": true,
406
+ "is_revealed": true,
407
+ "inputs": [
408
+ {
409
+ "name": "s",
410
+ "type": "Big_Int",
411
+ "description": "Input integer value",
412
+ "value": "2938475610293847561029"
413
+ },
414
+ {
415
+ "name": "from_base",
416
+ "type": "Big_Int",
417
+ "description": "From base",
418
+ "value": "10"
419
+ },
420
+ {
421
+ "name": "to_base",
422
+ "type": "Big_Int",
423
+ "description": "To base",
424
+ "value": "10"
425
+ }
426
+ ],
427
+ "outputs": [
428
+ {
429
+ "name": "str",
430
+ "type": "Big_Int",
431
+ "description": "Converted integer value",
432
+ "value": "2938475610293847561029"
433
+ }
434
+ ],
435
+ "init": {
436
+ "inputs": {
437
+ "s": "2938475610293847561029",
438
+ "from_base": "10",
439
+ "to_base": "10"
440
+ },
441
+ "outputs": {}
442
+ },
443
+ "narrative": "An antique Signal Decoder left behind by the missing detective. It looks like it was used to translate strange underground broadcasts."
444
+ }
445
+ ],
446
+ "edges": [
447
+ {
448
+ "source_id": "item_8_9e9c",
449
+ "target_id": "item_8",
450
+ "connection_type": "Hidden_Item",
451
+ "source_port": "content",
452
+ "target_port": "source_tool"
453
+ },
454
+ {
455
+ "source_id": "item_8_e7fd",
456
+ "target_id": "item_8_9e9c",
457
+ "connection_type": "Hidden_Item",
458
+ "source_port": "content",
459
+ "target_port": "source_tool"
460
+ },
461
+ {
462
+ "source_id": "item_8_4200",
463
+ "target_id": "item_8_e7fd",
464
+ "connection_type": "Hidden_Item",
465
+ "source_port": "content",
466
+ "target_port": "source_tool"
467
+ },
468
+ {
469
+ "source_id": "item_16",
470
+ "target_id": "item_8_4200",
471
+ "connection_type": "Hidden_Item",
472
+ "source_port": "content",
473
+ "target_port": "source_tool"
474
+ },
475
+ {
476
+ "source_id": "container_4",
477
+ "target_id": "item_16",
478
+ "connection_type": "Item",
479
+ "source_port": "inner_space",
480
+ "target_port": "source_tool"
481
+ },
482
+ {
483
+ "source_id": "item_16_d0f0",
484
+ "target_id": "container_4",
485
+ "connection_type": "Hidden_Item",
486
+ "source_port": "content",
487
+ "target_port": "container"
488
+ },
489
+ {
490
+ "source_id": "terminal_1",
491
+ "target_id": "container_4",
492
+ "connection_type": "Text_Generic",
493
+ "source_port": "text_output",
494
+ "target_port": "fingerprint_input"
495
+ },
496
+ {
497
+ "source_id": "calc_gcd",
498
+ "target_id": "terminal_1",
499
+ "connection_type": "Big_Int",
500
+ "source_port": "gcd",
501
+ "target_port": "slot_b"
502
+ },
503
+ {
504
+ "source_id": "num_base_convert",
505
+ "target_id": "calc_gcd",
506
+ "connection_type": "Big_Int",
507
+ "source_port": "str",
508
+ "target_port": "a"
509
+ }
510
+ ]
511
+ }
tasks/agentescape-10-skeleton-ac5cd29c/environment/puzzle/service.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Restricted facade over the unchanged, pinned upstream puzzle handlers."""
2
+
3
+ import hashlib
4
+ import json
5
+ import logging
6
+ import os
7
+ import sys
8
+ import threading
9
+ import urllib.request
10
+ import uuid
11
+ from pathlib import Path
12
+
13
+ from fastapi import FastAPI, HTTPException
14
+ from fastapi.responses import JSONResponse
15
+ from pydantic import BaseModel, ConfigDict
16
+
17
+ sys.path.insert(0, str(Path(__file__).parent / "upstream"))
18
+ import server as upstream # noqa: E402
19
+
20
+ log = logging.getLogger(__name__)
21
+
22
+
23
+ def public(value):
24
+ """Keep upstream agent-internal template hints out of the public response."""
25
+ if isinstance(value, dict):
26
+ return {k: public(v) for k, v in value.items() if not k.startswith("_")}
27
+ if isinstance(value, list):
28
+ return [public(v) for v in value]
29
+ return value
30
+
31
+
32
+ class Action(BaseModel):
33
+ model_config = ConfigDict(extra="forbid", strict=True)
34
+ action: str
35
+ node_id: str | None = None
36
+ arguments: dict | None = None
37
+ answer: str | None = None
38
+
39
+
40
+ class Episode:
41
+ def __init__(
42
+ self, scenario_path, max_actions=500, evidence_dir=None, worker_url=None
43
+ ):
44
+ if max_actions < 1:
45
+ raise ValueError("max_actions must be positive")
46
+ self.lock = threading.Lock()
47
+ self.max_actions = max_actions
48
+ self.count = 0
49
+ self.won = False
50
+ self.reason = None
51
+ self.evidence_dir = Path(evidence_dir) if evidence_dir else None
52
+ self.scenario_hash = hashlib.sha256(
53
+ Path(scenario_path).read_bytes()
54
+ ).hexdigest()
55
+ self.initial = upstream.reset_case(
56
+ case_file_path=str(scenario_path), session_id=uuid.uuid4().hex
57
+ )
58
+ self.case_id = self.initial["case_id"]
59
+ # Hide source file paths; no upstream reset/stats/routes are mounted.
60
+ self.initial.pop("message", None)
61
+ simulator = upstream.SIMULATORS[self.case_id]
62
+ if worker_url is None:
63
+
64
+ def no_worker(_inputs):
65
+ self.reason = "infrastructure_error"
66
+ raise RuntimeError("isolated Python worker is not configured")
67
+
68
+ simulator.tool_map["code_py_exec"] = no_worker
69
+ else:
70
+
71
+ def execute_python(inputs):
72
+ request = urllib.request.Request(
73
+ worker_url + "/execute",
74
+ data=json.dumps({"code": inputs.get("code", "")}).encode(),
75
+ headers={"Content-Type": "application/json"},
76
+ )
77
+ try:
78
+ with urllib.request.urlopen(request, timeout=12) as response:
79
+ result = json.load(response)
80
+ if not isinstance(result.get("stdout"), str):
81
+ raise RuntimeError("Invalid Python worker response")
82
+ return result
83
+ except Exception:
84
+ self.reason = "infrastructure_error"
85
+ raise
86
+
87
+ simulator.tool_map["code_py_exec"] = execute_python
88
+ self.save()
89
+ if self.evidence_dir is not None:
90
+ (self.evidence_dir / "trace.jsonl").touch()
91
+
92
+ def state(self):
93
+ return {
94
+ "scenario_sha256": self.scenario_hash,
95
+ "action_count": self.count,
96
+ "max_actions": self.max_actions,
97
+ "won": self.won,
98
+ "termination_reason": self.reason,
99
+ }
100
+
101
+ def save(self, action=None, result=None):
102
+ if self.evidence_dir is None:
103
+ return
104
+ self.evidence_dir.mkdir(parents=True, exist_ok=True)
105
+ target = self.evidence_dir / "outcome.json"
106
+ temp = target.with_suffix(".tmp")
107
+ temp.write_text(json.dumps(self.state()))
108
+ temp.replace(target)
109
+ if action is not None:
110
+ with (self.evidence_dir / "trace.jsonl").open("a") as handle:
111
+ handle.write(
112
+ json.dumps(
113
+ {"index": self.count, "action": action, "result": result}
114
+ )
115
+ + "\n"
116
+ )
117
+
118
+ def dispatch(self, payload):
119
+ with self.lock:
120
+ if self.reason is not None:
121
+ return {
122
+ "ok": False,
123
+ "error": "Episode has ended",
124
+ "episode": self.state(),
125
+ }
126
+ self.count += 1
127
+ try:
128
+ action = Action.model_validate(payload)
129
+ if action.action == "submit_answer" and action.answer is not None:
130
+ result = upstream.submit_answer(
131
+ self.case_id, upstream.SubmitAnswerRequest(answer=action.answer)
132
+ )
133
+ if result.get("is_win"):
134
+ self.won = True
135
+ self.reason = "success"
136
+ elif action.action == "investigate" and action.node_id is not None:
137
+ result = upstream.investigate(
138
+ self.case_id,
139
+ upstream.InvestigateRequest(node_id=action.node_id),
140
+ )
141
+ elif (
142
+ action.action in ("tool_call", "use_item")
143
+ and action.node_id is not None
144
+ ):
145
+ request_type, handler = (
146
+ (upstream.ToolCallRequest, upstream.tool_call)
147
+ if action.action == "tool_call"
148
+ else (upstream.UseItemRequest, upstream.use_item)
149
+ )
150
+ result = handler(
151
+ self.case_id,
152
+ request_type(
153
+ node_id=action.node_id, arguments=action.arguments or {}
154
+ ),
155
+ )
156
+ else:
157
+ result = {
158
+ "ok": False,
159
+ "error": "Unknown action or missing action parameter",
160
+ }
161
+ except HTTPException as exc:
162
+ result = {"ok": False, "error": exc.detail}
163
+ except ValueError:
164
+ result = {"ok": False, "error": "Malformed action"}
165
+ except Exception:
166
+ log.exception("Puzzle service failure")
167
+ self.reason = "infrastructure_error"
168
+ self.save()
169
+ raise
170
+ if self.reason is None and self.count >= self.max_actions:
171
+ self.reason = "action_budget_exhausted"
172
+ result = public(result)
173
+ result["episode"] = self.state()
174
+ self.save(payload, result)
175
+ return result
176
+
177
+
178
+ def create_app(
179
+ scenario_path=None, max_actions=None, evidence_dir=None, worker_url=None
180
+ ):
181
+ episode = Episode(
182
+ scenario_path or os.environ["SCENARIO_PATH"],
183
+ max_actions or int(os.environ.get("MAX_ACTIONS", "500")),
184
+ evidence_dir if evidence_dir is not None else os.environ.get("EVIDENCE_DIR"),
185
+ worker_url if worker_url is not None else os.environ.get("WORKER_URL"),
186
+ )
187
+ app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
188
+ app.state.episode = episode
189
+
190
+ @app.get("/health")
191
+ def health():
192
+ return {"ok": True}
193
+
194
+ @app.get("/observation")
195
+ def observation():
196
+ return {**public(episode.initial), "episode": episode.state()}
197
+
198
+ @app.get("/state")
199
+ def state():
200
+ return episode.state()
201
+
202
+ @app.post("/action")
203
+ def action(payload: dict):
204
+ try:
205
+ return episode.dispatch(payload)
206
+ except Exception:
207
+ return JSONResponse(
208
+ status_code=503,
209
+ content={"ok": False, "error": "Puzzle infrastructure failure"},
210
+ )
211
+
212
+ return app
tasks/agentescape-10-skeleton-ac5cd29c/environment/puzzle/upstream/models.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from enum import Enum
2
+ from typing import List, Dict, Any, Optional
3
+ from pydantic import BaseModel, Field
4
+
5
+ # 1. 细粒度接口类型定义
6
+ class InterfaceType(str, Enum):
7
+ '''
8
+ BIG_INT
9
+ TEXT_GENERIC
10
+ HEX_STRING
11
+ FILE_ID
12
+ HEX_STRING_KEY_AES
13
+ HEX_STRING_IV_AES
14
+ CODE_PYTHON
15
+ HIDDEN_ITEM
16
+ ITEM
17
+ '''
18
+ # --- 基础类型 ---
19
+ TEXT_GENERIC = "Text_Generic"
20
+ BIG_INT = "Big_Int"
21
+
22
+ # --- 编码/格式化字符串 ---
23
+ HEX_STRING = "Hex_String" # 通用 Hex
24
+
25
+ # --- 特定用途的 Hex 字符串 (用于精确匹配) ---
26
+ HEX_STRING_KEY_AES = "Hex_String_Key_AES"
27
+ HEX_STRING_IV_AES = "Hex_String_IV_AES"
28
+
29
+ # --- 文件类型 ---
30
+ FILE_ID = "File_Id"
31
+
32
+ # --- 代码/脚本 ---
33
+ CODE_PYTHON = "Code_Python"
34
+
35
+ # --- 实体交互类型 (严格命名) ---
36
+ ITEM = "Item" # 主动掉落接口 (Tool -> Item)
37
+ HIDDEN_ITEM = "Hidden_Item" # 被动掉落接口 (Item -> Item)
38
+
39
+ # 3. 端口定义
40
+ class Port(BaseModel):
41
+ name: str
42
+ type: InterfaceType
43
+ description: str
44
+
45
+ # 4. 统一节点定义 (融合工具和物品)
46
+ class Node(BaseModel):
47
+ id: str
48
+ name: str
49
+ description: str
50
+ type: str # "Tool" or "Item"
51
+
52
+ # 接口定义
53
+ inputs: List[Port] = []
54
+ outputs: List[Port] = []
55
+
56
+ # 状态字段
57
+ content: Optional[Any] = None # 物品有内容,工具为None
58
+ if_success: Optional[bool] = None # 工具初始为False,物品为None
59
+ initial_visible: bool = False
60
+
61
+ # 运行时状态 (Server维护)
62
+ is_revealed: bool = False
63
+
64
+ # 标记该 Tool 节点是否有待触发的 HIDDEN_ITEM 掉落
65
+ # 当 Tool 按照 golden_input 正确执行且有 HIDDEN_ITEM 输出边时设为 True
66
+ # 在 investigate 该 Tool 时触发掉落并重置为 False
67
+ has_hidden_item_ready: bool = False
68
+
69
+ # 初始输入值 (metadata.initial_values.init_inputs,用于渐进式暴露判断)
70
+ init_input_values: Dict[str, Any] = {}
71
+
72
+ # Golden 输入值 (nodes[].inputs[].value,用于评测验证)
73
+ golden_input_values: Dict[str, Any] = {}
74
+
75
+ # Golden 输出值 (nodes[].outputs[].value,用于评测验证和 Item 节点的 content)
76
+ golden_output_values: Dict[str, Any] = {}
77
+
78
+ # 实际获得的输出值历史 (工具每次执行后实际返回的输出列表,用于渐进式暴露判断)
79
+ # 格式: List[Dict[str, Any]],每个元素是一次执行的输出字典
80
+ actual_outputs_history: List[Dict[str, Any]] = []
81
+
82
+ # 逻辑规则 (用于终端机等复杂物品)
83
+ logic_rules: Optional[Dict[str, Any]] = None
84
+
85
+ def copy(self, **kwargs):
86
+ """Helper to create a copy with updated fields."""
87
+ data = self.dict()
88
+ data.update(kwargs)
89
+ return Node(**data)
90
+
91
+ # 5. 边定义 (拓扑结构)
92
+ class Edge(BaseModel):
93
+ source_id: str
94
+ target_id: str
95
+ connection_type: InterfaceType # 直接使用 InterfaceType
96
+ # 如果是 Data_Flow,指定端口对应关系
97
+ source_port: Optional[str] = None
98
+ target_port: Optional[str] = None
99
+
100
+ # 6. 完整图定义
101
+ class GraphScenario(BaseModel):
102
+ case_id: str
103
+ title: str
104
+ intro_narrative: str
105
+ nodes: Dict[str, Node]
106
+ edges: List[Edge]
107
+ difficulty: int
108
+ win_node_id: str # 标记哪个节点是最终目标(通常是一个提交工具或最终物品)
tasks/agentescape-10-skeleton-ac5cd29c/environment/puzzle/upstream/server.py ADDED
@@ -0,0 +1,1490 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import time
4
+ import logging
5
+ import random
6
+ from pathlib import Path
7
+ from typing import Dict, Any, List, Optional
8
+ from datetime import datetime
9
+ from collections import defaultdict
10
+ from fastapi import FastAPI, HTTPException, Request
11
+ from fastapi.responses import JSONResponse
12
+ from fastapi.middleware.cors import CORSMiddleware
13
+ from pydantic import BaseModel, Field
14
+
15
+ from models import GraphScenario, Node, InterfaceType
16
+ # from generator import ScenarioGenerator
17
+ from simulator import ToolSimulator
18
+ import uvicorn
19
+
20
+ # 配置日志
21
+ logging.basicConfig(
22
+ level=logging.INFO,
23
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
24
+ handlers=[
25
+ logging.FileHandler('server.log'),
26
+ logging.StreamHandler()
27
+ ]
28
+ )
29
+ logger = logging.getLogger(__name__)
30
+
31
+ app = FastAPI(
32
+ title="AgentEscapeBench Universal Server",
33
+ version="1.0.0",
34
+ description="Industrial-grade evaluation server for escape room AI agents"
35
+ )
36
+
37
+ # 添加 CORS 支持
38
+ app.add_middleware(
39
+ CORSMiddleware,
40
+ allow_origins=["*"],
41
+ allow_credentials=True,
42
+ allow_methods=["*"],
43
+ allow_headers=["*"],
44
+ )
45
+
46
+ # In-memory State
47
+ SCENARIOS: Dict[str, GraphScenario] = {}
48
+ SIMULATORS: Dict[str, ToolSimulator] = {} # case_id -> ToolSimulator
49
+ RAW_NODES_DATA: Dict[str, Dict[str, Any]] = {} # case_id -> node_id -> raw node data (for template_id)
50
+ FILE_METADATA: Dict[str, Dict[str, Any]] = {} # case_id -> metadata (for initial_values access)
51
+
52
+ # Performance monitoring
53
+ STATS: Dict[str, Any] = {
54
+ "total_requests": 0,
55
+ "successful_requests": 0,
56
+ "failed_requests": 0,
57
+ "tool_calls": defaultdict(int),
58
+ "investigates": defaultdict(int),
59
+ "use_items": defaultdict(int),
60
+ "case_loads": 0,
61
+ "start_time": datetime.now()
62
+ }
63
+
64
+ # Request timing middleware
65
+ @app.middleware("http")
66
+ async def add_process_time_header(request: Request, call_next):
67
+ start_time = time.time()
68
+ STATS["total_requests"] += 1
69
+
70
+ try:
71
+ response = await call_next(request)
72
+ STATS["successful_requests"] += 1
73
+ process_time = time.time() - start_time
74
+ response.headers["X-Process-Time"] = str(process_time)
75
+ logger.info(f"{request.method} {request.url.path} - {response.status_code} - {process_time:.3f}s")
76
+ return response
77
+ except Exception as e:
78
+ STATS["failed_requests"] += 1
79
+ logger.error(f"{request.method} {request.url.path} - Error: {str(e)}")
80
+ raise
81
+
82
+ # Exception handler
83
+ @app.exception_handler(Exception)
84
+ async def global_exception_handler(request: Request, exc: Exception):
85
+ logger.error(f"Unhandled exception: {exc}", exc_info=True)
86
+ return JSONResponse(
87
+ status_code=500,
88
+ content={
89
+ "ok": False,
90
+ "error": "Internal server error",
91
+ "detail": str(exc) if os.getenv("DEBUG") else "An error occurred"
92
+ }
93
+ )
94
+
95
+ # Health check endpoint
96
+ @app.get("/health")
97
+ def health_check():
98
+ """健康检查端点"""
99
+ uptime = (datetime.now() - STATS["start_time"]).total_seconds()
100
+ return {
101
+ "status": "healthy",
102
+ "version": "1.0.0",
103
+ "uptime_seconds": uptime,
104
+ "loaded_cases": len(SCENARIOS),
105
+ "stats": {
106
+ "total_requests": STATS["total_requests"],
107
+ "successful_requests": STATS["successful_requests"],
108
+ "failed_requests": STATS["failed_requests"],
109
+ "success_rate": STATS["successful_requests"] / max(STATS["total_requests"], 1)
110
+ }
111
+ }
112
+
113
+ # Statistics endpoint
114
+ @app.get("/stats")
115
+ def get_stats():
116
+ """获取详细统计信息"""
117
+ return {
118
+ "stats": STATS,
119
+ "loaded_cases": list(SCENARIOS.keys()),
120
+ "uptime": str(datetime.now() - STATS["start_time"])
121
+ }
122
+
123
+ def _apply_progressive_reveal_at_init(scenario: GraphScenario):
124
+ """
125
+ 在初始化时应用渐进式暴露机制(基于ITEM/HIDDEN_ITEM边)
126
+
127
+ 新逻辑:
128
+ - 如果一个节点没有 ITEM/HIDDEN_ITEM 类型的入边,它就是初始可见的
129
+ - 如果一个节点有 ITEM/HIDDEN_ITEM 类型的入边,它初始不可见,需要等待上游触发
130
+
131
+ Args:
132
+ scenario: 场景对象
133
+ """
134
+ # 收集所有有 ITEM/HIDDEN_ITEM 入边的节点
135
+ nodes_with_item_edges = set()
136
+ for edge in scenario.edges:
137
+ if edge.connection_type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]:
138
+ nodes_with_item_edges.add(edge.target_id)
139
+
140
+ logger.info(f"Nodes with ITEM/HIDDEN_ITEM incoming edges: {nodes_with_item_edges}")
141
+
142
+ # 设置初始可见性:没有 ITEM/HIDDEN_ITEM 入边的节点初始可见
143
+ initially_visible_count = 0
144
+ for node_id, node in scenario.nodes.items():
145
+ if node_id not in nodes_with_item_edges:
146
+ node.is_revealed = True
147
+ initially_visible_count += 1
148
+ logger.info(f"Initial visible (no ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})")
149
+ else:
150
+ node.is_revealed = False
151
+ logger.debug(f"Initial hidden (has ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})")
152
+
153
+ logger.info(f"Progressive reveal initialized: {initially_visible_count}/{len(scenario.nodes)} nodes initially visible")
154
+
155
+
156
+ def _check_inputs_match_golden(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> bool:
157
+ """
158
+ 检查实际输入参数是否与 golden inputs 完全匹配
159
+
160
+ Args:
161
+ arguments: 实际调用时传入的参数
162
+ golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value)
163
+
164
+ Returns:
165
+ True 表示所有 golden inputs 都存在且值匹配
166
+ """
167
+ if not golden_inputs:
168
+ return True # 如果没有 golden inputs,认为匹配
169
+
170
+ for key, expected_value in golden_inputs.items():
171
+ actual_value = arguments.get(key)
172
+ # 转换为字符串比较,避免类型问题(如 int vs str)
173
+ if str(actual_value) != str(expected_value):
174
+ logger.debug(f"Input mismatch for '{key}': expected '{expected_value}', got '{actual_value}'")
175
+ return False
176
+
177
+ return True
178
+
179
+
180
+ def _get_parameter_validation_feedback(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> Dict[str, Any]:
181
+ """
182
+ 对源头节点的参数进行详细验证,返回验证反馈
183
+
184
+ 注意:不返回期望值(expected),避免泄漏答案
185
+
186
+ Args:
187
+ arguments: 实际调用时传入的参数
188
+ golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value)
189
+
190
+ Returns:
191
+ 包含验证结果的字典:
192
+ - all_correct: bool - 所有参数是否正确
193
+ - correct_params: List[str] - 正确的参数名列表
194
+ - incorrect_params: List[str] - 错误的参数名列表(不包含期望值)
195
+ """
196
+ if not golden_inputs:
197
+ return {
198
+ "all_correct": True,
199
+ "correct_params": [],
200
+ "incorrect_params": []
201
+ }
202
+
203
+ correct_params = []
204
+ incorrect_params = []
205
+
206
+ for key, actual_value in arguments.items():
207
+ # 只对用户实际提交的参数给反馈,未提交的参数不评价
208
+ if key not in golden_inputs:
209
+ continue # 该参数不在 golden 中,跳过(如 _golden_inputs 等内部参数)
210
+ expected_value = golden_inputs[key]
211
+ # 转换为字符串比较,避免类型问题(如 int vs str)
212
+ if str(actual_value) == str(expected_value):
213
+ correct_params.append(key)
214
+ else:
215
+ # 只记录参数名,不包含期望值,避免泄漏答案
216
+ incorrect_params.append(key)
217
+
218
+ # all_correct:用户提交的所有参数都正确,且覆盖了全部 golden 参数
219
+ all_provided_correct = len(incorrect_params) == 0
220
+ all_golden_covered = all(k in arguments for k in golden_inputs)
221
+ return {
222
+ "all_correct": all_provided_correct and all_golden_covered,
223
+ "correct_params": correct_params,
224
+ "incorrect_params": incorrect_params
225
+ }
226
+
227
+
228
+ def _is_source_node(node_id: str, scenario: GraphScenario) -> bool:
229
+ """
230
+ 判断节点是否是源头节点(完全没有任何入边的节点)
231
+
232
+ 源头节点定义:
233
+ - 没有任何类型的入边(包括 DATA、ITEM、HIDDEN_ITEM)
234
+ - 即没有任何上游节点
235
+
236
+ Args:
237
+ node_id: 节点ID
238
+ scenario: 场景对象
239
+
240
+ Returns:
241
+ True 表示是源头节点
242
+ """
243
+ for edge in scenario.edges:
244
+ if edge.target_id == node_id:
245
+ # 只要有任何入边,就不是源头节点
246
+ return False
247
+
248
+ return True
249
+
250
+
251
+ def _check_and_reveal_ready_nodes(scenario: GraphScenario, recent_outputs: Dict[str, Any], source_node_id: str) -> List[Dict[str, Any]]:
252
+ """
253
+ 检查并释放参数齐全的隐藏节点(渐进式暴露机制)
254
+
255
+ 核心逻辑:
256
+ 1. 维护"可见值集合":包含所有被测模型当前可以看到的值
257
+ - init_inputs 的值(初始可见)
258
+ - 工具执行后的实际输出值(运行时获得)
259
+ - 可见 Item 的输出值
260
+ 2. 检查隐藏节点:该节点的所有 golden_input 值是否都在可见值集合中
261
+ 3. 如果是,则释放该节点
262
+
263
+ Args:
264
+ scenario: 场景对象
265
+ recent_outputs: 最近执行的工具的输出
266
+ source_node_id: 刚执行的工具节点ID
267
+
268
+ Returns:
269
+ 新释放的节点列表
270
+ """
271
+ newly_revealed = []
272
+
273
+ # 构建"可见值集合"(Set of visible values)
274
+ # 存储格式:set of values (转为字符串)
275
+ visible_values = set()
276
+
277
+ # 1. 添加有意义的 init_inputs 值到可见值集合
278
+ # Item 的 init_inputs 不应该加入,因为它们在密室中完全用不到
279
+ for node_id, node in scenario.nodes.items():
280
+ # 跳过源头 Item 节点(没有入边的 Item)
281
+ if node.type == "Item":
282
+ has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges)
283
+ if not has_incoming_edge:
284
+ # 这是源头 Item,跳过其 init_inputs
285
+ continue
286
+
287
+ # 添加其他节点的 init_inputs
288
+ for port_name, init_value in node.init_input_values.items():
289
+ if init_value:
290
+ visible_values.add(str(init_value))
291
+
292
+ # 2. 添加已执行工具的所有历史输出值
293
+ for node_id, node in scenario.nodes.items():
294
+ if node.type == "Tool" and node.if_success and node.actual_outputs_history:
295
+ # 遍历所有历史执行记录
296
+ for output_dict in node.actual_outputs_history:
297
+ for output_port_name, output_value in output_dict.items():
298
+ if output_value:
299
+ visible_values.add(str(output_value))
300
+
301
+ # 3. 添加已被 investigate 的 Item 的 golden 输出值
302
+ # 注意:Item 可见不等于其输出值可见,需要 investigate 后才能获得
303
+ # 这里我们使用 actual_outputs_history 来标记 Item 是否已被 investigate
304
+ for node_id, node in scenario.nodes.items():
305
+ if node.type == "Item" and node.is_revealed and node.actual_outputs_history:
306
+ # Item 通常只会被 investigate 一次,但为了一致性也使用历史列表
307
+ for output_dict in node.actual_outputs_history:
308
+ for port_name, port_value in output_dict.items():
309
+ if port_value:
310
+ visible_values.add(str(port_value))
311
+
312
+ # 遍历所有隐藏的节点,检查其 golden_input 是否都在可见值集合中
313
+ for node_id, node in scenario.nodes.items():
314
+ # 跳过已可见的节点
315
+ if node.is_revealed:
316
+ continue
317
+
318
+ # 只检查工具节点(物品节点由 ITEM 输出触发)
319
+ if node.type != "Tool":
320
+ continue
321
+
322
+ # 检查该节点的所有 golden_input 值是否都在可见值集合中
323
+ all_inputs_ready = True
324
+ missing_values = []
325
+
326
+ for input_port_name, golden_input_value in node.golden_input_values.items():
327
+ # 检查这个 golden 值是否在可见值集合中
328
+ if str(golden_input_value) not in visible_values:
329
+ all_inputs_ready = False
330
+ missing_values.append(f"{input_port_name}={golden_input_value}")
331
+
332
+ # 如果所有 golden_input 值都在可见值集合中,释放该节点
333
+ if all_inputs_ready and len(node.golden_input_values) > 0:
334
+ logger.info(f"All golden inputs ready for {node_id}: {list(node.golden_input_values.values())}")
335
+
336
+ # 如果所有输入都齐全,释放该节点
337
+ if all_inputs_ready:
338
+ node.is_revealed = True
339
+
340
+ # 构建节点信息返回给模型
341
+ node_info = {
342
+ "id": node.id,
343
+ "type": node.type,
344
+ "can_investigate": True,
345
+ "hint": "This tool's input parameters are now complete, you can use investigate to view detailed information"
346
+ }
347
+
348
+ # if node.name:
349
+ # node_info["name"] = node.name
350
+ if node.description:
351
+ node_info["description"] = node.description
352
+
353
+ newly_revealed.append(node_info)
354
+ logger.info(f"Progressive reveal: {node_id} is now ready (all inputs satisfied)")
355
+
356
+ return newly_revealed
357
+
358
+
359
+ def _initialize_node_values(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]):
360
+ """
361
+ Initialize node state and load values from port value fields.
362
+ 应用渐进式暴露机制:初始时只显示参数齐全的节点(源头节点)
363
+
364
+ 重要区分:
365
+ 1. input_values: 只加载 metadata.initial_values 中的 init_inputs(真正的初始值)
366
+ 2. output_values: 加载 nodes[].outputs[].value(golden 输出,用于验证)
367
+ """
368
+ # 第一步:加载所有节点的值,并将所有节点初始设为隐藏
369
+ initial_values = metadata.get('initial_values', {})
370
+
371
+ for node_id, node in scenario.nodes.items():
372
+ # 忽略 initial_visible 字段,初始全部隐藏
373
+ # 由渐进式暴露机制根据参数齐全情况决定是否显示
374
+ node.is_revealed = False
375
+
376
+ if node.type == "Tool":
377
+ node.if_success = False
378
+ node.actual_outputs_history = [] # 清空历史输出
379
+ elif node.type == "Item":
380
+ node.if_success = False
381
+ node.actual_outputs_history = [] # 清空历史输出
382
+
383
+ # 从 JSON 加载值
384
+ if node_id in raw_nodes_data:
385
+ node_data = raw_nodes_data[node_id] # node_data是json文件中nodes中的字典
386
+
387
+ # 【重要】只加载 metadata.initial_values 中的初始输入值
388
+ if node_id in initial_values:
389
+ init_data = initial_values[node_id]
390
+ # 加载初始输入值(用于渐进式暴露判断)
391
+ for port_name, port_value in init_data.get('init_inputs', {}).items():
392
+ node.init_input_values[port_name] = port_value
393
+
394
+ # 【评测用】加载 golden 输入值(用于验证模型传入的参数是否正确)
395
+ for input_port_data in node_data.get('inputs', []):
396
+ if 'value' in input_port_data:
397
+ node.golden_input_values[input_port_data['name']] = input_port_data['value']
398
+
399
+ # 【评测用】加载 golden 输出值(用于验证工具调用是否正确,以及 Item 节点的 content)
400
+ for output_port_data in node_data.get('outputs', []):
401
+ if 'value' in output_port_data:
402
+ node.golden_output_values[output_port_data['name']] = output_port_data['value']
403
+
404
+ # For Items, set content from golden_output_values
405
+ if node.type == "Item" and node.golden_output_values:
406
+ # Item 的 content 是其第一个 golden 输出值
407
+ node.content = list(node.golden_output_values.values())[0]
408
+
409
+ # 第二步:应用渐进式暴露机制
410
+ # 检查所有节点,根据参数齐全情况释放源头节点(工具 + Item)
411
+ _apply_progressive_reveal_at_init(scenario)
412
+
413
+ def _build_node_info(node: Node, raw_nodes_data: Dict[str, Any]) -> Dict[str, Any]:
414
+ """
415
+ 构建节点信息(工具或物品)
416
+
417
+ Args:
418
+ node: 节点对象
419
+ raw_nodes_data: 原始节点数据(用于获取 template_id 等)
420
+
421
+ Returns:
422
+ 节点信息字典
423
+ """
424
+ if node.type == "Tool":
425
+ # 过滤掉输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口)
426
+ # 这些端口仅用于控制掉落机制,不应暴露给 Agent
427
+ # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到)
428
+ tool_info = {
429
+ "id": node.id,
430
+ # "name": node.name,
431
+ "description": node.description,
432
+ "type": "Tool",
433
+ "inputs": [{"name": p.name, "type": p.type, "description": p.description}
434
+ for p in node.inputs if p.type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]],
435
+ "outputs": [{"name": p.name, "type": p.type, "description": p.description}
436
+ for p in node.outputs]
437
+ }
438
+
439
+ # 添加 template_id(工具的标准名称)
440
+ if node.id in raw_nodes_data:
441
+ node_data = raw_nodes_data[node.id]
442
+ template_id = node_data.get('template_id')
443
+ if template_id:
444
+ tool_info['template_id'] = template_id
445
+
446
+ return tool_info
447
+
448
+ elif node.type == "Item":
449
+ return {
450
+ "id": node.id,
451
+ # "name": node.name,
452
+ "description": node.description,
453
+ "type": "Item"
454
+ }
455
+
456
+ else:
457
+ return {
458
+ "id": node.id,
459
+ # "name": node.name,
460
+ "type": node.type
461
+ }
462
+
463
+ def _get_initial_observation(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]) -> Dict[str, Any]:
464
+ """
465
+ Generate initial observation for the agent (what they see when entering the room).
466
+
467
+ 策略:
468
+ - Tools: 只显示名称和描述,不显示接口定义。需要 investigate 才能获得详细接口信息。
469
+ - Items: 只显示存在,不显示内容。需要 investigate 才能获得内容值。
470
+ - init_inputs: 作为"可用信息"告诉模型,这些是可以用作工具参数的初始值。
471
+ - init_outputs: 不告诉模型(这些是答案,需要模型通过调用工具获得)。
472
+ """
473
+ available_entities = [] # 统一的实体列表(Tools 和 Items)
474
+ available_information = [] # 可用的初始信息(来自 init_inputs)
475
+
476
+ # 从 metadata.initial_values 提取 init_inputs 作为可用信息
477
+ # 只提供值本身,不透露这些值对应哪个节点的哪个参数,让模型自己推理
478
+ # 注意:跳过源头 Item(没有入边的 Item)的 init_inputs,因为它们在密室中完全用不到
479
+ initial_values = metadata.get('initial_values', {})
480
+ # initial_values字段的格式
481
+ # "initial_values": {
482
+ # "terminal_1": {
483
+ # "init_inputs": {},
484
+ # "init_outputs": {
485
+ # "text_output": "System initialization complete.",
486
+ # "hex_output": "48656c6c6f20576f726c64",
487
+ # "item_dispenser": "掉落了一张纸条,上面写着“请勿随意触摸终端”"
488
+ # }
489
+ # }
490
+ # }
491
+ for node_id, init_data in initial_values.items():
492
+ # 获取节点信息,判断是否为源头 Item
493
+ node = scenario.nodes.get(node_id)
494
+ if node and node.type == "Item":
495
+ # 检查是否为源头 Item(没有入边)
496
+ has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges)
497
+ if not has_incoming_edge:
498
+ # 这是源头 Item,检查是否有 init_inputs
499
+ init_inputs = init_data.get('init_inputs', {})
500
+ if init_inputs:
501
+ # 有 init_inputs,需要暴露这些参数
502
+ for param_name, param_value in init_inputs.items():
503
+ available_information.append({
504
+ "value": param_value
505
+ })
506
+ # 处理完后跳过后续的通用逻辑
507
+ continue
508
+
509
+ init_inputs = init_data.get('init_inputs', {})
510
+ if init_inputs:
511
+ # 为每个 init_input 值创建一个信息条目(不包含 source_node 和 parameter 信息)
512
+ for param_name, param_value in init_inputs.items():
513
+ available_information.append({
514
+ "value": param_value
515
+ })
516
+
517
+ for node in scenario.nodes.values():
518
+ if node.is_revealed:
519
+ # Tools: 只显示基本信息,提示可以 investigate 查看详细接口
520
+ if node.type == "Tool":
521
+ tool_info = {
522
+ "id": node.id, # 这里只有id而没有template_id
523
+ "type": "Tool",
524
+ "can_investigate": True, # 可以被 investigate
525
+ "hint": "You can use investigate to view the tool's detailed interface information for calling"
526
+ }
527
+ # 只在 name 非空时添加
528
+ # if node.name:
529
+ # tool_info["name"] = node.name
530
+ # 只在 description 非空时添加
531
+ if node.description:
532
+ tool_info["description"] = node.description
533
+
534
+ available_entities.append(tool_info)
535
+
536
+ # Items: 只显示基本信息,提示可以 investigate 查看内容
537
+ elif node.type == "Item":
538
+ item_info = {
539
+ "id": node.id, # 这里只有id而没有template_id
540
+ "type": "Item",
541
+ "can_investigate": True, # 可以被 investigate
542
+ "hint": "You can use investigate to view the item's content"
543
+ }
544
+ # 只在 name 非空时添加
545
+ # if node.name:
546
+ # item_info["name"] = node.name
547
+ # 只在 description 非空时添加
548
+ if node.description:
549
+ item_info["description"] = node.description
550
+
551
+ available_entities.append(item_info)
552
+
553
+ return {
554
+ "narrative": scenario.intro_narrative,
555
+ "available_entities": available_entities, # 使用统一的实体列表
556
+ "available_information": available_information, # 可用的初始信息(只包含 init_inputs)
557
+ "win_node_id": scenario.win_node_id # 胜利节点ID,让模型知道需要关注哪个节点
558
+ }
559
+
560
+ @app.post("/env/reset")
561
+ def reset_case(case_id: str = None, case_file_path: str = None, session_id: str = None):
562
+ """Loads a specific case from file and resets it.
563
+
564
+ Args:
565
+ case_id: Optional case ID for resetting an existing case
566
+ case_file_path: Path to case file for loading a new case
567
+ session_id: Optional session ID to ensure isolation between concurrent evaluations
568
+ """
569
+ logger.info(f"Reset request - case_id: {case_id}, case_file_path: {case_file_path}, session_id: {session_id}")
570
+ STATS["case_loads"] += 1
571
+
572
+ if case_file_path:
573
+ if not os.path.exists(case_file_path):
574
+ logger.error(f"Case file not found: {case_file_path}")
575
+ raise HTTPException(status_code=404, detail=f"File not found: {case_file_path}")
576
+ try:
577
+ with open(case_file_path, "r", encoding="utf-8") as f:
578
+ file_data = json.load(f)
579
+
580
+ # 转换格式:从 DAG executor 生成的格式转换为 GraphScenario 格式
581
+ # 1. 提取 metadata
582
+ metadata = file_data.get('metadata', {})
583
+
584
+ # 2. 生成 case_id, title, intro_narrative
585
+ # 【修复】为每个评测会话生成唯一的 case_id,防止并发评测时状态污染
586
+ base_name = os.path.basename(case_file_path).replace('.json', '').replace('_full', '').replace('_full2', '')
587
+
588
+ if session_id:
589
+ # 如果提供了 session_id,使用它来确保唯一性
590
+ case_id = f"{base_name}_{session_id}"
591
+ else:
592
+ # 否则使用时间戳和随机数确保唯一性
593
+ unique_suffix = f"{int(time.time() * 1000)}_{random.randint(1000, 9999)}"
594
+ case_id = f"{base_name}_{unique_suffix}"
595
+
596
+ file_data['case_id'] = case_id
597
+ logger.info(f"Generated unique case_id: {case_id} (base: {base_name}, session: {session_id})")
598
+
599
+ if 'title' not in file_data:
600
+ file_data['title'] = f"Escape Room: {file_data['case_id']}"
601
+
602
+ if 'intro_narrative' not in file_data: # 目前的json文件中已经有了intro_narrative字段,不会使用下面一行的内容,而是使用每个评测问题的json文件中的对应字段
603
+ file_data['intro_narrative'] = 'You are trapped in a locked room. There may be tools and items in the environment - explore them and find a way to escape. You need to find a victory string to escape. When you obtain the victory string and submit it correctly, the system will clearly indicate: "🎉 Congratulations on successfully escaping the room! Your answer is correct: [your answer]".'
604
+
605
+ # 3. 转换 nodes 列表为字典(DAG executor 生成的文件中 nodes 是列表格式)
606
+ nodes_dict = {}
607
+ for node_data in file_data['nodes']:
608
+ nodes_dict[node_data['id']] = node_data # 这里的id是template_id之后可能添加一个后缀
609
+ file_data['nodes'] = nodes_dict # 把列表转成一个字典
610
+
611
+ # 4. 添加缺失的字段
612
+ if 'difficulty' not in file_data:
613
+ file_data['difficulty'] = metadata.get('total_nodes', 5)
614
+
615
+ if 'win_node_id' not in file_data:
616
+ file_data['win_node_id'] = metadata.get('win_node_id', '')
617
+
618
+ scenario = GraphScenario(**file_data)
619
+
620
+ # Extract raw nodes data for template_id access
621
+ # nodes 已经在上面转换为字典格式
622
+ raw_nodes_data = file_data.get('nodes', {})
623
+ RAW_NODES_DATA[scenario.case_id] = raw_nodes_data
624
+
625
+ # Store metadata for initial values access
626
+ FILE_METADATA[scenario.case_id] = metadata
627
+
628
+ logger.info(f"Successfully parsed case file: {scenario.case_id}, nodes: {len(scenario.nodes)}, edges: {len(scenario.edges)}")
629
+ except Exception as e:
630
+ logger.error(f"Failed to load case file: {str(e)}", exc_info=True)
631
+ raise HTTPException(status_code=500, detail=f"Failed to load case file: {str(e)}")
632
+
633
+ # Initialize node state and load values
634
+ _initialize_node_values(scenario, raw_nodes_data, metadata)
635
+
636
+ SCENARIOS[scenario.case_id] = scenario
637
+ simulator = ToolSimulator()
638
+ SIMULATORS[scenario.case_id] = simulator
639
+
640
+ logger.info(f"Case {scenario.case_id} initialized successfully - tools: {len([n for n in scenario.nodes.values() if n.type == 'Tool'])}, items: {len([n for n in scenario.nodes.values() if n.type == 'Item'])}")
641
+
642
+ # 生成初始观察信息(进入密室后看到的环境)
643
+ initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata)
644
+ '''
645
+ initial_observation的格式:
646
+ {
647
+ "narrative": scenario.intro_narrative,
648
+ "available_entities": available_entities # 使用统一的实体列表
649
+ "available_information": available_information # 可用的初始信息(只包含 init_inputs)
650
+ }
651
+ '''
652
+
653
+ return {
654
+ "ok": True,
655
+ "message": f"Case loaded from {case_file_path}",
656
+ "case_id": scenario.case_id,
657
+ **initial_observation # 直接展开初始观察信息
658
+ }
659
+
660
+ # 如果没有提供 case_file_path,但提供了 case_id,则尝试从内存重置
661
+ if case_id and case_id in SCENARIOS:
662
+ scenario = SCENARIOS[case_id]
663
+ raw_nodes_data = RAW_NODES_DATA.get(case_id, {})
664
+ metadata = FILE_METADATA.get(case_id, {})
665
+
666
+ # Reset dynamic fields and re-apply progressive reveal
667
+ # 重新初始化节点状态(包括渐进式暴露)
668
+ _initialize_node_values(scenario, raw_nodes_data, metadata)
669
+
670
+ logger.info(f"Case {case_id} reset - tools: {len([n for n in scenario.nodes.values() if n.type == 'Tool'])}, items: {len([n for n in scenario.nodes.values() if n.type == 'Item'])}")
671
+
672
+ # 生成初始观察信息
673
+ initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata)
674
+
675
+ return {
676
+ "ok": True,
677
+ "message": f"Case {case_id} reset.",
678
+ "case_id": case_id,
679
+ **initial_observation # 直接展开初始观察信息
680
+ }
681
+
682
+ # 如果既没有 case_file_path,也没有在内存中找到,返回错误
683
+ raise HTTPException(
684
+ status_code=400,
685
+ detail="Must provide case_file_path to load a new case, or use case_id to reset an existing case."
686
+ )
687
+
688
+ class InvestigateRequest(BaseModel):
689
+ node_id: str
690
+
691
+ @app.post("/env/{case_id}/investigate")
692
+ def investigate(case_id: str, req: InvestigateRequest):
693
+ """
694
+ Investigates a Tool or Item to reveal detailed information.
695
+
696
+ - For Tools: Returns detailed interface information (inputs/outputs) needed to call the tool
697
+ - For Items: Returns content value and triggers hidden item drops
698
+ """
699
+ logger.info(f"Investigate request - case_id: {case_id}, node_id: {req.node_id}")
700
+ STATS["investigates"][case_id] += 1
701
+
702
+ if case_id not in SCENARIOS:
703
+ logger.error(f"Case not found: {case_id}")
704
+ raise HTTPException(status_code=404, detail="Case not found")
705
+
706
+ scenario = SCENARIOS[case_id]
707
+ if req.node_id not in scenario.nodes:
708
+ logger.error(f"Node not found: {req.node_id} in case {case_id}")
709
+ raise HTTPException(status_code=404, detail="Node not found")
710
+
711
+ node = scenario.nodes[req.node_id]
712
+
713
+ if not node.is_revealed:
714
+ logger.warning(f"Attempt to investigate hidden node: {req.node_id}")
715
+ return {"ok": False, "error": "Node is not visible yet."}
716
+
717
+ raw_nodes_data = RAW_NODES_DATA.get(case_id, {})
718
+ newly_revealed = []
719
+
720
+ # 处理 Tool 的 investigate
721
+ if node.type == "Tool":
722
+ logger.info(f"Investigating tool: {req.node_id}")
723
+
724
+ # 返回工具的详细接口信息
725
+ # id 字段使用 node.id(节点唯一标识),agent 用这个字段识别和调用具体的节点
726
+ # template_id 是工具类型标识符,Agent 内部用于判断工具特性(如 terminal 类工具参数可选)
727
+ # 注意:只过滤输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口),这些端口仅用于控制掉落,不应暴露给 Agent
728
+ # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到)
729
+ # 【端口上游依赖提示 & 初始值直接给出】
730
+ # 针对参数语义模糊(全为数字类型)的工具,在 investigate 返回信息中标注
731
+ # 哪个输入端口来自哪个上游节点(upstream_from)。
732
+ # 对于所有工具:若该节点不是纯源头节点(有任意数据流入边),
733
+ # 且某个端口没有上游入边(值来自初始可见参数),则直接给出该端口的 golden input 值。
734
+ AMBIGUOUS_TOOLS = {
735
+ "num_base_convert", "calc_modexp", "calc_modexp_int",
736
+ "calc_inv_mod", "calc_inv_mod_int", "crypto_rsa_decrypt_hex", "geo_haversine"
737
+ }
738
+ # Terminal 类工具自带参数对错反馈机制,玩家/模型可自行试错,
739
+ # 无需在 investigate 时直接暴露 init_value
740
+ SELF_FEEDBACK_TOOLS = {
741
+ "terminal_1", "terminal_2",
742
+ "Logic Terminal", "Math Terminal", "Encryption Terminal", "Sequence Terminal"
743
+ }
744
+ _template_id_for_hint = raw_nodes_data.get(node.id, {}).get("template_id", "")
745
+ # 构建数据流入边映射(对所有工具):{target_port -> (source_node_id, source_port)}
746
+ _upstream_map = {}
747
+ for _edge in scenario.edges:
748
+ if (_edge.target_id == node.id
749
+ and _edge.connection_type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]
750
+ and _edge.target_port is not None):
751
+ _upstream_map[_edge.target_port] = (_edge.source_id, _edge.source_port)
752
+ # 判断该节点是否有任意数据流入边(即不是纯源头节点)
753
+ _has_any_upstream = len(_upstream_map) > 0
754
+ # 判断该节点是否有任意入边(包括 ITEM/HIDDEN_ITEM 掉落边)
755
+ # 有任意入边(含掉落边)但无数据流入边的节点,其输入来自初始可见参数,应直接给出
756
+ _has_any_edge = any(_edge.target_id == node.id for _edge in scenario.edges)
757
+ # 构建 inputs 列表
758
+ _inputs_list = []
759
+ for p in node.inputs:
760
+ if p.type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]:
761
+ continue
762
+ port_dict = {"name": p.name, "type": p.type, "description": p.description}
763
+ if p.name in _upstream_map:
764
+ # 该端口有上游数据流依赖,且属于语义模糊工具 → 标注来源
765
+ if _template_id_for_hint in AMBIGUOUS_TOOLS:
766
+ src_node_id, src_port = _upstream_map[p.name]
767
+ port_dict["upstream_from"] = f"{src_node_id}.{src_port}" if src_port else src_node_id
768
+ elif _has_any_edge and _template_id_for_hint not in SELF_FEEDBACK_TOOLS:
769
+ # 该节点有任意入边,但此端口没有数据流入边 → 值来自初始可见参数,直接给出
770
+ # 排除自带反馈机制的 terminal 类工具(它们通过执行结果反馈对错,无需提前暴露参数值)
771
+ golden_val = node.golden_input_values.get(p.name)
772
+ if golden_val is not None:
773
+ port_dict["init_value"] = golden_val
774
+ _inputs_list.append(port_dict)
775
+
776
+ tool_details = {
777
+ "id": node.id, # 节点 ID,用于唯一标识和调用这个具体节点
778
+ "type": "Tool",
779
+ "inputs": _inputs_list,
780
+ "outputs": [{"name": p.name, "type": p.type, "description": p.description}
781
+ for p in node.outputs]
782
+ }
783
+
784
+ # 添加 template_id 用于 Agent 内部判断工具类型(不会展示给被测模型)
785
+ if node.id in raw_nodes_data:
786
+ template_id = raw_nodes_data[node.id].get('template_id')
787
+ if template_id:
788
+ tool_details["_template_id"] = template_id # 使用下划线前缀标记为内部字段
789
+
790
+ # 只在 name 非空时添加
791
+ # if node.name:
792
+ # tool_details["name"] = node.name
793
+ # 只在 description 非空时添加
794
+ if node.description:
795
+ tool_details["description"] = node.description
796
+
797
+ # 添加 narrative 字段(如果存在)
798
+ if node.id in raw_nodes_data:
799
+ narrative = raw_nodes_data[node.id].get('narrative')
800
+ if narrative:
801
+ tool_details['narrative'] = narrative
802
+
803
+ # 不再返回 init_values,避免泄漏答案
804
+ # investigate 只应该返回工具的接口定义,不应该暴露初始值
805
+
806
+ # 【新增】检查该 Tool 是否有待触发的 HIDDEN_ITEM 掉落
807
+ # 如果该工具已按照 golden_input 正确执行,且有 HIDDEN_ITEM 输出边,则触发掉落
808
+ if node.has_hidden_item_ready:
809
+ logger.info(f"Tool has HIDDEN_ITEM ready - triggering passive drop for: {req.node_id}")
810
+
811
+ # 遍历该工具的所有 HIDDEN_ITEM 输出边
812
+ for edge in scenario.edges:
813
+ if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM:
814
+ target_node = scenario.nodes[edge.target_id]
815
+
816
+ if not target_node.is_revealed:
817
+ target_node.is_revealed = True
818
+ # 构建基本节点信息(不包含详细内容)
819
+ node_info = {
820
+ "id": target_node.id,
821
+ "type": target_node.type,
822
+ "can_investigate": True,
823
+ "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content"
824
+ }
825
+ # 只在 name 非空时添加
826
+ # if target_node.name:
827
+ # node_info["name"] = target_node.name
828
+ # 只在 description 非空时添加
829
+ if target_node.description:
830
+ node_info["description"] = target_node.description
831
+
832
+ newly_revealed.append(node_info)
833
+ logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)")
834
+
835
+ # 重置标志,已经触发过了,避免重复
836
+ node.has_hidden_item_ready = False
837
+
838
+ logger.info(f"Tool investigation successful - node: {req.node_id}, revealed: {len(newly_revealed)}")
839
+
840
+ # 构建返回结果
841
+ result = {
842
+ "ok": True,
843
+ "entity_type": "Tool",
844
+ "details": tool_details
845
+ }
846
+
847
+ # 如果有新掉落的节点,添加到响应中
848
+ if newly_revealed:
849
+ result["newly_revealed"] = newly_revealed
850
+
851
+ return result
852
+
853
+ # 处理 Item 的 investigate
854
+ elif node.type == "Item":
855
+ logger.info(f"Investigating item: {req.node_id}")
856
+
857
+ # 【第一步】检查该 Item 是否有需要参数的输入端口
858
+ # 如果有,且尚未通过 use_item 验证,则不返回内容,只返回参数要求
859
+ required_inputs = []
860
+ if node.id in raw_nodes_data:
861
+ raw_node = raw_nodes_data[node.id]
862
+ inputs_info = raw_node.get('inputs', [])
863
+ required_inputs = [
864
+ {
865
+ "name": inp.get("name"),
866
+ "type": inp.get("type"),
867
+ "description": inp.get("description", "")
868
+ }
869
+ for inp in inputs_info
870
+ if inp.get("type") not in ["Item", "Hidden_Item"]
871
+ ]
872
+
873
+ # 如果有 required_inputs 且尚未通过 use_item 验证(if_success == False)
874
+ # 则不返回内容,只返回参数要求提示
875
+ if required_inputs and not node.if_success:
876
+ logger.info(f"Item has required inputs and not yet unlocked: {req.node_id}")
877
+ result = {
878
+ "ok": True,
879
+ "entity_type": "Item",
880
+ "required_inputs": required_inputs
881
+ }
882
+
883
+ # 添加 narrative
884
+ if node.id in raw_nodes_data:
885
+ raw_node = raw_nodes_data[node.id]
886
+ narrative = raw_node.get('narrative')
887
+ if narrative:
888
+ result['narrative'] = narrative
889
+
890
+ param_names = ', '.join([inp['name'] for inp in required_inputs])
891
+ result["hint"] = f"This item requires parameters to unlock. Use the use_item operation with the following exact parameter names (do not change or translate): {param_names}"
892
+
893
+ return result
894
+
895
+ # 【新增】如果有 required_inputs 且已经通过 use_item 验证(if_success == True)
896
+ # 则返回提示:该节点已经被成功解决
897
+ if required_inputs and node.if_success:
898
+ logger.info(f"Item has required inputs and already unlocked: {req.node_id}")
899
+ result = {
900
+ "ok": True,
901
+ "entity_type": "Item",
902
+ "message": "This item has already been successfully unlocked by you."
903
+ }
904
+ return result
905
+
906
+ # 【第二步】该 Item 没有 required_inputs 或已通过验证,返回内容
907
+ # 1. 返回 Item 的 golden_output_values(即 Item 的内容)
908
+ # 注意:某些 Item 仅用于触发 HIDDEN_ITEM 掉落,没有实际内容
909
+ has_actual_content = bool(node.golden_output_values) or node.content is not None
910
+ content = node.golden_output_values if node.golden_output_values else node.content
911
+
912
+ # 【关键】将 golden_output_values 追加到 actual_outputs_history,标记该 Item 已被 investigate
913
+ # 这样在渐进式暴露时,这些值才会被加入可见值集合
914
+ # 即使是空字典(仅触发 HIDDEN_ITEM 的 Item),也要记录,以便渐进式暴露逻辑知道该 Item 已被调查
915
+ if node.golden_output_values is not None:
916
+ node.actual_outputs_history.append(dict(node.golden_output_values))
917
+
918
+ # 2. Trigger Hidden Item Drops (Passive Drop)
919
+ for edge in scenario.edges:
920
+ if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM:
921
+ target_node = scenario.nodes[edge.target_id]
922
+ if not target_node.is_revealed:
923
+ target_node.is_revealed = True
924
+ # 构建基本节点信息(不包含详细内容)
925
+ node_info = {
926
+ "id": target_node.id,
927
+ "type": target_node.type,
928
+ "can_investigate": True,
929
+ "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content"
930
+ }
931
+ # 只在 name 非空时添加
932
+ # if target_node.name:
933
+ # node_info["name"] = target_node.name
934
+ # 只在 description 非空时添加
935
+ if target_node.description:
936
+ node_info["description"] = target_node.description
937
+
938
+ newly_revealed.append(node_info)
939
+ logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)")
940
+
941
+ logger.info(f"Item investigation successful - node: {req.node_id}, has_content: {has_actual_content}, revealed: {len(newly_revealed)}")
942
+
943
+ # 【渐进式暴露】旧机制(基于 golden_input)已禁用
944
+ # 现在完全由 ITEM/HIDDEN_ITEM 边触发控制节点可见性
945
+ # 上面的 HIDDEN_ITEM 掉落逻辑已经处理了节点释放
946
+ # progressive_revealed = _check_and_reveal_ready_nodes(scenario, node.golden_output_values or {}, node.id)
947
+ # if progressive_revealed:
948
+ # # 合并到 newly_revealed 中
949
+ # if newly_revealed:
950
+ # newly_revealed.extend(progressive_revealed)
951
+ # else:
952
+ # newly_revealed = progressive_revealed
953
+ # logger.info(f"Progressive reveal after Item investigate: {len(progressive_revealed)} nodes now ready")
954
+
955
+ # 构建返回结果
956
+ result = {
957
+ "ok": True,
958
+ "entity_type": "Item"
959
+ }
960
+
961
+ # 只在有实际内容时才添加 content 字段
962
+ # 对于仅触发 HIDDEN_ITEM 掉落的 Item,不返回 content 字段,避免返回 None 或空字典让模型困惑
963
+ if has_actual_content:
964
+ result["content"] = content
965
+
966
+ # 添加 narrative
967
+ if node.id in raw_nodes_data:
968
+ raw_node = raw_nodes_data[node.id]
969
+ narrative = raw_node.get('narrative')
970
+ if narrative:
971
+ result['narrative'] = narrative
972
+
973
+ if newly_revealed:
974
+ result["newly_revealed"] = newly_revealed
975
+
976
+ # 不再主动提示胜利字符串,让模型自己判断
977
+ # 模型通过 investigate 获得内容后,需要自己识别这是否是胜利字符串
978
+
979
+ return result
980
+
981
+ else:
982
+ logger.warning(f"Attempt to investigate unknown node type: {req.node_id} (type: {node.type})")
983
+ return {"ok": False, "error": f"Cannot investigate node type: {node.type}"}
984
+
985
+ class ToolCallRequest(BaseModel):
986
+ node_id: str # 使用 node_id 精确指定要调用的节点
987
+ arguments: Dict[str, Any]
988
+
989
+ @app.post("/env/{case_id}/tool_call")
990
+ def tool_call(case_id: str, req: ToolCallRequest):
991
+ """Executes a tool and triggers item drops."""
992
+ logger.info(f"Tool call request - case_id: {case_id}, node_id: {req.node_id}, args: {list(req.arguments.keys())}")
993
+ STATS["tool_calls"][case_id] += 1
994
+
995
+ if case_id not in SCENARIOS:
996
+ logger.error(f"Case not found: {case_id}")
997
+ raise HTTPException(status_code=404, detail="Case not found")
998
+
999
+ scenario = SCENARIOS[case_id]
1000
+ raw_nodes_data = RAW_NODES_DATA.get(case_id, {})
1001
+
1002
+ # 通过 node_id 精确查找节点
1003
+ node_id = req.node_id
1004
+ if node_id not in scenario.nodes:
1005
+ logger.error(f"Node not found: {node_id} in case {case_id}")
1006
+ raise HTTPException(status_code=404, detail="Node not found")
1007
+
1008
+ tool_node = scenario.nodes[node_id]
1009
+
1010
+ if not tool_node:
1011
+ logger.error(f"Tool not found: {node_id} in case {case_id}")
1012
+ raise HTTPException(status_code=404, detail="Tool not found")
1013
+
1014
+ if not tool_node.is_revealed:
1015
+ logger.warning(f"Attempt to call hidden tool: {node_id}")
1016
+ return {"ok": False, "error": "Tool is not visible yet."}
1017
+
1018
+ if tool_node.type != "Tool":
1019
+ logger.warning(f"Attempt to call non-tool node: {node_id} (type: {tool_node.type})")
1020
+ return {"ok": False, "error": "Only tools can be called."}
1021
+
1022
+ # 1. Execute Tool (Real Execution via Simulator)
1023
+ simulator = SIMULATORS[case_id]
1024
+
1025
+ # Get tool name from template_id if available, otherwise use node name
1026
+ tool_name = tool_node.name
1027
+ if case_id in RAW_NODES_DATA and node_id in RAW_NODES_DATA[case_id]:
1028
+ template_id = RAW_NODES_DATA[case_id][node_id].get('template_id')
1029
+ if template_id:
1030
+ tool_name = template_id
1031
+
1032
+ # 文件处理工具和 Terminal 需要验证输入并返回预先计算的输出
1033
+ # 传递节点的实际输入输出值(从 DAG 执行后填充的数据)
1034
+ tool_arguments = dict(req.arguments) # Make a copy
1035
+
1036
+ # 传递节点的 golden values(从 JSON 的 inputs[].value 和 outputs[].value 加载)
1037
+ # 用于在评测阶段验证被测模型传入的参数是否正确
1038
+ if tool_node.golden_input_values:
1039
+ tool_arguments['_golden_inputs'] = tool_node.golden_input_values
1040
+ if tool_node.golden_output_values:
1041
+ tool_arguments['_golden_outputs'] = tool_node.golden_output_values
1042
+
1043
+ logger.debug(f"Executing tool {tool_name} (node: {tool_node.name}) with args {tool_arguments}")
1044
+
1045
+ try:
1046
+ output_values = simulator.execute(tool_name, tool_arguments)
1047
+ logger.info(f"Tool invoked - {tool_name}: {list(output_values.keys())}")
1048
+ except Exception as e:
1049
+ logger.error(f"Tool execution failed - {tool_name}: {str(e)}", exc_info=True)
1050
+ return {"ok": False, "error": f"Tool execution failed: {str(e)}"}
1051
+
1052
+ # 检查验证结果(精细化错误反馈)
1053
+ validation = output_values.pop("_validation", {"valid": True})
1054
+
1055
+ if not validation["valid"]:
1056
+ # 根据错误类型构造友好的错误消息
1057
+ error_type = validation.get("error_type")
1058
+
1059
+ if error_type == "missing_required":
1060
+ missing = validation.get("missing_params", [])
1061
+ error_msg = f"Error: Missing required parameters {', '.join(missing)}"
1062
+
1063
+ elif error_type == "type_error":
1064
+ param = validation.get("param_name")
1065
+ message = validation.get("message", "Parameter type error")
1066
+ error_msg = f"Error: {message}"
1067
+
1068
+ elif error_type == "incomplete_optional":
1069
+ provided = validation.get("provided_params", [])
1070
+ missing = validation.get("missing_params", [])
1071
+ error_msg = (
1072
+ f"Hint: You provided some parameters ({', '.join(provided)}), "
1073
+ f"but may also need: {', '.join(missing)}.\n"
1074
+ f"Trying to provide these parameters together might yield better results."
1075
+ )
1076
+
1077
+ elif error_type == "value_mismatch":
1078
+ param = validation.get("param_name")
1079
+ hint = validation.get("hint", "Parameter value may be incorrect")
1080
+ error_msg = f"Hint: {hint}.\nPlease check if this parameter value meets the requirements."
1081
+
1082
+ else:
1083
+ error_msg = validation.get("hint") or validation.get("message", "Parameter validation failed")
1084
+
1085
+ logger.info(f"Tool validation failed - {tool_name}: {error_type}")
1086
+ return {
1087
+ "ok": False,
1088
+ "error": error_msg,
1089
+ "error_type": error_type
1090
+ }
1091
+
1092
+ # Simulate success
1093
+ tool_node.if_success = True
1094
+
1095
+ # 【关键】将本次执行的输出值追加到历史列表(用于渐进式暴露判断)
1096
+ # 每次调用都会记录,不会覆盖之前的执行结果
1097
+ tool_node.actual_outputs_history.append(dict(output_values))
1098
+
1099
+ # 2. 检查是否应该触发掉落(只有输入参数正确时才掉落)
1100
+ # 验证输入参数是否与 golden_input_values 匹配
1101
+ inputs_match_golden = _check_inputs_match_golden(req.arguments, tool_node.golden_input_values)
1102
+
1103
+ newly_revealed = []
1104
+ investigate_hints = [] # 提示模型哪些节点可以 investigate 来发现隐藏内容
1105
+
1106
+ if inputs_match_golden:
1107
+ logger.info(f"✓ Tool inputs match golden - node: {node_id}, triggering drops")
1108
+
1109
+ # 检查该工具是否有 ITEM 或 HIDDEN_ITEM 输出边
1110
+ for edge in scenario.edges:
1111
+ if edge.source_id == tool_node.id:
1112
+ target_node = scenario.nodes[edge.target_id]
1113
+
1114
+ # ITEM 边:立即掉落(主动掉落)
1115
+ if edge.connection_type == InterfaceType.ITEM:
1116
+ if not target_node.is_revealed:
1117
+ target_node.is_revealed = True
1118
+ # 构建基本节点信息(不包含详细内容)
1119
+ node_info = {
1120
+ "id": target_node.id,
1121
+ "type": target_node.type,
1122
+ "can_investigate": True,
1123
+ "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content"
1124
+ }
1125
+ # 只在 name 非空时添加
1126
+ # if target_node.name:
1127
+ # node_info["name"] = target_node.name
1128
+ # 只在 description 非空时添加
1129
+ if target_node.description:
1130
+ node_info["description"] = target_node.description
1131
+
1132
+ newly_revealed.append(node_info)
1133
+ logger.info(f"ITEM drop triggered: {target_node.id} (from {node_id})")
1134
+
1135
+ # HIDDEN_ITEM 边:不立即掉落,标记并提示(被动掉落)
1136
+ elif edge.connection_type == InterfaceType.HIDDEN_ITEM:
1137
+ # 标记该工具有待触发的 HIDDEN_ITEM 掉落
1138
+ tool_node.has_hidden_item_ready = True
1139
+
1140
+ # 提示模型可以 investigate 这个工具来发现隐藏内容
1141
+ hint_info = {
1142
+ "tool_id": tool_node.id,
1143
+ "hint": f"Tool '{tool_node.id}' seems to hide something, try investigating it to discover more information"
1144
+ }
1145
+ # if tool_node.name:
1146
+ # hint_info["tool_name"] = tool_node.name
1147
+
1148
+ investigate_hints.append(hint_info)
1149
+ logger.info(f"HIDDEN_ITEM ready: {tool_node.id} -> {target_node.id} (will drop on investigate)")
1150
+ else:
1151
+ logger.info(f"✗ Tool inputs do NOT match golden - node: {node_id}, no drops triggered")
1152
+
1153
+ response = {
1154
+ "ok": True,
1155
+ "message": "Tool invoked",
1156
+ "output_values": output_values # Return raw outputs to Agent
1157
+ }
1158
+
1159
+ # 【新增】对源头节点进行参数验证反馈
1160
+ # 源头节点:没有数据流入边的节点,这些节点的参数需要模型自己推理
1161
+ # 验证模型使用的参数是否正确,并提供明确的反馈
1162
+ if _is_source_node(node_id, scenario) and tool_node.golden_input_values:
1163
+ validation_feedback = _get_parameter_validation_feedback(req.arguments, tool_node.golden_input_values)
1164
+
1165
+ if validation_feedback["all_correct"]:
1166
+ # 用户提交了全部 golden 参数且全部正确
1167
+ response["parameter_feedback"] = {
1168
+ "status": "correct",
1169
+ "message": f"✓ All parameters are correct! This tool has been successfully solved. You can now proceed to explore downstream nodes that depend on this tool's output."
1170
+ }
1171
+ logger.info(f"✓ Source node parameters all correct - node: {node_id}")
1172
+ elif validation_feedback["incorrect_params"]:
1173
+ # 有提交了但值错误的参数,只对这些参数给出反馈
1174
+ incorrect_list = []
1175
+ for param_name in validation_feedback["incorrect_params"]:
1176
+ incorrect_list.append(f" - Parameter '{param_name}' is incorrect")
1177
+
1178
+ correct_info = ""
1179
+ if validation_feedback["correct_params"]:
1180
+ correct_info = f"\n✓ Correct parameters: {', '.join(validation_feedback['correct_params'])}"
1181
+
1182
+ response["parameter_feedback"] = {
1183
+ "status": "incorrect",
1184
+ "message": (
1185
+ f"⚠️ Some parameters are incorrect:\n" +
1186
+ "\n".join(incorrect_list) +
1187
+ correct_info +
1188
+ f"\n\nHint: This is a source node. You need to reason about the correct parameter values from the available parameters. Please try using different parameter values."
1189
+ ),
1190
+ "incorrect_params": validation_feedback["incorrect_params"],
1191
+ "correct_params": validation_feedback["correct_params"]
1192
+ }
1193
+ logger.info(f"✗ Source node parameters incorrect - node: {node_id}, incorrect: {validation_feedback['incorrect_params']}")
1194
+ # else: 部分提交且全部正确 → 不给任何 parameter_feedback,避免对未提交的参数发表意见
1195
+
1196
+ # 检查工具调用是否完全正确(输出与 golden outputs 匹配)
1197
+ # 用于给模型正向反馈,让它知道这个工具已经正确调用过,避免重复调用
1198
+ # 注意:只有当输出完全匹配时才标记为 correct,不会在错误时提供具体错误信息
1199
+ # if tool_node.golden_output_values and output_values:
1200
+ # is_correct = True
1201
+ # for port_name, expected_value in tool_node.golden_output_values.items():
1202
+ # actual_value = output_values.get(port_name)
1203
+ # if str(actual_value) != str(expected_value):
1204
+ # is_correct = False
1205
+ # break
1206
+
1207
+ # if is_correct:
1208
+ # response["tool_call_correct"] = True
1209
+ # logger.info(f"✓ Tool called with correct result - node: {node_id}")
1210
+
1211
+ # 只在有新内容掉落时才返回 newly_revealed
1212
+ if newly_revealed:
1213
+ response["newly_revealed"] = newly_revealed
1214
+
1215
+ # 添加 investigate 提示(对于有待触发 HIDDEN_ITEM 掉落的工具)
1216
+ if investigate_hints:
1217
+ response["investigate_hints"] = investigate_hints
1218
+
1219
+ # 3. 渐进式暴露机制 - 现在完全由 ITEM/HIDDEN_ITEM 边控制
1220
+ # 旧机制(基于 golden_input 检查)已被禁用
1221
+ # 新机制中,节点的可见性只由 ITEM/HIDDEN_ITEM 边触发决定
1222
+ # 上面的 ITEM/HIDDEN_ITEM 掉落逻辑已经处理了节点释放
1223
+ # progressive_revealed = _check_and_reveal_ready_nodes(scenario, output_values, tool_node.id)
1224
+ # if progressive_revealed:
1225
+ # # 合并到 newly_revealed 中
1226
+ # if newly_revealed:
1227
+ # newly_revealed.extend(progressive_revealed)
1228
+ # else:
1229
+ # newly_revealed = progressive_revealed
1230
+ # response["newly_revealed"] = newly_revealed
1231
+ # logger.info(f"Progressive reveal: {len(progressive_revealed)} nodes now ready")
1232
+
1233
+ # Check if this is the win node
1234
+ if node_id == scenario.win_node_id:
1235
+ # 验证输出值是否等于预期的胜利值
1236
+ # 从节点的 golden_output_values 中获取预期值(在 _initialize_node_values 时从 JSON 加载)
1237
+ expected_outputs = tool_node.golden_output_values
1238
+
1239
+ # 检查实际输出是否与预期输出匹配
1240
+ is_correct = False
1241
+ victory_string = None
1242
+ mismatch_info = []
1243
+
1244
+ if expected_outputs and output_values:
1245
+ # 检查每个预期输出端口的值是否匹配
1246
+ is_correct = True
1247
+ for port_name, expected_value in expected_outputs.items():
1248
+ actual_value = output_values.get(port_name)
1249
+ if actual_value != expected_value:
1250
+ is_correct = False
1251
+ mismatch_info.append(f"Port '{port_name}': expected '{expected_value}', actual '{actual_value}'")
1252
+ logger.warning(f"Win node output mismatch - port: {port_name}, expected: {expected_value}, actual: {actual_value}")
1253
+
1254
+ # 如果所有输出都匹配,使用第一个输出作为胜利字符串
1255
+ if is_correct and output_values:
1256
+ victory_string = list(output_values.values())[0]
1257
+ else:
1258
+ logger.warning(f"Win node called but missing output values - expected: {expected_outputs}, actual: {output_values}")
1259
+
1260
+ # 不再主动提示胜利字符串,让模型自己判断
1261
+ # 模型调用工具获得输出后,需要自己识别这是否是胜利字符串并提交
1262
+ if is_correct:
1263
+ logger.info(f"🎯 Win node called with correct output - case: {case_id}, node: {node_id}, victory: {victory_string}")
1264
+ else:
1265
+ logger.info(f"❌ Win node called with incorrect output - case: {case_id}, node: {node_id}")
1266
+
1267
+ return response
1268
+
1269
+ class UseItemRequest(BaseModel):
1270
+ node_id: str = Field(..., description="The ID of the Item node to use (must be Item type)")
1271
+ arguments: Dict[str, Any] = Field(default_factory=dict, description="Input arguments to provide to the item")
1272
+
1273
+ @app.post("/env/{case_id}/use_item")
1274
+ def use_item(case_id: str, req: UseItemRequest):
1275
+ """
1276
+ Use an Item node by providing input arguments.
1277
+
1278
+ This is specifically for Item nodes that require parameters to be "unlocked" or "activated",
1279
+ such as containers that need a password/fingerprint.
1280
+
1281
+ - Validates that the node is of type Item
1282
+ - Checks if provided arguments match the item's golden_input_values
1283
+ - If match: triggers ITEM-type edge drops and returns the item's content
1284
+ - If not match: returns error message
1285
+ """
1286
+ logger.info(f"Use item request - case_id: {case_id}, node_id: {req.node_id}, args: {req.arguments}")
1287
+ STATS["use_items"][case_id] += 1
1288
+
1289
+ if case_id not in SCENARIOS:
1290
+ logger.error(f"Case not found: {case_id}")
1291
+ raise HTTPException(status_code=404, detail="Case not found")
1292
+
1293
+ scenario = SCENARIOS[case_id]
1294
+ if req.node_id not in scenario.nodes:
1295
+ logger.error(f"Node not found: {req.node_id} in case {case_id}")
1296
+ raise HTTPException(status_code=404, detail="Node not found")
1297
+
1298
+ item_node = scenario.nodes[req.node_id]
1299
+
1300
+ if not item_node.is_revealed:
1301
+ logger.warning(f"Attempt to use hidden item: {req.node_id}")
1302
+ return {"ok": False, "error": "Item is not visible yet."}
1303
+
1304
+ if item_node.type != "Item":
1305
+ logger.warning(f"Attempt to use non-item node: {req.node_id} (type: {item_node.type})")
1306
+ return {"ok": False, "error": "Only Item nodes can be used with use_item. Tools should be called with tool_call."}
1307
+
1308
+ # 【新增】检查该 Item 是否已经被成功解锁
1309
+ # 如果已经被正确使用过,直接返回成功提示
1310
+ if item_node.if_success:
1311
+ logger.info(f"Item already unlocked, returning success message: {req.node_id}")
1312
+ return {
1313
+ "ok": True,
1314
+ "message": "This item has already been successfully unlocked by you."
1315
+ }
1316
+
1317
+ # 检查该 Item 是否真的需要通过 use_item 提供参数
1318
+ # 只有当 Item 有非 Item/Hidden_Item 类型的输入时,才应该使用 use_item
1319
+ raw_nodes_data = RAW_NODES_DATA.get(case_id, {})
1320
+ if req.node_id in raw_nodes_data:
1321
+ raw_node = raw_nodes_data[req.node_id]
1322
+ inputs_info = raw_node.get('inputs', [])
1323
+ non_hidden_inputs = [
1324
+ inp for inp in inputs_info
1325
+ if inp.get("type") not in ["Item", "Hidden_Item"]
1326
+ ]
1327
+
1328
+ if not non_hidden_inputs:
1329
+ # 该 Item 不需要参数,应该只使用 investigate
1330
+ logger.warning(f"Attempt to use_item on a node that doesn't require parameters: {req.node_id}")
1331
+ return {
1332
+ "ok": False,
1333
+ "error": "This item does not require parameters. Please use investigate to examine the item directly."
1334
+ }
1335
+
1336
+ # 验证输入参数是否与 golden_input_values 匹配
1337
+ inputs_match_golden = _check_inputs_match_golden(req.arguments, item_node.golden_input_values)
1338
+
1339
+ if not inputs_match_golden:
1340
+ logger.info(f"✗ Item inputs do NOT match golden - node: {req.node_id}")
1341
+ # 提供更详细的错误信息,帮助 Agent 理解问题
1342
+ # 只显示非 Item/Hidden_Item 类型的参数(Hidden_Item 由系统自动处理)
1343
+ expected_params = []
1344
+ if req.node_id in raw_nodes_data:
1345
+ raw_node = raw_nodes_data[req.node_id]
1346
+ inputs_info = raw_node.get('inputs', [])
1347
+ expected_params = [
1348
+ inp.get("name") for inp in inputs_info
1349
+ if inp.get("type") not in ["Item", "Hidden_Item"]
1350
+ ]
1351
+
1352
+ provided_params = list(req.arguments.keys()) if req.arguments else []
1353
+
1354
+ # 检查参数名是否匹配
1355
+ if set(expected_params) == set(provided_params):
1356
+ # 参数名正确但值不匹配 - 不泄漏正确的值
1357
+ error_msg = f"Parameter names are correct, but the parameter values are incorrect. Please try using different parameter values."
1358
+ else:
1359
+ error_msg = f"Parameter names do not match. Expected parameter names: {expected_params}, you provided: {provided_params}."
1360
+
1361
+ return {
1362
+ "ok": False,
1363
+ "error": error_msg
1364
+ }
1365
+
1366
+ logger.info(f"✓ Item inputs match golden - node: {req.node_id}, activating item")
1367
+
1368
+ # 标记该 Item 已被正确使用
1369
+ item_node.if_success = True
1370
+
1371
+ # 将 golden_output_values 追加到 actual_outputs_history
1372
+ if item_node.golden_output_values:
1373
+ item_node.actual_outputs_history.append(dict(item_node.golden_output_values))
1374
+
1375
+ # 触发 ITEM 类型边的掉落
1376
+ newly_revealed = []
1377
+ for edge in scenario.edges:
1378
+ if edge.source_id == item_node.id and edge.connection_type == InterfaceType.ITEM:
1379
+ target_node = scenario.nodes[edge.target_id]
1380
+
1381
+ if not target_node.is_revealed:
1382
+ target_node.is_revealed = True
1383
+ # 构建基本节点信息(不包含详细内容)
1384
+ node_info = {
1385
+ "id": target_node.id,
1386
+ "type": target_node.type,
1387
+ "can_investigate": True,
1388
+ "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content"
1389
+ }
1390
+ # 只在 name 非空时添加
1391
+ # if target_node.name:
1392
+ # node_info["name"] = target_node.name
1393
+ # 只在 description 非空时添加
1394
+ if target_node.description:
1395
+ node_info["description"] = target_node.description
1396
+
1397
+ newly_revealed.append(node_info)
1398
+ logger.info(f"ITEM drop triggered: {target_node.id} (from use_item on {req.node_id})")
1399
+
1400
+ # 检查是否为 Win Node
1401
+ win_node_id = scenario.win_node_id
1402
+ is_win_node = (req.node_id == win_node_id)
1403
+
1404
+ # 构建返回结果
1405
+ result = {
1406
+ "ok": True,
1407
+ "message": "Item used successfully.",
1408
+ "content": item_node.golden_output_values if item_node.golden_output_values else None
1409
+ }
1410
+
1411
+ # 获取 narrative(如果存在)
1412
+ raw_nodes_data = RAW_NODES_DATA.get(case_id, {})
1413
+ if req.node_id in raw_nodes_data:
1414
+ narrative = raw_nodes_data[req.node_id].get('narrative')
1415
+ if narrative:
1416
+ result['narrative'] = narrative
1417
+
1418
+ if newly_revealed:
1419
+ result["newly_revealed"] = newly_revealed
1420
+
1421
+ # 不再主动提示胜利字符串,让模型自己判断
1422
+ # 如果是 Win Node,只记录日志
1423
+ if is_win_node:
1424
+ logger.info(f"Win node (Item) unlocked via use_item - case: {case_id}, node: {req.node_id}")
1425
+
1426
+ return result
1427
+
1428
+
1429
+ class SubmitAnswerRequest(BaseModel):
1430
+ answer: str = Field(..., description="The victory string to submit")
1431
+
1432
+ @app.post("/env/{case_id}/submit_answer")
1433
+ def submit_answer(case_id: str, req: SubmitAnswerRequest):
1434
+ """
1435
+ 提交答案接口
1436
+ 被测模型在获得胜利字符串提示后,需要调用此接口提交答案
1437
+ """
1438
+ logger.info(f"Submit answer request - case_id: {case_id}, answer: {req.answer}")
1439
+
1440
+ if case_id not in SCENARIOS:
1441
+ logger.error(f"Case not found: {case_id}")
1442
+ raise HTTPException(status_code=404, detail="Case not found")
1443
+
1444
+ scenario = SCENARIOS[case_id]
1445
+
1446
+ # 获取 win_node 的 golden_output_values
1447
+ if not scenario.win_node_id:
1448
+ logger.error(f"No win node defined for case: {case_id}")
1449
+ return {
1450
+ "ok": False,
1451
+ "error": "This case has no victory node defined"
1452
+ }
1453
+
1454
+ win_node = scenario.nodes.get(scenario.win_node_id)
1455
+ if not win_node:
1456
+ logger.error(f"Win node not found: {scenario.win_node_id}")
1457
+ return {
1458
+ "ok": False,
1459
+ "error": "Victory node does not exist"
1460
+ }
1461
+
1462
+ # 获取正确的胜利字符串(取第一个 golden_output_value)
1463
+ if win_node.golden_output_values:
1464
+ correct_answer = list(win_node.golden_output_values.values())[0]
1465
+ else:
1466
+ logger.error(f"Win node has no golden_output_values: {scenario.win_node_id}")
1467
+ return {
1468
+ "ok": False,
1469
+ "error": "Victory node has no correct answer"
1470
+ }
1471
+
1472
+ # 验证提交的答案
1473
+ if req.answer == correct_answer:
1474
+ logger.info(f"🎉 CORRECT ANSWER SUBMITTED - case: {case_id}, answer: {req.answer}")
1475
+ return {
1476
+ "ok": True,
1477
+ "is_win": True,
1478
+ "victory_message": f"🎉 Congratulations on successfully escaping the room! Your answer is correct: {req.answer}"
1479
+ }
1480
+ else:
1481
+ logger.info(f"❌ INCORRECT ANSWER SUBMITTED - case: {case_id}, submitted: {req.answer}, correct: {correct_answer}")
1482
+ return {
1483
+ "ok": True,
1484
+ "is_win": False,
1485
+ "error": f"The submitted answer is incorrect. You submitted: {req.answer}"
1486
+ }
1487
+
1488
+ if __name__ == "__main__":
1489
+
1490
+ uvicorn.run(app, host="0.0.0.0", port=8000)
tasks/agentescape-10-skeleton-ac5cd29c/environment/puzzle/upstream/simulator.py ADDED
The diff for this file is too large to render. See raw diff
 
tasks/agentescape-10-skeleton-ac5cd29c/environment/puzzle/worker.Dockerfile ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f
2
+ RUN apt-get update && apt-get install -y --no-install-recommends libseccomp2 && rm -rf /var/lib/apt/lists/*
3
+ COPY requirements.txt /app/requirements.txt
4
+ RUN pip install --no-cache-dir -r /app/requirements.txt
5
+ WORKDIR /app
6
+ COPY worker.py child.py /app/
7
+ COPY upstream/simulator.py /app/simulator.py
8
+ CMD ["uvicorn", "worker:app", "--host", "0.0.0.0", "--port", "8001", "--workers", "1", "--no-access-log"]
tasks/agentescape-10-skeleton-ac5cd29c/environment/puzzle/worker.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stateless Python tool worker. Never receives a scenario or reference values."""
2
+
3
+ import json
4
+ import os
5
+ import signal
6
+ import subprocess
7
+ import sys
8
+ import tempfile
9
+ import threading
10
+
11
+ from fastapi import FastAPI
12
+ from pydantic import BaseModel, ConfigDict
13
+
14
+ app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
15
+ lock = threading.Lock()
16
+
17
+
18
+ class Execution(BaseModel):
19
+ model_config = ConfigDict(extra="forbid", strict=True)
20
+ code: str
21
+
22
+
23
+ @app.get("/health")
24
+ def health():
25
+ return {"ok": True}
26
+
27
+
28
+ @app.post("/execute")
29
+ def execute(request: Execution):
30
+ if len(request.code.encode()) > 65536:
31
+ return {"stdout": "Error: code exceeds 64 KiB limit"}
32
+ with lock, tempfile.TemporaryDirectory(prefix="escape-code-") as directory:
33
+ os.chown(directory, 65534, 65534)
34
+ with tempfile.TemporaryFile() as output:
35
+ process = subprocess.Popen(
36
+ [sys.executable, "-I", "/app/child.py"],
37
+ stdin=subprocess.PIPE,
38
+ stdout=output,
39
+ stderr=subprocess.DEVNULL,
40
+ cwd=directory,
41
+ user=65534,
42
+ group=65534,
43
+ extra_groups=[],
44
+ start_new_session=True,
45
+ env={"PATH": "/usr/local/bin:/usr/bin:/bin"},
46
+ )
47
+ try:
48
+ process.communicate(
49
+ json.dumps({"code": request.code}).encode(), timeout=5
50
+ )
51
+ except subprocess.TimeoutExpired:
52
+ os.killpg(process.pid, signal.SIGKILL)
53
+ process.wait()
54
+ return {"stdout": "Error: Python execution timed out"}
55
+ finally:
56
+ # Also remove children still in the process group after normal exit.
57
+ try:
58
+ os.killpg(process.pid, signal.SIGKILL)
59
+ except ProcessLookupError:
60
+ pass
61
+ output.seek(0)
62
+ value = output.read(65537)
63
+ if len(value) > 65536 or process.returncode != 0:
64
+ return {
65
+ "stdout": "Error: Python execution exceeded a resource limit or failed"
66
+ }
67
+ try:
68
+ result = json.loads(value)
69
+ if not isinstance(result.get("stdout"), str):
70
+ raise ValueError("Invalid worker response")
71
+ return result
72
+ except (ValueError, AttributeError):
73
+ return {"stdout": "Error: Python execution returned invalid output"}
tasks/agentescape-10-skeleton-ac5cd29c/instruction.md ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Escape the room
2
+
3
+ Discover the victory string and submit it with `escape submit-answer`.
4
+ Start with `escape observe`. This returns the room, available information, visible entities, and victory node ID.
5
+
6
+ Use these commands (JSON responses):
7
+
8
+ ```sh
9
+ escape investigate NODE_ID
10
+ escape tool-call NODE_ID --arguments-json '{"parameter": "value"}'
11
+ escape use-item NODE_ID --arguments-json '{"parameter": "value"}'
12
+ escape submit-answer 'exact victory string'
13
+ escape state
14
+ ```
15
+
16
+ Investigate tools to learn their interfaces and clues. Investigate items for their contents; items requiring parameters use `use-item`. Tool calls can reveal new entities. A hidden-item hint means investigate that tool again. Use node IDs and parameter names exactly as returned. Carry outputs into subsequent calls; do not guess intermediate values. The victory string can be code, a number encoded as text, or other arbitrary text.
17
+
18
+ Only successful answer submission completes the task. Wrong submissions allow another attempt. You have **500 puzzle actions**; invalid actions count. `observe` and `state` do not count. This action limit differs from the original evaluator's model-turn limit. Do not reset or replace the environment.